From a94006b9daf604dcf743fef2fa3f8ef76e59ea1a Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:19:33 +0900 Subject: [PATCH 1/9] =?UTF-8?q?test(contracts):=20=EC=BF=A0=ED=82=A4=20?= =?UTF-8?q?=EC=93=B0=EA=B8=B0=20CSRF=EC=99=80=20realtime=20snapshot=20?= =?UTF-8?q?=EA=B2=80=EC=82=AC=EB=A5=BC=20method=EB=B3=84=20=ED=91=9C?= =?UTF-8?q?=EB=A1=9C=20=EA=B3=A0=EC=A0=95=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 V2에서 옮긴 두 조립 검사가 한 사례씩만 테스트된다. 쿠키 쓰기 CSRF 검사는 POST와 x-xsrf-token 한 쌍만 본다. 그래서 `!isRead`를 `method === "POST"`로 좁히거나, CSRF 헤더 이름 대신 "필수 헤더가 하나라도 있으면"으로 바꾸거나, x-csrf-token 허용을 지워도 테스트가 통과한다. realtime snapshot 바인딩(GET + SAFE·IDEMPOTENT)은 거절 사례가 없어 method 조건이나 retrySemantics 조건을 지워도 통과한다. 고른 방법 - rest-profile-contract: POST·PUT·PATCH·DELETE마다 CSRF 없는 쿠키 프로필과 x-tenant-context만 요구하는 쿠키 프로필을 거절하고, x-csrf-token과 x-xsrf-token을 각각 받는지 본다. GET·HEAD 쿠키 읽기는 CSRF 없이 된다. - realtime-stream-registry: 6 method × 4 retrySemantics 표를 CURSOR와 SNAPSHOT_ONLY 두 복구 모드로 돈다. 받는 조합은 GET×SAFE, GET×IDEMPOTENT 뿐이다. 행은 조립한 descriptor를 projectApiOperationRows로 뽑은 것에서 method와 retrySemantics만 바꾼다. 투영 칸 이름이 바뀌어도 이 표가 같이 깨진다. FE-REG-API 행이 없는 id도 거절한다. 버린 대안 - 손으로 쓴 행(fixture.ts)을 그대로 쓰기: 투영과 realtime 검사가 따로 바뀌는 것을 못 잡는다. 위험·한계 - 검사 코드는 바꾸지 않았다. 테스트만 더했다. - resumable upload 제어 요청의 쿠키 POST는 descriptor 밖이라 이 검사 범위가 아니다(영역 01). 검증 - 변이 7종을 하나씩 넣고 두 테스트 파일을 돌렸다. 모두 실패한다: M2(POST만), M3(아무 필수 헤더), H19(x-csrf-token 허용 삭제), M9(method 조건 삭제), M9b(method·retry 조건 삭제), S2(retry 조건 삭제), H21-PUT(GET 또는 PUT 허용). - 변이 없이 두 파일 47건 통과. check:types, eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-02 Refs: docs/reviews/2026-11-03-maturity-review/10-tests-fast-layers.md 10-03, 10-04 Refs: docs/reviews/2026-11-03-maturity-review/04-adapters-realtime.md 04-03 --- .../realtime/realtime-stream-registry.test.ts | 106 ++++++++++++++++++ tests/unit/rest-profile-contract.test.ts | 63 ++++++++++- 2 files changed, 164 insertions(+), 5 deletions(-) diff --git a/tests/unit/realtime/realtime-stream-registry.test.ts b/tests/unit/realtime/realtime-stream-registry.test.ts index dfb7ed62..f4c5f78d 100644 --- a/tests/unit/realtime/realtime-stream-registry.test.ts +++ b/tests/unit/realtime/realtime-stream-registry.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from "vitest"; +import { projectApiOperationRows } from "../../../src/contracts/api-operations.ts"; +import { + composeContractContributions, + type HttpMethod, + type RetrySemantics, +} from "../../../src/contracts/external-contract-runtime.ts"; import { createRealtimePolicyRegistry, defineEventTypeId, @@ -20,6 +26,7 @@ import { TEST_SCHEMA_CODECS, createTestRealtimeRegistry, } from "./fixture.ts"; +import { TEST_CONTRACT_CONTRIBUTION } from "../../helpers/external-contract-fixture.ts"; describe("realtime policy registry", () => { it("deep-snapshots registrations and resolves only stream-owned event types", () => { @@ -209,6 +216,105 @@ describe("realtime policy registry", () => { }); }); +/** + * 1103/04-03, 07-02, 10-04. Recovery sends the snapshot operation on every + * reconnect, so it must be a read that may be sent again: GET with SAFE or + * IDEMPOTENT. A HEAD carries no checkpoint body. The row is the FE-REG-API + * projection of a composed descriptor, so a renamed projected field breaks + * this table too. + */ +describe("realtime snapshot operation binding", () => { + const projected = projectApiOperationRows( + composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).contributions, + ); + const methods: readonly HttpMethod[] = [ + "GET", + "HEAD", + "POST", + "PUT", + "PATCH", + "DELETE", + ]; + const retries: readonly RetrySemantics[] = [ + "SAFE", + "IDEMPOTENT", + "KEYED", + "NEVER", + ]; + const register = ( + recovery: "CURSOR" | "SNAPSHOT_ONLY", + apiOperations: Readonly>, + ) => { + const baseline = createTestRealtimeRegistry(); + const stream = baseline.listStreams()[0]!; + return createRealtimePolicyRegistry({ + streams: [ + { + ...stream, + recovery: + recovery === "CURSOR" + ? stream.recovery + : { + mode: "SNAPSHOT_ONLY", + snapshotOperationId: "GET_REFERENCE_REALTIME_SNAPSHOT", + checkpointCodecId: "ReferenceRealtimeCheckpoint", + barrier: "CONNECT_BUFFER", + }, + }, + ], + eventTypes: [baseline.listEventTypes()[0]!], + bindings: { + ...bindings(), + apiOperations: apiOperations as ReturnType< + typeof bindings + >["apiOperations"], + }, + }); + }; + const snapshotRow = (method: HttpMethod, retrySemantics: RetrySemantics) => ({ + GET_REFERENCE_REALTIME_SNAPSHOT: { + ...projected.TEST_LIST_ENTITIES!, + operationId: "GET_REFERENCE_REALTIME_SNAPSHOT", + method, + retrySemantics, + }, + }); + const cases = methods.flatMap((method) => + retries.map((retrySemantics) => ({ + method, + retrySemantics, + accepted: + method === "GET" && + (retrySemantics === "SAFE" || retrySemantics === "IDEMPOTENT"), + })), + ); + + it.each(cases)( + "$method $retrySemantics as the snapshot operation: accepted=$accepted", + ({ method, retrySemantics, accepted }) => { + for (const recovery of ["CURSOR", "SNAPSHOT_ONLY"] as const) { + const install = () => + register(recovery, snapshotRow(method, retrySemantics)); + if (accepted) { + expect(install().findStream(STREAM_ID)?.recovery.mode).toBe(recovery); + } else { + expect(install, recovery).toThrow( + recovery === "CURSOR" + ? "Realtime cursor recovery profile is invalid." + : "Realtime snapshot recovery profile is invalid.", + ); + } + } + }, + ); + + it("refuses a snapshot operation id with no FE-REG-API row", () => { + expect(() => register("CURSOR", {})).toThrow( + "Realtime cursor recovery profile is invalid.", + ); + }); +}); + function bindings() { return { schemaCodecs: TEST_SCHEMA_CODECS, diff --git a/tests/unit/rest-profile-contract.test.ts b/tests/unit/rest-profile-contract.test.ts index 8451c7a3..b7c0abc7 100644 --- a/tests/unit/rest-profile-contract.test.ts +++ b/tests/unit/rest-profile-contract.test.ts @@ -63,26 +63,79 @@ describe("one installed REST auth profile registry", () => { * installed HTTP contract has to refuse it too. */ describe("cookie profiles on writes", () => { - const cookie = (authProfileId: string, csrf: readonly ("x-csrf-token" | "x-xsrf-token")[]) => ({ + const cookie = ( + authProfileId: string, + headers: readonly ("x-csrf-token" | "x-xsrf-token" | "x-tenant-context")[], + ) => ({ authProfileId, transport: "SAME_ORIGIN_COOKIE" as const, credentials: "include" as const, - allowedCredentialHeaders: [...csrf], - requiredCredentialHeaders: [...csrf], + allowedCredentialHeaders: [...headers], + requiredCredentialHeaders: [...headers], }); const registry = installRestAuthProfileRegistry({ ...REST_AUTH_PROFILES, COOKIE_READ: cookie("COOKIE_READ", []), COOKIE_WRITE: cookie("COOKIE_WRITE", ["x-xsrf-token"]), + COOKIE_CSRF: cookie("COOKIE_CSRF", ["x-csrf-token"]), + COOKIE_TENANT: cookie("COOKIE_TENANT", ["x-tenant-context"]), }); - const withProfile = (index: number, authProfileId: string) => { + const withProfile = ( + index: number, + authProfileId: string, + method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE", + ) => { const row = TEST_CONTRACT_CONTRIBUTION.http[index]!; return { ...TEST_CONTRACT_CONTRIBUTION, - http: [{ ...row, frontend: { ...row.frontend, authProfileId } }], + http: [ + { + contract: method ? { ...row.contract, method } : row.contract, + frontend: { ...row.frontend, authProfileId }, + }, + ], }; }; // TEST_CONTRACT_CONTRIBUTION.http: [list (GET), detail (GET), create (POST)] + const compose = ( + index: number, + authProfileId: string, + method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE", + ) => + composeContractContributions( + [withProfile(index, authProfileId, method)], + registry, + ).httpByOperationId.size; + + // 1103/07-02, 10-03. Every write method, not POST alone, and only the two + // CSRF header names count: another required header is not a CSRF proof. + it.each(["POST", "PUT", "PATCH", "DELETE"] as const)( + "refuses a %s whose cookie profile requires no CSRF header", + (method) => { + for (const authProfileId of ["COOKIE_READ", "COOKIE_TENANT"]) { + expect(() => compose(2, authProfileId, method)).toThrow( + expect.objectContaining({ + reason: `test-feature/TEST_CREATE_ENTITY: ${method} with cookie profile ${authProfileId} must require x-csrf-token or x-xsrf-token`, + }), + ); + } + }, + ); + + it.each(["POST", "PUT", "PATCH", "DELETE"] as const)( + "accepts a %s that requires x-csrf-token or x-xsrf-token", + (method) => { + expect(compose(2, "COOKIE_CSRF", method)).toBe(1); + expect(compose(2, "COOKIE_WRITE", method)).toBe(1); + }, + ); + + it.each(["GET", "HEAD"] as const)( + "accepts a cookie %s without a CSRF header", + (method) => { + expect(compose(0, "COOKIE_READ", method)).toBe(1); + }, + ); it("refuses a write whose cookie profile requires no CSRF header", () => { expect(() => From e4caafda3070da4d55802fc6ca8fcccfd672dbe6 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:21:04 +0900 Subject: [PATCH 2/9] =?UTF-8?q?fix(contracts)!:=20=EC=9D=BD=EA=B8=B0=20ope?= =?UTF-8?q?ration=EC=9D=80=20SAFE=C2=B7IDEMPOTENT=EC=9D=BC=20=EB=95=8C?= =?UTF-8?q?=EB=A7=8C=20=EC=A1=B0=EB=A6=BD=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 GET에 `retrySemantics: "KEYED"`(commandRecovery 없음)나 `"NEVER"`를 적어도 계약 조립이 통과하고 FE-REG-API 행에 그 값이 남는다. KEYED 복구 descriptor 검사가 쓰기 분기 안에만 있기 때문이다. 실행기는 이 GET을 쓰기로 보지 않아 재시도 없는 읽기로 돌린다. 매뉴얼은 "읽기(GET)는 늘 SAFE"라 적는다. V2 `defineRestOperation`은 조회에 SAFE·IDEMPOTENT만 허용했는데 V2 삭제 때 이 규칙이 V3로 옮겨지지 않았다(실험 R1). 고른 방법 assertHttpContract의 읽기 분기에서 GET·HEAD의 retrySemantics가 SAFE나 IDEMPOTENT가 아니면 method와 값을 담아 거절한다. realtime snapshot 바인딩이 요구하는 짝(GET + SAFE·IDEMPOTENT)과 같은 어휘다. 매뉴얼 02 3절 "틀리면"에 거절 문구를 더했다. 버린 대안 - 레지스트리 governance의 allowedValues로 막기: method별 허용값을 표현할 칸이 없고, 조립(부팅 경로)이 아니라 check:registries에서만 걸린다. 위험·한계 - GET·HEAD를 KEYED나 NEVER로 적은 다운스트림 descriptor는 부팅에서 계약 조립 실패가 된다. 템플릿 안에는 그런 descriptor가 없다(grep). - 쓰기의 SAFE 금지(03-03)는 이 커밋 범위가 아니다. 검증 - RED: tests/unit/external-contract-runtime.test.ts의 GET·HEAD × KEYED·NEVER 4건이 실패(조립 통과)했다. - GREEN: `run-vitest related src/contracts/external-contract-runtime.ts` 105파일 950건 통과. check:types, eslint, check:registries, verify:documentation 통과. BREAKING CHANGE: GET·HEAD operation의 retrySemantics가 KEYED나 NEVER이면 계약 조립이 CONTRACT_CONTRIBUTION_INVALID로 실패한다. SAFE(재시도 허용)나 IDEMPOTENT로 바꾼다. 재시도를 막으려면 frontend.retryBudget을 0으로 둔다. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-01 --- docs/manual/02-decision-tables.md | 1 + src/contracts/external-contract-runtime.ts | 11 +++++++ tests/unit/external-contract-runtime.test.ts | 33 ++++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 96fe6213..4972f5cf 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -102,6 +102,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 **틀리면** +- 읽기(GET·HEAD)에 `KEYED`나 `NEVER`를 적으면 계약 조립이 ` is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>`으로 거부한다. - `NEVER`에 `retryBudget`을 0보다 크게 주면 계약 조립이 `retry budget contradicts NEVER retry semantics`로 거부한다. - `KEYED`에 `commandRecovery`가 없으면 `KEYED commands require a recovery descriptor`로 거부한다. - 서버 보장과 다른 의미를 고른 것은 검사가 잡지 못한다. diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 4ac7ffec..2250fb90 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -508,6 +508,17 @@ function assertHttpContract( if (contract.requestBody !== "NONE") { fail(`${label}: read operations carry no request body`); } + // 1103/07-01 (c). The executor runs a read as a read whatever it is + // declared; KEYED or NEVER here only looks like a decision the executor + // never makes. A realtime snapshot binding reads the same pair. + if ( + contract.retrySemantics !== "SAFE" && + contract.retrySemantics !== "IDEMPOTENT" + ) { + fail( + `${label}: ${contract.method} is a read; its retrySemantics is SAFE or IDEMPOTENT, not ${contract.retrySemantics}`, + ); + } } else { if (!contract.commandEffect) { fail(`${label}: command operations require a command effect descriptor`); diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index ba47667a..3e9f8943 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -124,6 +124,39 @@ describe("write operation rules", () => { ).toBe("test-feature/TEST_LIST_ENTITIES: read operations carry no command descriptors"); }); + // 1103/07-01 (c). The KEYED recovery check sits in the write branch, so a + // GET written as KEYED or NEVER used to compose and run as a read with no + // retry. A read is SAFE or IDEMPOTENT (docs/manual/02-decision-tables.md 3절). + it.each([ + ["GET", "KEYED"], + ["GET", "NEVER"], + ["HEAD", "KEYED"], + ["HEAD", "NEVER"], + ] as const)("rejects a %s declared %s", (method, retrySemantics) => { + expect( + reasonFor({ + ...listRow, + contract: { ...listRow.contract, method, retrySemantics }, + frontend: { ...listRow.frontend, retryBudget: 0 }, + }), + ).toBe( + `test-feature/TEST_LIST_ENTITIES: ${method} is a read; its retrySemantics is SAFE or IDEMPOTENT, not ${retrySemantics}`, + ); + }); + + it.each(["SAFE", "IDEMPOTENT"] as const)("composes a GET declared %s", (retrySemantics) => { + expect( + composeContractContributions([ + contribution("read-rule", [ + { + ...listRow, + contract: { ...listRow.contract, retrySemantics }, + } as InstalledContractContribution["http"][number], + ]), + ]).httpByOperationId.size, + ).toBe(1); + }); + it("requires a recovery descriptor on a KEYED command", () => { expect( reasonFor({ From 08ed0a088d023656f40c670aa7c4740a718bec59 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:24:41 +0900 Subject: [PATCH 3/9] =?UTF-8?q?fix(contracts)!:=20FE-REG-API=20=ED=96=89?= =?UTF-8?q?=EC=97=90=20status=20=EB=AA=A9=EB=A1=9D=C2=B7=EC=83=81=ED=95=9C?= =?UTF-8?q?=C2=B7=EC=9E=AC=EC=8B=9C=EB=8F=84=20=EC=98=88=EC=82=B0=C2=B7?= =?UTF-8?q?=EA=B2=80=EC=A6=9D=20=EC=83=9D=EB=9E=B5=EC=9D=84=20=EB=8B=B4?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 V2 행과 V2/V3 parity 테스트를 지운 뒤 FE-REG-API 행은 descriptor에서 12칸만 뽑는다. acceptedStatuses, emptyBodyStatuses, 바이트 상한, 마감, retryBudget, traffic, commandEffect, commandRecovery, 검증 생략 표시는 행에 없다. 그래서 생성 API의 acceptedStatuses를 [200, 201]에서 [201]로 줄여도 check:registries가 통과한다(실험 X2). 이전 커밋 d99301b에서는 같은 변경이 breaking 증거 누락으로 실패했다. 응답 상한·마감 변경은 기록에서 사라졌고 (X3·X6), problemSchema는 breaking 칸이 아니어서 problem 검증기 id를 바꿔도 behavior-change로 통과했다(X4). 짝 백엔드는 생성에 201, 본문 없는 응답에 204를 쓴다. 이 status를 빼면 배포 뒤 그 API가 모두 실패한다. 고른 방법 - projectApiOperationRows가 함수 밖의 descriptor 값을 모두 뽑는다: acceptedStatuses, emptyBodyStatuses, unvalidated(검증을 건너뛰는 검증기 칸 이름: input·output·problem), requestByteLimit, responseByteLimit, totalDeadlineMs, retryBudget, traffic, commandEffect, commandRecovery. - commandEffect는 함수를 빼고 데이터만 남긴다: classifyStatus가 있는지 (classifiesStatus)와, descriptor가 이름을 붙였을 때만 refusedBeforeWrite 목록. refusedBeforeWrite는 다른 작업에서 더해지는 선택 칸이라 구조로 읽고, 없으면 행에도 없다. - governance: problemSchema와 unvalidated를 breakingFields에 넣는다. status 배열은 breakingFields에 넣지 않는다. 분류기가 배열에서 값이 빠지면 이미 allowed-value-removed breaking으로 본다. breakingFields에 넣으면 status를 더하는 것(전에 받던 응답을 모두 계속 받는 변경)까지 증거를 요구한다. 숫자 칸·traffic·command 칸은 behavior-change로 기록한다. - 매뉴얼 01 9단계에 무엇이 breaking이고 무엇이 behavior-change인지, descriptor 함수는 행에 없다는 것을 적었다. 버린 대안 - descriptor 전체(함수 제외)를 투영: policyId·diagnosticsOperation까지 기준선이 흔들려 리뷰 잡음만 는다. 둘은 wire 값이 아니다. - V2/V3 parity 테스트 부활: 사본이 다시 둘이 된다. - 숫자 칸 감소를 breaking으로: 분류기에 방향 규칙이 없고, 상한·마감 조정은 자주 하는 운영 값이다. 기록만 하고 PR에서 본다. 위험·한계 - governance 계약(requiredFields·fieldTypes·breakingFields)이 바뀌어 기준선을 다시 승인했다. 다운스트림은 동기화 때 재승인 1회가 필요하다. - FE-REG-SCHEMA에 problem 스키마 행이 없어 problemSchema는 참조 검사 대상이 아니다. breaking 칸으로만 잠근다. - classifyProblem이 무엇을 NOT_APPLIED로 보는지는 함수라 기록되지 않는다. 검증 - 기준선 재승인 뒤 실험 재실행(check:registries): X2 [200,201]->[201] 실패(acceptedStatuses:allowed-value-removed 증거 누락), X4 problem 검증기 id 변경 실패(problemSchema:field-changed 3건), X5 GET 출력 검증기 생략 실패(unvalidated:field-changed), X3 응답 상한·X6 마감 변경은 behavior-change로 통과하고 스냅샷에 남는다. - tests/unit/api-operation-rows.test.ts: 새 칸 고정, refusedBeforeWrite 있음·없음, governance JSON으로 분류한 8가지 변경. - run-vitest related(api-operations.ts, governance) 21파일 156건, registry 테스트 4파일 63건, check:registries:compatibility-fixtures, check:types, eslint, verify:documentation 통과. BREAKING CHANGE: FE-REG-API governance 계약이 바뀌어 다운스트림의 check:registries가 FE-REG-API:$contract:* contract-field-changed로 실패한다. 동기화 뒤 REGISTRY_BASELINE_OWNER·REGISTRY_BASELINE_REASON을 주고 update:registry-baseline을 한 번 돌린다. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-01 Refs: docs/reviews/2026-11-03-maturity-review/README.md 3절 --- .../contracts/registry-baseline.approval.json | 6 +- config/contracts/registry-baseline.json | 105 ++++++++- config/contracts/registry-governance.json | 28 ++- docs/manual/01-add-a-feature.md | 6 +- src/contracts/api-operations.ts | 87 +++++++ tests/unit/api-operation-rows.test.ts | 223 ++++++++++++++++++ tests/unit/realtime/fixture.ts | 10 + 7 files changed, 451 insertions(+), 14 deletions(-) diff --git a/config/contracts/registry-baseline.approval.json b/config/contracts/registry-baseline.approval.json index 7f1f1b88..fad51b0f 100644 --- a/config/contracts/registry-baseline.approval.json +++ b/config/contracts/registry-baseline.approval.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "snapshotDigest": "16f727424579279e0ef810620f672a8a9d74de6b71e3e9ce37ab07a82f645588", + "snapshotDigest": "96e048bf63f739ba7acb9238e77b4b36abaf9c1fc3e40ea2f2f4a4862e0127b9", "owner": "DongHyeonka", - "reason": "2026-11-03 사용자 승인('둘 다 지워'): V2 API 행 제거. FE-REG-API 행은 V3 descriptor에서 뽑은 projection(operationId·featureId·method·path·authProfileId·retrySemantics·requestBody·responseBody·responseEnvelope·request/response/problemSchema)이다. V3 descriptor가 쓰지 않는 참조 기능 NoRequest 스키마 행 제거", - "approvedAt": "2026-11-03T12:22:21.004Z" + "reason": "1103/07-01 FE-REG-API rows carry descriptor wire values (statuses, limits, deadline, retry budget, traffic, command data, validation skip); problemSchema and unvalidated are breaking fields", + "approvedAt": "2026-11-04T11:23:02.382Z" } diff --git a/config/contracts/registry-baseline.json b/config/contracts/registry-baseline.json index f01ec895..01e176d5 100644 --- a/config/contracts/registry-baseline.json +++ b/config/contracts/registry-baseline.json @@ -341,7 +341,17 @@ "responseEnvelope", "requestSchema", "responseSchema", - "problemSchema" + "problemSchema", + "acceptedStatuses", + "emptyBodyStatuses", + "unvalidated", + "requestByteLimit", + "responseByteLimit", + "totalDeadlineMs", + "retryBudget", + "traffic", + "commandEffect", + "commandRecovery" ], "fieldTypes": { "operationId": "string", @@ -355,7 +365,17 @@ "responseEnvelope": "string", "requestSchema": "string", "responseSchema": "string", - "problemSchema": "string" + "problemSchema": "string", + "acceptedStatuses": "array", + "emptyBodyStatuses": "array", + "unvalidated": "array", + "requestByteLimit": "integer", + "responseByteLimit": "integer", + "totalDeadlineMs": "integer", + "retryBudget": "integer", + "traffic": "object|null", + "commandEffect": "object|null", + "commandRecovery": "object|null" }, "uniqueFields": [ "operationId" @@ -412,51 +432,110 @@ "responseBody", "responseEnvelope", "requestSchema", - "responseSchema" + "responseSchema", + "problemSchema", + "unvalidated" ] }, "rows": { "CREATE_REFERENCE_RESOURCE": { + "acceptedStatuses": [ + 200, + 201 + ], "authProfileId": "EXTERNAL_BEARER", + "commandEffect": { + "classifiesStatus": true + }, + "commandRecovery": { + "mode": "IDEMPOTENCY_REPLAY", + "operationIdentityField": "idempotencyKey" + }, + "emptyBodyStatuses": [], "featureId": "reference-feature", "method": "POST", "operationId": "CREATE_REFERENCE_RESOURCE", "path": "/api/reference-resources", "problemSchema": "ReferenceProblem", "requestBody": "JSON", + "requestByteLimit": 32768, "requestSchema": "CreateReferenceResourceCommand", "responseBody": "REQUIRED_JSON", + "responseByteLimit": 32768, "responseEnvelope": "NONE", "responseSchema": "ReferenceResourcePayload", - "retrySemantics": "KEYED" + "retryBudget": 0, + "retrySemantics": "KEYED", + "totalDeadlineMs": 10000, + "traffic": { + "maxConcurrentRequests": 1, + "maxPhysicalRequests": 1, + "maxQueuedRequests": 0, + "maxRetries": 0 + }, + "unvalidated": [] }, "GET_REFERENCE_RESOURCE": { + "acceptedStatuses": [ + 200 + ], "authProfileId": "EXTERNAL_BEARER", + "commandEffect": null, + "commandRecovery": null, + "emptyBodyStatuses": [], "featureId": "reference-feature", "method": "GET", "operationId": "GET_REFERENCE_RESOURCE", "path": "/api/reference-resources/{resourceId}", "problemSchema": "ReferenceProblem", "requestBody": "NONE", + "requestByteLimit": 0, "requestSchema": "ReferenceResourceParams", "responseBody": "REQUIRED_JSON", + "responseByteLimit": 32768, "responseEnvelope": "NONE", "responseSchema": "ReferenceResourcePayload", - "retrySemantics": "SAFE" + "retryBudget": 2, + "retrySemantics": "SAFE", + "totalDeadlineMs": 10000, + "traffic": { + "maxConcurrentRequests": 1, + "maxPhysicalRequests": 3, + "maxQueuedRequests": 0, + "maxRetries": 2 + }, + "unvalidated": [] }, "LIST_REFERENCE_RESOURCES": { + "acceptedStatuses": [ + 200 + ], "authProfileId": "EXTERNAL_BEARER", + "commandEffect": null, + "commandRecovery": null, + "emptyBodyStatuses": [], "featureId": "reference-feature", "method": "GET", "operationId": "LIST_REFERENCE_RESOURCES", "path": "/api/reference-resources", "problemSchema": "ReferenceProblem", "requestBody": "NONE", + "requestByteLimit": 0, "requestSchema": "ReferenceResourceListQuery", "responseBody": "REQUIRED_JSON", + "responseByteLimit": 262144, "responseEnvelope": "NONE", "responseSchema": "ReferenceResourceListPayload", - "retrySemantics": "SAFE" + "retryBudget": 2, + "retrySemantics": "SAFE", + "totalDeadlineMs": 10000, + "traffic": { + "maxConcurrentRequests": 1, + "maxPhysicalRequests": 3, + "maxQueuedRequests": 0, + "maxRetries": 2 + }, + "unvalidated": [] } } }, @@ -565,7 +644,7 @@ "registryId": "FE-REG-ENV", "owner": "feature-frontend-env-runtime-config-contract", "source": "src/contracts/env.ts", - "rowCount": 16, + "rowCount": 18, "contract": { "requiredFields": [ "phase", @@ -619,6 +698,12 @@ "phase": "runtime", "required": true }, + "BUILD_ID": { + "classification": "public-metadata", + "defaultValue": null, + "phase": "runtime", + "required": false + }, "CAPABILITY_OVERRIDES": { "classification": "public", "defaultValue": null, @@ -643,6 +728,12 @@ "phase": "runtime", "required": false }, + "RELEASE_ID": { + "classification": "public-metadata", + "defaultValue": null, + "phase": "runtime", + "required": false + }, "RELEASE_MANIFEST_URL": { "classification": "public", "defaultValue": "/release-manifest.json", diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index 23aa7522..71add621 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -149,7 +149,17 @@ "responseEnvelope", "requestSchema", "responseSchema", - "problemSchema" + "problemSchema", + "acceptedStatuses", + "emptyBodyStatuses", + "unvalidated", + "requestByteLimit", + "responseByteLimit", + "totalDeadlineMs", + "retryBudget", + "traffic", + "commandEffect", + "commandRecovery" ], "fieldTypes": { "operationId": "string", @@ -163,7 +173,17 @@ "responseEnvelope": "string", "requestSchema": "string", "responseSchema": "string", - "problemSchema": "string" + "problemSchema": "string", + "acceptedStatuses": "array", + "emptyBodyStatuses": "array", + "unvalidated": "array", + "requestByteLimit": "integer", + "responseByteLimit": "integer", + "totalDeadlineMs": "integer", + "retryBudget": "integer", + "traffic": "object|null", + "commandEffect": "object|null", + "commandRecovery": "object|null" }, "uniqueFields": [ "operationId" @@ -224,7 +244,9 @@ "responseBody", "responseEnvelope", "requestSchema", - "responseSchema" + "responseSchema", + "problemSchema", + "unvalidated" ] }, { diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 8382286d..f9a74029 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -497,7 +497,10 @@ projectRequest: (input) => Object.freeze({ ② **기준** - 라우트, operation, 스키마, 무효화 topic·namespace·edge를 **더하기만** 하면 기준선은 바뀌지 않는다. -- 행을 **빼거나 바꾸면** breaking 변경이다. 둘 중 하나를 한다. +- 행을 **빼거나** breaking 칸을 **바꾸면** breaking 변경이다. breaking 칸은 `config/contracts/registry-governance.json`의 `breakingFields`다. 배열 칸에서 값을 빼는 것도 breaking이다. + - FE-REG-API 예: 생성 API의 `acceptedStatuses`를 `[200, 201]`에서 `[201]`로 줄이거나, `problemSchema`를 바꾸거나, 검증기를 `unvalidatedPayload`로 바꾸면(`unvalidated` 칸) breaking이다. + - status를 더하는 것, 바이트 상한·마감·`retryBudget`·`traffic`·`commandEffect`·`commandRecovery`를 바꾸는 것은 behavior-change다. 통과하지만 스냅샷 diff(`artifacts/quality/registries.json`의 `compatibility.changes`)에 남는다. PR에서 본다. +- breaking 변경이면 둘 중 하나를 한다. - `REGISTRY_BASELINE_OWNER`, `REGISTRY_BASELINE_REASON`을 주고 `corepack pnpm update:registry-baseline`을 돌린다. - 또는 `config/contracts/registry-change-evidence.json`에 항목을 더한다. 칸 설명은 `docs/operations/ci-quality-gates.md`에 있다. - a11y 기록은 생성 명령이 pending으로 만든다. 서명은 릴리스 전에 사람이 한다([03 문서](03-outside-feature-folder.md)). @@ -510,6 +513,7 @@ projectRequest: (input) => Object.freeze({ - 메시지: `breaking change missing evidence: ` - 지금 diff와 맞지 않는 증거 행이 남으면 `stale breaking evidence : ...`로 실패한다. - **못 잡음**: 사람이 서명하지 않은 a11y 기록은 merge 게이트를 통과한다. 릴리스 게이트 FE-GATE-028이 막는다. +- **못 잡음**: descriptor의 함수는 행에 없다. `classifyProblem`·`classifyStatus`가 무엇을 `NOT_APPLIED`로 보는지, `projectRequest`가 무엇을 보내는지는 PR에서 본다. ④ **쓸 스킬**: `documentation-and-adrs`, `deprecation-and-migration` diff --git a/src/contracts/api-operations.ts b/src/contracts/api-operations.ts index 4d7b496c..ae9bc4c3 100644 --- a/src/contracts/api-operations.ts +++ b/src/contracts/api-operations.ts @@ -1,16 +1,40 @@ import type { + CommandEffectDescriptor, + CommandRecoveryDescriptor, HttpMethod, InstalledContractContribution, InstalledHttpContract, ResponseEnvelope, RetrySemantics, + RuntimeValidator, } from "./external-contract-runtime.ts"; +import type { TrafficBudget } from "../platform/traffic/traffic-budget.ts"; + +/** + * 1103/07-01. The data of a command effect descriptor. Its classifiers are + * behaviour and stay out of the row; what the row keeps is whether the + * descriptor answers 401, 403 and 429 itself, and the problem codes it names + * as refused before any write when it names them. + */ +export type ApiCommandEffectRow = Readonly<{ + classifiesStatus: boolean; + refusedBeforeWrite?: readonly string[]; +}>; + +/** A validator slot whose validation is skipped (`unvalidatedPayload`). */ +export type ApiUnvalidatedSlot = "input" | "output" | "problem"; /** * FE-REG-API. The governed row of one installed HTTP operation, projected * from its V3 descriptor (`InstalledHttpContract`). A feature writes the * operation once, in its contract contribution; `check:registries` compares * these rows with the approved baseline. + * + * 1103/07-01. The row carries every wire-facing value of the descriptor: + * what is sent and accepted, the bounds, and the retry and command data. The + * governance grades a change (`config/contracts/registry-governance.json`). + * Only functions stay out (`projectRequest`, the validators' parsing, the + * command effect classifiers), with the policy and diagnostics names. */ export type ApiOperationRow = Readonly<{ operationId: string; @@ -25,6 +49,17 @@ export type ApiOperationRow = Readonly<{ requestSchema: string; responseSchema: string; problemSchema: string; + acceptedStatuses: readonly number[]; + emptyBodyStatuses: readonly number[]; + /** Validator slots that skip validation by name; `[]` when all validate. */ + unvalidated: readonly ApiUnvalidatedSlot[]; + requestByteLimit: number; + responseByteLimit: number; + totalDeadlineMs: number; + retryBudget: 0 | 1 | 2; + traffic: TrafficBudget | null; + commandEffect: ApiCommandEffectRow | null; + commandRecovery: CommandRecoveryDescriptor | null; }>; /** @@ -50,8 +85,60 @@ export function projectApiOperationRows( requestSchema: contract.inputValidator.schemaId, responseSchema: contract.outputValidator.schemaId, problemSchema: contract.problemValidator.schemaId, + acceptedStatuses: Object.freeze([...contract.acceptedStatuses]), + emptyBodyStatuses: Object.freeze([...contract.emptyBodyStatuses]), + unvalidated: unvalidatedSlots({ + input: contract.inputValidator, + output: contract.outputValidator, + problem: contract.problemValidator, + }), + requestByteLimit: frontend.requestByteLimit, + responseByteLimit: frontend.responseByteLimit, + totalDeadlineMs: frontend.totalDeadlineMs, + retryBudget: frontend.retryBudget, + traffic: + frontend.traffic === undefined + ? null + : Object.freeze({ + maxPhysicalRequests: frontend.traffic.maxPhysicalRequests, + maxRetries: frontend.traffic.maxRetries, + maxConcurrentRequests: frontend.traffic.maxConcurrentRequests, + maxQueuedRequests: frontend.traffic.maxQueuedRequests, + }), + commandEffect: commandEffectRow(contract.commandEffect), + commandRecovery: + contract.commandRecovery === null + ? null + : Object.freeze({ ...contract.commandRecovery }), }); } } return Object.freeze(rows); } + +/** The same marker rule as `listUnvalidatedPayloads`: any marker counts. */ +function unvalidatedSlots( + validators: Readonly>>, +): readonly ApiUnvalidatedSlot[] { + return Object.freeze( + (Object.keys(validators) as ApiUnvalidatedSlot[]).filter( + (slot) => validators[slot].validation !== undefined, + ), + ); +} + +function commandEffectRow( + effect: CommandEffectDescriptor | null, +): ApiCommandEffectRow | null { + if (effect === null) return null; + // Read structurally: a descriptor that does not name refused codes has no + // such list, and the row then has no such field. + const refused: unknown = (effect as Readonly<{ refusedBeforeWrite?: unknown }>) + .refusedBeforeWrite; + return Object.freeze({ + classifiesStatus: typeof effect.classifyStatus === "function", + ...(Array.isArray(refused) + ? { refusedBeforeWrite: Object.freeze(refused.map(String)) } + : {}), + }); +} diff --git a/tests/unit/api-operation-rows.test.ts b/tests/unit/api-operation-rows.test.ts index fac6639b..fc597cd5 100644 --- a/tests/unit/api-operation-rows.test.ts +++ b/tests/unit/api-operation-rows.test.ts @@ -1,13 +1,22 @@ +import { readFile } from "node:fs/promises"; + import { describe, expect, it } from "vitest"; +import { + canonicalizeRegistryValue, + diffRegistrySnapshots, +} from "../../scripts/lib/registry-compatibility.ts"; import { projectApiOperationRows } from "../../src/contracts/api-operations.ts"; import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts"; +import { unvalidatedPayload } from "../../src/contracts/unvalidated-payload.ts"; import { API_OPERATIONS, COMPOSED_CONTRACT_CONTRIBUTIONS, } from "../../src/features/loaded-feature-runtimes.ts"; import { + TEST_CLASSIFIED_CREATE_HTTP_CONTRACT, TEST_CONTRACT_CONTRIBUTION, + TEST_CREATE_HTTP_CONTRACT, TEST_LIST_HTTP_CONTRACT, } from "../helpers/external-contract-fixture.ts"; @@ -40,11 +49,80 @@ describe("FE-REG-API rows projected from HTTP descriptors", () => { requestSchema: "TestEntityListQuery", responseSchema: "TestEntityListPayload", problemSchema: "TestProblem", + acceptedStatuses: [200], + emptyBodyStatuses: [], + unvalidated: [], + requestByteLimit: 0, + responseByteLimit: 32_768, + totalDeadlineMs: 10_000, + retryBudget: 2, + traffic: null, + commandEffect: null, + commandRecovery: null, }); expect(rows.TEST_CREATE_ENTITY).toMatchObject({ method: "POST", retrySemantics: "KEYED", requestBody: "JSON", + acceptedStatuses: [201], + retryBudget: 0, + commandEffect: { classifiesStatus: false }, + commandRecovery: { + mode: "IDEMPOTENCY_REPLAY", + operationIdentityField: "idempotencyKey", + }, + }); + expect(rows.TEST_CREATE_ENTITY?.commandEffect).not.toHaveProperty( + "refusedBeforeWrite", + ); + }); + + it("carries the command effect data and the validator slots that skip validation", () => { + const traffic = Object.freeze({ + maxPhysicalRequests: 2, + maxRetries: 1, + maxConcurrentRequests: 1, + maxQueuedRequests: 0, + }); + const rows = projectApiOperationRows( + composeContractContributions([ + { + ...TEST_CONTRACT_CONTRIBUTION, + http: [ + { + ...TEST_LIST_HTTP_CONTRACT, + contract: { + ...TEST_LIST_HTTP_CONTRACT.contract, + outputValidator: unvalidatedPayload( + "TestEntityListPayload", + "typed by the package", + ), + }, + frontend: { ...TEST_LIST_HTTP_CONTRACT.frontend, traffic }, + }, + { + ...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT, + contract: { + ...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract, + // A descriptor that names the codes refused before any write. + commandEffect: { + ...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract.commandEffect, + refusedBeforeWrite: ["VALIDATION_FAILED", "CONFLICT"], + }, + }, + }, + ] as never, + }, + ]).contributions, + ); + + expect(rows.TEST_LIST_ENTITIES).toMatchObject({ + unvalidated: ["output"], + traffic, + }); + expect(rows.TEST_CREATE_ENTITY?.commandEffect).toEqual({ + classifiesStatus: true, + refusedBeforeWrite: ["VALIDATION_FAILED", "CONFLICT"], }); }); @@ -78,3 +156,148 @@ describe("FE-REG-API rows projected from HTTP descriptors", () => { ); }); }); + +/** + * 1103/07-01. The wire values of a descriptor are graded by the governance + * the repository ships, not only recorded: narrowing what the frontend + * accepts, or changing how it validates, needs baseline evidence. + */ +describe("FE-REG-API compatibility of descriptor wire values", () => { + async function snapshotOf( + rows: Readonly>, + ): Promise>> { + const governance = JSON.parse( + await readFile("config/contracts/registry-governance.json", "utf8"), + ) as { + registries: Array<{ + registryId: string; + breakingFields: string[]; + fieldTypes: Record; + }>; + }; + const api = governance.registries.find( + (registry) => registry.registryId === "FE-REG-API", + )!; + return { + registries: [ + { + registryId: "FE-REG-API", + contract: { + breakingFields: api.breakingFields, + fieldTypes: api.fieldTypes, + }, + rows: canonicalizeRegistryValue(rows), + }, + ], + }; + } + const rowsWith = ( + contract: Partial = {}, + frontend: Partial = {}, + ) => + projectApiOperationRows( + composeContractContributions([ + { + ...TEST_CONTRACT_CONTRIBUTION, + http: [ + { + contract: { + ...TEST_CREATE_HTTP_CONTRACT.contract, + acceptedStatuses: [200, 201], + emptyBodyStatuses: [201], + ...contract, + }, + frontend: { ...TEST_CREATE_HTTP_CONTRACT.frontend, ...frontend }, + }, + ] as never, + }, + ]).contributions, + ); + async function changesFor(after: Readonly>) { + const diff = diffRegistrySnapshots( + await snapshotOf(rowsWith()), + await snapshotOf(after), + ); + return diff.changes.map(({ changeId, impact }) => `${changeId} ${impact}`); + } + + it.each([ + [ + "a narrowed status list", + { acceptedStatuses: [201] }, + {}, + [ + "FE-REG-API:TEST_CREATE_ENTITY:acceptedStatuses:allowed-value-removed breaking", + ], + ], + [ + "a narrowed empty-body list", + { emptyBodyStatuses: [] }, + {}, + [ + "FE-REG-API:TEST_CREATE_ENTITY:emptyBodyStatuses:allowed-value-removed breaking", + ], + ], + [ + "another problem schema", + { + problemValidator: { + ...TEST_CREATE_HTTP_CONTRACT.contract.problemValidator, + schemaId: "OtherProblem", + }, + }, + {}, + ["FE-REG-API:TEST_CREATE_ENTITY:problemSchema:field-changed breaking"], + ], + [ + "an output whose validation is skipped", + { outputValidator: unvalidatedPayload("TestEntityPayload", "trusted") }, + {}, + ["FE-REG-API:TEST_CREATE_ENTITY:unvalidated:field-changed breaking"], + ], + [ + "a widened status list", + { acceptedStatuses: [200, 201, 202] }, + {}, + [ + "FE-REG-API:TEST_CREATE_ENTITY:acceptedStatuses:field-changed behavior-change", + ], + ], + [ + "a larger response limit and a longer deadline", + {}, + { responseByteLimit: 8_388_608, totalDeadlineMs: 60_000 }, + [ + "FE-REG-API:TEST_CREATE_ENTITY:responseByteLimit:field-changed behavior-change", + "FE-REG-API:TEST_CREATE_ENTITY:totalDeadlineMs:field-changed behavior-change", + ], + ], + [ + "a traffic policy", + {}, + { + traffic: { + maxPhysicalRequests: 1, + maxRetries: 0, + maxConcurrentRequests: 1, + maxQueuedRequests: 0, + }, + }, + ["FE-REG-API:TEST_CREATE_ENTITY:traffic:field-changed behavior-change"], + ], + [ + "a status classifier", + { + commandEffect: TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract.commandEffect, + }, + {}, + [ + "FE-REG-API:TEST_CREATE_ENTITY:commandEffect:field-changed behavior-change", + ], + ], + ] as const)("grades %s", async (_name, contract, frontend, expected) => { + expect(await changesFor(rowsWith(contract as never, frontend as never))).toEqual( + expected, + ); + }); +}); diff --git a/tests/unit/realtime/fixture.ts b/tests/unit/realtime/fixture.ts index 372db896..fe64d75c 100644 --- a/tests/unit/realtime/fixture.ts +++ b/tests/unit/realtime/fixture.ts @@ -115,6 +115,16 @@ const snapshotOperation: ApiOperationRow = Object.freeze({ requestSchema: "NoRequest", responseSchema: "ReferenceRealtimeCheckpoint", problemSchema: "ReferenceRealtimeProblem", + acceptedStatuses: [200], + emptyBodyStatuses: [], + unvalidated: [], + requestByteLimit: 0, + responseByteLimit: 32_768, + totalDeadlineMs: 10_000, + retryBudget: 2, + traffic: null, + commandEffect: null, + commandRecovery: null, }); export const TEST_API_OPERATIONS = Object.freeze({ From a144b575e5d6c052eba8bf12cfeb238fea1bbcbc Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:27:35 +0900 Subject: [PATCH 4/9] =?UTF-8?q?fix(contracts):=20FE-REG-ENV=20=EB=9F=B0?= =?UTF-8?q?=ED=83=80=EC=9E=84=20=ED=96=89=EC=9D=98=20=ED=95=84=EC=88=98=20?= =?UTF-8?q?=EC=97=AC=EB=B6=80=C2=B7=EA=B8=B0=EB=B3=B8=EA=B0=92=EC=9D=84=20?= =?UTF-8?q?=EC=8A=A4=ED=82=A4=EB=A7=88=EC=99=80=20=EB=A7=9E=EC=B6=98?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 FE-REG-ENV 런타임 행 13개 중 5개의 required·defaultValue가 실제 V2 runtime config 스키마(runtimeConfigV2ArtifactSchema)와 다르다. - TELEMETRY_ENABLED: 행 기본값 false / 스키마 필수, 기본값 없음 - AUTH_MODE: 행 기본값 "external" / 스키마 기본값 없음 - RELEASE_MANIFEST_URL: 행 required true / 스키마 선택(기본값 있음) - CAPABILITY_OVERRIDES: 행 기본값 null / 스키마 기본값 네 항목 DEFAULT - FEATURE_OVERRIDES: 행 기본값 null / 스키마 기본값 {} d0414c8의 테스트는 스키마 키마다 행이 있는지만 본다. 스키마에 없는 런타임 행도, 값이 다른 행도 통과한다. 이 레지스트리는 기준선 호환 검사 대상이라 틀린 값이 계약으로 굳는다. AUTH_MODE를 빼도 external이 된다고 읽으면 부팅이 스키마 오류로 멈춘다. 고른 방법 - env-registry-coverage에 두 방향을 더한다. 스키마가 읽지 않는 런타임 행은 실패한다. 각 행의 required·defaultValue는 스키마 필드에 undefined를 넣은 결과(실패 = 필수·기본값 없음, 성공 = 선택·그 값)와 같아야 한다. 차이는 키·행 값·스키마 값을 한 줄로 보인다. 제품 키(PRODUCT_*)도 같은 검사를 받는다. - 5개 행을 스키마에 맞춘다. 두 override 기본값은 객체라 governance의 defaultValue 타입에 object를 더했다. - ENV_REGISTRY 주석에 두 칸의 뜻(null = 스키마가 기본값을 주지 않음)을 적었다. 버린 대안 - 행의 required·defaultValue를 스키마에서 계산해 채우기: 손으로 맞출 일이 사라지지만 env.ts가 zod 스키마를 import해야 한다. env.ts는 부팅 경로 (getBuildConfig)에 있어 초기 청크에 zod 스키마가 끌려 들어간다. 위험·한계 - RELEASE_MANIFEST_URL required true→false는 breaking 칸 변경이고 governance fieldTypes도 바뀌어 기준선을 다시 승인했다. - 스키마 superRefine의 조건부 필수(TELEMETRY_ENABLED면 TELEMETRY_ENDPOINT)는 행에 표현하지 않는다. 검증 - RED: 새 대조 테스트가 위 5개 행을 정확히 보고하며 실패했다. - GREEN: env-registry-coverage 3건 통과. 변이: 스키마 REQUEST_TIMEOUT_MS 기본값만 20,000으로 바꾸면 실패, 스키마 필드 없는 제품 행을 더하면 실패. - check:registries(재승인 뒤 compatibility=none), run-vitest related (env.ts, governance) 18파일 154건, registry-governance·product-composition 23건, check:types, eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 13-04 Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md P-07-05 --- .../contracts/registry-baseline.approval.json | 6 +- config/contracts/registry-baseline.json | 17 ++++-- config/contracts/registry-governance.json | 2 +- src/contracts/env.ts | 21 +++++-- tests/unit/env-registry-coverage.test.ts | 55 +++++++++++++++++-- 5 files changed, 81 insertions(+), 20 deletions(-) diff --git a/config/contracts/registry-baseline.approval.json b/config/contracts/registry-baseline.approval.json index fad51b0f..38b05eee 100644 --- a/config/contracts/registry-baseline.approval.json +++ b/config/contracts/registry-baseline.approval.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "snapshotDigest": "96e048bf63f739ba7acb9238e77b4b36abaf9c1fc3e40ea2f2f4a4862e0127b9", + "snapshotDigest": "8f5ae6dde9c6a293144e5bccad1765367f06ac3a6b58a6229c69426703158c9c", "owner": "DongHyeonka", - "reason": "1103/07-01 FE-REG-API rows carry descriptor wire values (statuses, limits, deadline, retry budget, traffic, command data, validation skip); problemSchema and unvalidated are breaking fields", - "approvedAt": "2026-11-04T11:23:02.382Z" + "reason": "1103/13-04 FE-REG-ENV runtime rows state required and defaultValue as runtimeConfigV2ArtifactSchema reads them (TELEMETRY_ENABLED, AUTH_MODE, RELEASE_MANIFEST_URL, CAPABILITY_OVERRIDES, FEATURE_OVERRIDES); defaultValue may be an object", + "approvedAt": "2026-11-04T11:26:00.863Z" } diff --git a/config/contracts/registry-baseline.json b/config/contracts/registry-baseline.json index 01e176d5..da86f4cd 100644 --- a/config/contracts/registry-baseline.json +++ b/config/contracts/registry-baseline.json @@ -656,7 +656,7 @@ "phase": "string", "classification": "string", "required": "boolean", - "defaultValue": "string|integer|boolean|null" + "defaultValue": "string|integer|boolean|object|null" }, "uniqueFields": [], "allowedValues": { @@ -694,7 +694,7 @@ }, "AUTH_MODE": { "classification": "public", - "defaultValue": "external", + "defaultValue": null, "phase": "runtime", "required": true }, @@ -706,7 +706,12 @@ }, "CAPABILITY_OVERRIDES": { "classification": "public", - "defaultValue": null, + "defaultValue": { + "OFFLINE_COMMANDS": "DEFAULT", + "REALTIME": "DEFAULT", + "SERVICE_WORKER": "DEFAULT", + "WEB_WORKER": "DEFAULT" + }, "phase": "runtime", "required": false }, @@ -718,7 +723,7 @@ }, "FEATURE_OVERRIDES": { "classification": "public", - "defaultValue": null, + "defaultValue": {}, "phase": "runtime", "required": false }, @@ -738,7 +743,7 @@ "classification": "public", "defaultValue": "/release-manifest.json", "phase": "runtime", - "required": true + "required": false }, "REQUEST_TIMEOUT_MS": { "classification": "public", @@ -748,7 +753,7 @@ }, "TELEMETRY_ENABLED": { "classification": "public", - "defaultValue": false, + "defaultValue": null, "phase": "runtime", "required": true }, diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index 71add621..dce422f5 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -291,7 +291,7 @@ "phase": "string", "classification": "string", "required": "boolean", - "defaultValue": "string|integer|boolean|null" + "defaultValue": "string|integer|boolean|object|null" }, "allowedValues": { "phase": ["build", "runtime"], diff --git a/src/contracts/env.ts b/src/contracts/env.ts index 48c874be..0fcf1a9e 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -41,6 +41,12 @@ export type EnvironmentDefinition = Readonly<{ defaultValue: unknown; }>; +/** + * FE-REG-ENV. A runtime row states its key as `runtimeConfigV2ArtifactSchema` + * (`release-artifacts.ts`) reads it: `required` when config.json must carry + * the key, and `defaultValue` the value the schema gives an absent key, or + * `null` when it gives none (1103/13-04, tests/unit/env-registry-coverage). + */ export const ENV_REGISTRY = Object.freeze(withProductRows({ // F-6. Required: a staging or production build fails without it // (scripts/generate-runtime-config.ts). Local and development builds fall @@ -53,20 +59,25 @@ export const ENV_REGISTRY = Object.freeze(withProductRows({ API_BASE_URL: runtime("public-sensitive", true, null), REQUEST_TIMEOUT_MS: runtime("public", false, 10_000), MAX_RETRY_ATTEMPTS: runtime("public", false, 2), - TELEMETRY_ENABLED: runtime("public", true, false), + TELEMETRY_ENABLED: runtime("public", true, null), TELEMETRY_ENDPOINT: runtime("public-sensitive", false, null), - AUTH_MODE: runtime("public", true, "external"), + AUTH_MODE: runtime("public", true, null), CONFIG_SCHEMA_VERSION: runtime("public", true, null), - RELEASE_MANIFEST_URL: runtime("public", true, "/release-manifest.json"), + RELEASE_MANIFEST_URL: runtime("public", false, "/release-manifest.json"), // F-6. The release identity the build writes into config.json. It must match // the deployed HTML and release manifest, or boot stops with // CONFIG_BUILD_MISMATCH (scripts/check-release-admission.ts). RELEASE_ID: runtime("public-metadata", false, null), BUILD_ID: runtime("public-metadata", false, null), // §3.5: overrides may only disable an installed capability, never enable one. - CAPABILITY_OVERRIDES: runtime("public", false, null), + CAPABILITY_OVERRIDES: runtime("public", false, Object.freeze({ + REALTIME: "DEFAULT", + WEB_WORKER: "DEFAULT", + SERVICE_WORKER: "DEFAULT", + OFFLINE_COMMANDS: "DEFAULT", + })), // §3.5: likewise for features — subtractive, keyed by installed feature id. - FEATURE_OVERRIDES: runtime("public", false, null), + FEATURE_OVERRIDES: runtime("public", false, Object.freeze({})), // §3.5: build-time narrowing of the product manifest, applied by // scripts/generate-product-feature-index.ts (09-02). A feature left out here // is not imported by any registry and never reaches the bundle. diff --git a/tests/unit/env-registry-coverage.test.ts b/tests/unit/env-registry-coverage.test.ts index f28118d0..e5efe327 100644 --- a/tests/unit/env-registry-coverage.test.ts +++ b/tests/unit/env-registry-coverage.test.ts @@ -1,19 +1,64 @@ +import { isDeepStrictEqual } from "node:util"; + import { describe, expect, it } from "vitest"; -import { ENV_REGISTRY } from "../../src/contracts/env.ts"; +import { + ENV_REGISTRY, + type EnvironmentDefinition, +} from "../../src/contracts/env.ts"; import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts"; +const rows: Readonly> = ENV_REGISTRY; +const shape = runtimeConfigV2ArtifactSchema.shape as Readonly< + Record +>; + +/** + * What the schema field says when the key is left out of config.json: a field + * that fails on `undefined` is required and has no default; one that passes + * has the parsed value as its default (`null` when it stays absent). + */ +function schemaDeclaration(key: string) { + const result = shape[key]!.safeParse(undefined); + return result.success + ? { required: false, defaultValue: result.data ?? null } + : { required: true, defaultValue: null }; +} + // 09-02. A key the deployed config.json may carry needs an FE-REG-ENV row, so // check:registries sees it. A product key added to // PRODUCT_RUNTIME_CONFIG_FIELDS without a PRODUCT_ENV_REGISTRY row fails here. describe("FE-REG-ENV coverage", () => { it("has a runtime row for every V2 runtime config key", () => { - const missing = Object.keys(runtimeConfigV2ArtifactSchema.shape).filter( - (key) => - !Object.hasOwn(ENV_REGISTRY, key) || - ENV_REGISTRY[key as keyof typeof ENV_REGISTRY].phase !== "runtime", + const missing = Object.keys(shape).filter( + (key) => !Object.hasOwn(rows, key) || rows[key]!.phase !== "runtime", ); expect(missing).toEqual([]); }); + + // 1103/13-04, 0929/P-07-05. The other direction: a runtime row names a key + // the schema reads, and states its required flag and default as the schema + // field does, so the governed snapshot does not describe another document. + it("has no runtime row the V2 schema does not read", () => { + const extra = Object.keys(rows).filter( + (key) => rows[key]!.phase === "runtime" && !Object.hasOwn(shape, key), + ); + + expect(extra).toEqual([]); + }); + + it("states each runtime row's required flag and default as its schema field does", () => { + const differences = Object.keys(shape).flatMap((key) => { + const row = rows[key]; + if (!row) return []; + const declared = { required: row.required, defaultValue: row.defaultValue }; + const expected = schemaDeclaration(key); + return isDeepStrictEqual(declared, expected) + ? [] + : [`${key}: row ${JSON.stringify(declared)}, schema ${JSON.stringify(expected)}`]; + }); + + expect(differences).toEqual([]); + }); }); From 9800bc89f3b5eb5ab4eda94ffd44cc81d0230af5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:28:49 +0900 Subject: [PATCH 5/9] =?UTF-8?q?test(contracts):=20=EA=B8=88=EC=A7=80=20?= =?UTF-8?q?=EC=A1=B0=EA=B0=81=EC=9D=B4=20=EB=93=A0=20=EB=9F=B0=ED=83=80?= =?UTF-8?q?=EC=9E=84=20=EC=84=A4=EC=A0=95=20=ED=82=A4=EB=A5=BC=20test:unit?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 설정 키 금지 조각 검사(assertSafeConfigNames: TOKEN, COOKIE, SECRET 등)는 부팅 때 한 곳에서만 돈다. ece944d가 연 제품 키 경로로 PRODUCT_COOKIE_NOTICE 같은 키를 zod 필드·FE-REG-ENV 행·config/runtime 값으로 더하면 generateRuntimeConfig, 범위 테스트, check:registries가 모두 통과한다. 그 config.json으로 배포하면 모든 사용자가 부팅 실패 화면을 보고, 오류 코드 CONFIG_SECRET_NAME_REJECTED에는 키 이름이 없다(실험 E-4). 고른 방법 env-registry-coverage에 사례 하나를 더한다. V2 스키마가 읽는 키와 FE-REG-ENV 런타임 행 키 전부로, 값은 스키마 기본값(CAPABILITY_OVERRIDES의 중첩 키 포함)으로 문서를 만들어 assertSafeConfigNames에 넣는다. 실패 메시지가 키 이름을 말한다. 규칙은 매뉴얼 03 C절의 product-contracts.ts 항목에 적었다. 버린 대안 - product-contracts.ts 주석에 규칙 적기: 이 파일은 제품 소유이고 템플릿이 복사 뒤에 고치지 않는다고 약속한 파일이다. 동기화 때 충돌을 만든다. - generate-runtime-config에서도 검사: 스키마가 strict라 제품 키는 스키마 필드여야 들어가고, 그 키는 이 테스트가 먼저 잡는다. 같은 검사를 한 곳 더 두지 않았다. 위험·한계 - 부팅 오류 CONFIG_SECRET_NAME_REJECTED에 거절한 키 이름을 싣는 것은 하지 않았다(src/bootstrap/load-runtime-config.ts, 다른 작업 범위). - 제품 record 필드의 임의 중첩 키(값으로만 생기는 키)는 기본값에 없으면 이 테스트가 보지 못한다. 부팅 검사가 여전히 막는다. 검증 - E-4 재실행: PRODUCT_COOKIE_NOTICE를 제품 zod 필드와 행으로 더하면 이 사례가 "Forbidden client configuration key: PRODUCT_COOKIE_NOTICE"로 실패한다. 되돌리면 4건 통과. - eslint, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-04 --- docs/manual/03-outside-feature-folder.md | 2 ++ tests/unit/env-registry-coverage.test.ts | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 1c13012f..c7639bfd 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -106,6 +106,8 @@ release admission refused for staging: - 템플릿 파일 `src/bootstrap/runtime-adapters.ts`는 고치지 않는다. - `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때. - 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다. + - 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈춘다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다. + - FE-REG-ENV 행의 `required`·`defaultValue`는 zod 필드가 키가 없을 때 하는 것과 같게 적는다. 기본값이 없으면 `defaultValue: null`이다. 같은 테스트가 대조한다. - `config/runtime/.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`). - `package.json`, lockfile, `config/security/dependency-change-evidence.json`: 계약 패키지를 더할 때(B절). diff --git a/tests/unit/env-registry-coverage.test.ts b/tests/unit/env-registry-coverage.test.ts index e5efe327..4098c556 100644 --- a/tests/unit/env-registry-coverage.test.ts +++ b/tests/unit/env-registry-coverage.test.ts @@ -3,6 +3,7 @@ import { isDeepStrictEqual } from "node:util"; import { describe, expect, it } from "vitest"; import { + assertSafeConfigNames, ENV_REGISTRY, type EnvironmentDefinition, } from "../../src/contracts/env.ts"; @@ -61,4 +62,23 @@ describe("FE-REG-ENV coverage", () => { expect(differences).toEqual([]); }); + + // 1103/07-04. The boot refuses a config.json key with a credential-like + // name (`assertSafeConfigNames`). Checking every key the schema reads, with + // the nested keys of its defaults, fails here instead of at the first boot, + // and the error names the key. + it("names no runtime config key the boot would refuse", () => { + const keys = new Set([ + ...Object.keys(shape), + ...Object.keys(rows).filter((key) => rows[key]!.phase === "runtime"), + ]); + const document = Object.fromEntries( + [...keys].map((key) => [ + key, + Object.hasOwn(shape, key) ? schemaDeclaration(key).defaultValue : null, + ]), + ); + + expect(() => assertSafeConfigNames(document)).not.toThrow(); + }); }); From 5bee9abed97832627aa73629af679b000474fbf7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:30:16 +0900 Subject: [PATCH 6/9] =?UTF-8?q?test(contracts):=20FE-REG-SCHEMA=20?= =?UTF-8?q?=ED=96=89=EC=9D=98=20=EB=B0=A9=ED=96=A5=C2=B7=EB=AA=A8=EB=A5=B4?= =?UTF-8?q?=EB=8A=94=20=ED=95=84=EB=93=9C=20=EC=A0=95=EC=B1=85=EC=9D=84=20?= =?UTF-8?q?=EA=B2=80=EC=A6=9D=EA=B8=B0=EC=99=80=20=EB=8C=80=EC=A1=B0?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 참조 기능의 FE-REG-SCHEMA 행은 응답 스키마를 STRIP_UNKNOWN, 요청 스키마를 REJECT_UNKNOWN이라 적는다. 실제 정책은 zod .strip()·.strict()가 정하고, unknownFieldPolicy·direction을 읽는 실행 코드는 없다. 응답 DTO를 .strict()로 바꿔도 check:registries와 관련 테스트가 모두 통과한다(실험 X8). 그러면 백엔드가 응답에 필드 하나를 더할 때마다 그 API가 SCHEMA_MISMATCH로 실패하는데, 스냅샷과 docs/contracts/compatibility.md는 여전히 additive라 말한다. 고른 방법 설치된 기능의 HTTP descriptor마다 입력·출력 검증기를 FE-REG-SCHEMA 행과 대조하는 테스트를 더한다. - direction: 입력 검증기 행은 REQUEST, 출력 검증기 행은 RESPONSE. - unknownFieldPolicy: 아무 스키마도 선언하지 않는 키 하나를 가진 객체와, 그 객체 하나를 담은 배열을 검증기에 넣는다. 그 객체 위치의 unrecognized_keys면 REJECT_UNKNOWN, 객체 안을 봤는데 그 issue가 없으면 STRIP_UNKNOWN이다. 정책을 적은 행만 본다. loaded-feature-runtimes를 읽으므로 다운스트림이 더한 기능도 같은 검사를 받는다. create:feature 뼈대(NoRequest strict, 목록 응답 strip)도 맞는다. 버린 대안 - 메타데이터에서 두 칸을 지우기: 읽는 곳이 없어 가장 단순하지만 호환 문서의 근거가 사라지고 기준선 재승인이 필요하다. 메타데이터 생성은 다른 작업(16-04~06) 범위다. - 스키마마다 유효한 예시 값을 두고 모르는 키를 더하기: 기능마다 예시를 손으로 써야 해 다운스트림 기능을 자동으로 덮지 못한다. 위험·한계 - 탐침은 payload의 첫 객체 단계(객체, 또는 배열의 항목)만 본다. 그 아래 중첩 객체의 정책은 보지 않는다. - problem 검증기는 FE-REG-SCHEMA 행이 없어 대상이 아니다. 검증 - 변이: 응답 DTO .strip()→.strict()(X8), 생성 명령 .strict()→.strip(), 응답 행 direction을 REQUEST로 바꾸면 각각 실패한다. 되돌리면 2건 통과. 설치된 기능이 없으면(샘플 제거 뒤) 두 건 모두 빈 채로 통과한다. - eslint, check:types:test 통과. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-03 --- tests/unit/schema-metadata-policy.test.ts | 98 +++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 tests/unit/schema-metadata-policy.test.ts diff --git a/tests/unit/schema-metadata-policy.test.ts b/tests/unit/schema-metadata-policy.test.ts new file mode 100644 index 00000000..16923671 --- /dev/null +++ b/tests/unit/schema-metadata-policy.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "vitest"; + +import type { RuntimeValidator } from "../../src/contracts/external-contract-runtime.ts"; +import { + COMPOSED_CONTRACT_CONTRIBUTIONS, + SCHEMA_REGISTRY, +} from "../../src/features/loaded-feature-runtimes.ts"; + +/** + * 1103/07-03. FE-REG-SCHEMA rows state each HTTP schema's direction and + * unknown-field policy, and `docs/contracts/compatibility.md` builds the + * "adding a response field is additive" rule on `STRIP_UNKNOWN`. Nothing at + * run time reads those two fields, so they are checked here against the + * validators the installed HTTP descriptors run. + * + * The probe is an object with one key no schema declares, and the same object + * as the only item of an array, so it reaches the first object level of an + * object or list payload. A validator that rejects it with + * `unrecognized_keys` rejects unknown fields; one that reaches the object + * without that issue tolerates them. A nested object below that level is not + * probed. + */ +const PROBE_KEY = "__unknownFieldProbe"; + +type ProbedPolicy = "REJECT_UNKNOWN" | "STRIP_UNKNOWN" | "UNREACHED"; + +function probeUnknownFieldPolicy(validator: RuntimeValidator): ProbedPolicy { + const probe = { [PROBE_KEY]: true }; + for (const [value, objectPath] of [ + [probe, []], + [[probe], [0]], + ] as const) { + const result = validator.safeParse(value); + if (result.success) return "STRIP_UNKNOWN"; + const atObject = (path: readonly (string | number)[]) => + JSON.stringify(path) === JSON.stringify(objectPath); + if ( + result.issues.some( + (issue) => issue.code === "unrecognized_keys" && atObject(issue.path), + ) + ) { + return "REJECT_UNKNOWN"; + } + // Every issue sits at or above the probed object (wrong type, wrong + // shape): the validator never looked inside it, so try the next probe. + const unreached = result.issues.every( + (issue) => + issue.path.length <= objectPath.length && + issue.path.every((segment, index) => segment === objectPath[index]), + ); + if (!unreached) return "STRIP_UNKNOWN"; + } + return "UNREACHED"; +} + +const slots = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.flatMap( + ({ http }) => + http.flatMap(({ contract }) => [ + { + operationId: contract.operationId, + direction: "REQUEST" as const, + validator: contract.inputValidator, + }, + { + operationId: contract.operationId, + direction: "RESPONSE" as const, + validator: contract.outputValidator, + }, + ]), +); + +// With no installed feature (after the sample is removed) there is nothing to +// probe, and both cases pass empty. +describe("FE-REG-SCHEMA policy of the installed HTTP schemas (1103/07-03)", () => { + it("declares the direction each schema is used in", () => { + const wrong = slots.flatMap(({ operationId, direction, validator }) => { + const declared = SCHEMA_REGISTRY[validator.schemaId]?.direction; + return declared === undefined || declared === direction + ? [] + : [`${operationId} ${validator.schemaId}: row ${declared}, used as ${direction}`]; + }); + + expect(wrong).toEqual([]); + }); + + it("declares the unknown-field policy its validator applies", () => { + const wrong = slots.flatMap(({ operationId, validator }) => { + const declared = SCHEMA_REGISTRY[validator.schemaId]?.unknownFieldPolicy; + if (declared === undefined) return []; + const probed = probeUnknownFieldPolicy(validator); + return probed === declared + ? [] + : [`${operationId} ${validator.schemaId}: row ${declared}, validator ${probed}`]; + }); + + expect(wrong).toEqual([]); + }); +}); From 84d6e526a33f69244fd0b413e5ca2e953d254f58 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:32:20 +0900 Subject: [PATCH 7/9] =?UTF-8?q?fix(registries):=20=EA=B3=84=EC=95=BD=20?= =?UTF-8?q?=EC=A1=B0=EB=A6=BD=20=EC=8B=A4=ED=8C=A8=EC=9D=98=20reason?= =?UTF-8?q?=EC=9D=84=20=EC=A0=81=EA=B3=A0=20=EC=9D=BD=EC=A7=80=20=EB=AA=BB?= =?UTF-8?q?=ED=95=9C=20=EB=A0=88=EC=A7=80=EC=8A=A4=ED=8A=B8=EB=A6=AC?= =?UTF-8?q?=EB=A5=BC=20=EC=A7=80=EC=9A=B4=20=EA=B2=83=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EC=84=B8=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 기능 계약 조립이 실패하면(예: 없는 authProfileId) check:registries 출력은 "missing registry source src/features/loaded-feature-runtimes.ts: Installed contract contribution is not composable" 두 줄, "FE-REG-API is not an object registry", "FE-REG-ROUTE references unknown registry FE-REG-SCHEMA", "breaking change missing evidence: FE-REG-API:*:*:removed" 등이다. 원인은 ContractContributionError.reason에 있는데 검사기는 message 첫 줄만 적는다. 끝의 removed 줄은 "breaking 증거를 더하라"로 읽혀 틀린 다음 행동을 제안한다(실험 E-9). 고른 방법 - source를 읽다 난 오류에 문자열 reason이 있으면 "(reason: ...)"로 함께 적는다. - 읽지 못한 레지스트리는 따로 모은다. 그 레지스트리에 대해서는 행 검사 ("is not an object registry"), 그것을 가리키는 참조 검사, 기준선 비교 (removed 증거 요구)를 하지 않는다. 같은 실패를 다른 이름으로 다시 적지 않기 위해서다. 게이트는 load 실패 한 줄로 그대로 실패한다. - errors.md 레지스트리 표에 이 메시지 행을 더했다. 버린 대안 - 메시지 접두어를 "failed to load"로 바꾸기: 의미는 더 맞지만 기존 테스트와 CI 진단 기대값이 "missing registry source"를 쓴다. 이번에는 바꾸지 않았다. 위험·한계 - source 파일을 실수로 지운 경우에도 removed 증거 요구를 건너뛴다. 그래도 "missing registry source" 실패로 게이트는 막힌다. 레지스트리를 의도해서 지우면 governance에서도 빠지므로 removed 증거 요구는 그대로다. - FE-REG-API와 FE-REG-SCHEMA가 같은 source라 load 실패 줄은 두 번 나온다. 검증 - RED: registry-governance에 임시 디렉터리 fixture(두 레지스트리, 하나가 다른 하나를 참조, 기준선 있음)를 더했다. source가 reason 있는 오류를 던지면 출력이 load 실패 한 줄이어야 한다. 고치기 전에는 reason이 없고 cascade 3줄이 더 나와 실패했다. - GREEN: registry-governance 11건 통과. E-9 재실행(참조 기능 목록 operation의 authProfileId를 NOTICE_NOPE로): 출력이 "... (reason: reference-feature/LIST_REFERENCE_RESOURCES: unknown authProfileId NOTICE_NOPE)" 두 줄뿐이고 removed 줄이 없다. - check:registries:fixture·check:routes:fixture·baseline-fixture가 기대 진단으로 실패한다. eslint, check:types:node, check:types:test 통과. Refs: docs/reviews/2026-11-03-maturity-review/14-template-product-docs.md 14-06 --- docs/manual/reference/errors.md | 1 + scripts/check-registries.ts | 48 ++++++++++- tests/unit/registry-governance.test.ts | 112 +++++++++++++++++++++++++ 3 files changed, 158 insertions(+), 3 deletions(-) diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 4cf83d62..8397a68f 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -144,6 +144,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `FE-REG-ROUTE.. has unknown value ` | `access`·`errorSurface`가 정해진 값이 아니다 | 계약 `routes` | | `FE-REG-ROUTE..paramsSchema references unknown FE-REG-SCHEMA.schemaId=` | 라우트 스키마 ID를 기능이 등록하지 않았다 (`searchSchema`도 같은 꼴) | 계약 스키마 메타 | | `FE-REG-API. has no executable consumer for operationId=` | 계약의 operation을 기능 `adapters/`·`application/`에서 쓰지 않는다 | 쓰지 않으면 descriptor를 지운다 | +| `missing registry source : (reason: )` | 레지스트리 source를 읽다가 오류가 났다. 계약 조립 실패면 ``이 위 `reason` 표의 값이다. 읽지 못한 레지스트리는 `removed` 증거를 요구하지 않는다 | ``이 가리키는 곳 | | `breaking change missing evidence: ` | 행을 빼거나 바꿨는데 승인이 없다 | `update:registry-baseline` 또는 `config/contracts/registry-change-evidence.json` | | `stale breaking evidence : no breaking change in the current diff has this changeId. ...` | 지금 diff와 맞지 않는 증거 행 | 그 행을 지운다 | | `registry baseline approval digest mismatch: approved= actual=` | 기준선 파일을 손으로 고쳤다 | `update:registry-baseline`으로 다시 찍는다 | diff --git a/scripts/check-registries.ts b/scripts/check-registries.ts index b34bba0c..73c3c11d 100644 --- a/scripts/check-registries.ts +++ b/scripts/check-registries.ts @@ -116,6 +116,13 @@ const owners = new Map(); const snapshots: RegistrySnapshot[] = []; const rowsByRegistry = new Map(); const sourcesByRegistry = new Map(); +/** + * 1103/14-06. Registries whose source did not load. Their failure is already + * reported with its cause, so the checks that read their rows (references, + * the baseline comparison) skip them instead of reporting the same failure + * again as a deleted registry. + */ +const unloadedRegistries = new Set(); const registryExtensions = [".ts", ".tsx", ".mts", ".cts"]; async function resolveRegistrySource( @@ -144,6 +151,33 @@ async function resolveRegistrySource( return candidates[0] ?? null; } +/** + * 1103/14-06. A contract composition failure (`ContractContributionError`) + * says only "not composable"; its cause is the `reason` property. + */ +function loadErrorText(error: Error): string { + const message = error.message.split("\n")[0] ?? ""; + const reason: unknown = (error as Error & { reason?: unknown }).reason; + return typeof reason === "string" && reason.length > 0 + ? `${message} (reason: ${reason})` + : message; +} + +function withoutRegistries( + snapshot: Readonly>, + registryIds: ReadonlySet, +): Readonly> { + if (registryIds.size === 0 || !Array.isArray(snapshot.registries)) { + return snapshot; + } + return { + ...snapshot, + registries: (snapshot.registries as Array<{ registryId?: unknown }>).filter( + (registry) => !registryIds.has(String(registry.registryId)), + ), + }; +} + type FieldLookup = Readonly<{ found: boolean; value: unknown; @@ -371,8 +405,12 @@ for (const specification of governance.registries) { } catch (error) { // A source that exists but fails to load names its error, so a broken // import in a feature contract is not reported as a missing file. - const reason = sourcePath && error instanceof Error ? `: ${error.message.split("\n")[0]}` : ""; - if (!rows) failures.push(`missing registry source ${specification.path}${reason}`); + const reason = sourcePath && error instanceof Error ? `: ${loadErrorText(error)}` : ""; + if (!rows) { + failures.push(`missing registry source ${specification.path}${reason}`); + unloadedRegistries.add(specification.registryId); + continue; + } } const registryRows = projectRegistryRows(specification, rows); @@ -534,6 +572,7 @@ for (const specification of governance.registries) { for (const reference of specification.references ?? []) { const targetRows = rowsByRegistry.get(reference.registryId); if (!targetRows) { + if (unloadedRegistries.has(reference.registryId)) continue; failures.push( `${specification.registryId} references unknown registry ${reference.registryId}`, ); @@ -672,7 +711,10 @@ if (baselinePath && approvalPath && evidencePath) { `registry baseline approval digest mismatch: approved=${approvalResult.approvedDigest} actual=${approvalResult.actualDigest}`, ); } - const registryDiff = diffRegistrySnapshots(baseline, currentSnapshot); + const registryDiff = diffRegistrySnapshots( + withoutRegistries(baseline, unloadedRegistries), + currentSnapshot, + ); compatibility = registryDiff; const evidence = JSON.parse( await readFile(evidencePath, "utf8"), diff --git a/tests/unit/registry-governance.test.ts b/tests/unit/registry-governance.test.ts index 8c2e0586..e038d441 100644 --- a/tests/unit/registry-governance.test.ts +++ b/tests/unit/registry-governance.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest"; import { diffRegistrySnapshots, + registrySnapshotDigest, validateBreakingEvidence, verifyRegistryBaselineApproval, } from "../../scripts/lib/registry-compatibility.ts"; @@ -536,4 +537,115 @@ describe("registry governance manifest", () => { await rm(directory, { recursive: true, force: true }); } }); + + // 1103/14-06. A contract contribution that fails to compose throws while + // the registry source loads. The gate names the cause the error carries in + // `reason` and does not also report the unloaded registries as deleted + // (`removed` evidence) or as unknown reference targets. + it("names a load error's reason and reports no cascade for the registries it did not load", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "registry-source-reason-")); + const run = (extra: readonly string[]) => + spawnSync( + process.execPath, + [ + path.resolve("scripts/check-registries.ts"), + "--governance", + "governance.json", + "--artifact", + "out.json", + ...extra, + ], + { cwd: directory, encoding: "utf8" }, + ); + try { + await mkdir(path.join(directory, "src"), { recursive: true }); + await writeFile( + path.join(directory, "src/composed.ts"), + 'export const ROWS = { A: { id: "A" } };\n', + ); + await writeFile( + path.join(directory, "src/routes.ts"), + 'export const ROUTES = { R: { id: "R", target: "A" } };\n', + ); + await writeFile( + path.join(directory, "governance.json"), + JSON.stringify({ + schemaVersion: 1, + sourceDirectories: [], + registries: [ + { + registryId: "FIXTURE-COMPOSED", + path: "src/composed.ts", + exportName: "ROWS", + owner: "fixture", + keyField: "id", + requiredFields: ["id"], + fieldTypes: { id: "string" }, + }, + { + registryId: "FIXTURE-ROUTES", + path: "src/routes.ts", + exportName: "ROUTES", + owner: "fixture", + keyField: "id", + requiredFields: ["id", "target"], + fieldTypes: { id: "string", target: "string" }, + references: [ + { + field: "target", + registryId: "FIXTURE-COMPOSED", + targetField: "id", + }, + ], + }, + ], + }), + ); + const healthy = run(["--no-baseline"]); + expect(healthy.status, healthy.stderr).toBe(0); + const report = JSON.parse( + await readFile(path.join(directory, "out.json"), "utf8"), + ) as { registries: unknown[] }; + const baseline = { schemaVersion: 2, registries: report.registries }; + await writeFile(path.join(directory, "baseline.json"), JSON.stringify(baseline)); + await writeFile( + path.join(directory, "approval.json"), + JSON.stringify({ + schemaVersion: 1, + snapshotDigest: registrySnapshotDigest(baseline), + owner: "fixture", + reason: "fixture", + approvedAt: "2026-11-04T00:00:00.000Z", + }), + ); + await writeFile( + path.join(directory, "evidence.json"), + JSON.stringify({ schemaVersion: 1, changes: [] }), + ); + const withBaseline = [ + "--baseline", + "baseline.json", + "--approval", + "approval.json", + "--compatibility-evidence", + "evidence.json", + ]; + expect(run(withBaseline).status).toBe(0); + + await writeFile( + path.join(directory, "src/composed.ts"), + 'throw Object.assign(new Error("Installed contract contribution is not composable"), { reason: "notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE" });\n', + ); + const broken = run(withBaseline); + const output = `${broken.stdout}${broken.stderr}`; + + expect(broken.status).toBe(1); + expect(output.trim().split("\n")).toEqual([ + "Registry governance failed:", + "missing registry source src/composed.ts: Installed contract contribution is not composable (reason: notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE)", + ]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); }); From 64f19ac66529bdc2d3fae2d8772e01e8fb0017d4 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:36:46 +0900 Subject: [PATCH 8/9] =?UTF-8?q?fix(architecture):=20zod=20=ED=95=98?= =?UTF-8?q?=EC=9C=84=20=EA=B2=BD=EB=A1=9C=20import=EB=8F=84=20src/contract?= =?UTF-8?q?s/zod.ts=EB=A5=BC=20=EA=B1=B0=EC=B9=98=EA=B2=8C=20=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 zod-is-reached-through-contracts-zod 규칙의 to.path가 ^zod$다. src 파일이 "zod/v4"를 import하면 check:architecture가 rc=0으로 통과한다(실험 Z1). 그 모듈은 src/contracts/zod.ts의 jitless 설정보다 먼저 스키마를 만들 수 있고, 그러면 운영 CSP가 zod의 Function 탐침을 부팅마다 보고한다(F-7). 고른 방법 to.path를 ^zod(/|$)로 넓힌다. 그래프 fixture에 "zod/v4"를 import하는 파일과 그것이 거절되는지 보는 회귀 검사를 더했다. layers.md 규칙 표도 고쳤다. 버린 대안 - eslint no-restricted-imports에 zod 패턴 추가: 같은 규칙을 두 도구에 둔다. 경계 규칙은 dependency-cruiser가 정본이다. 위험·한계 - src 안에 zod 하위 경로 import는 지금 없다(grep). 다운스트림이 쓰고 있으면 check:architecture가 실패한다. src/contracts/zod.ts의 z로 바꾼다. 검증 - 수정 뒤: 참조 기능 스키마 파일 import를 "zod/v4"로 바꾸면 "Architecture violation [zod-is-reached-through-contracts-zod]: ... -> zod/v4"로 실패, "zod"도 실패. - 규칙을 ^zod$로 되돌리면 새 회귀 검사 "zod subpath import outside src/contracts/zod.ts is rejected"가 실패한다. - check:architecture(29 regression checks PASS), check:types, eslint, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md P-07-06 --- .dependency-cruiser.json | 4 ++-- docs/architecture/layers.md | 2 +- scripts/check-architecture.ts | 9 +++++++++ .../import-boundaries/presentation/pages/subpath-zod.ts | 5 +++++ 4 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 tests/fixtures/architecture/dependency-graph/import-boundaries/presentation/pages/subpath-zod.ts diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json index 133c1641..9aa7ada8 100644 --- a/.dependency-cruiser.json +++ b/.dependency-cruiser.json @@ -58,14 +58,14 @@ }, { "name": "zod-is-reached-through-contracts-zod", - "comment": "F-7 (13-08). src/contracts/zod.ts sets zod jitless before any schema is built, so the production CSP never sees zod's Function probe. Schema code imports z from there.", + "comment": "F-7 (13-08). src/contracts/zod.ts sets zod jitless before any schema is built, so the production CSP never sees zod's Function probe. Schema code imports z from there. A subpath (zod/v4, zod/mini) is the same zod and counts too (0929/P-07-06).", "severity": "error", "from": { "path": "^src", "pathNot": "^src/contracts/zod\\.ts$" }, "to": { - "path": "^zod$" + "path": "^zod(/|$)" } }, { diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md index 973e6e6a..4c30f033 100644 --- a/docs/architecture/layers.md +++ b/docs/architecture/layers.md @@ -42,7 +42,7 @@ Each row is one `forbidden` rule in `.dependency-cruiser.json`, by its `name`. | `presentation-does-not-know-adapters` | `src/presentation`, except `adapters/query` | adapters, bootstrap, TanStack | | `page-templates-own-layout-only` | `src/presentation/templates` | application, adapters, bootstrap, the presentation query adapter, TanStack. Templates take data and actions as props | | `icon-vendor-is-facade-only` | all of `src`, except the lucide vendor facade | `lucide-react` | -| `zod-is-reached-through-contracts-zod` | all of `src`, except `src/contracts/zod.ts` | `zod` | +| `zod-is-reached-through-contracts-zod` | all of `src`, except `src/contracts/zod.ts` | `zod` and its subpaths (`zod/v4`) | | `design-system-is-reached-through-its-index` | code outside the design system and its named facades | design-system files other than its `index.ts` | | `adapters-do-not-know-presentation` | `src/adapters` | presentation, bootstrap | | `feature-domain-is-framework-neutral` | `src/features//domain` | application, presentation, adapters, bootstrap, any feature's application, adapters and presentation, React, TanStack | diff --git a/scripts/check-architecture.ts b/scripts/check-architecture.ts index 2413162c..1a232292 100644 --- a/scripts/check-architecture.ts +++ b/scripts/check-architecture.ts @@ -931,6 +931,15 @@ async function runGraphFixtureChecks(): Promise { target === "zod", ), }, + { + name: "zod subpath import outside src/contracts/zod.ts is rejected", + passed: blockingViolations(importBoundaryGraph).some( + ({ rule, source, target }) => + rule === "zod-is-reached-through-contracts-zod" && + source === "src/presentation/pages/subpath-zod.ts" && + target === "zod/v4", + ), + }, { name: "zod through src/contracts/zod.ts is accepted", passed: !blockingViolations(importBoundaryGraph).some(({ source }) => diff --git a/tests/fixtures/architecture/dependency-graph/import-boundaries/presentation/pages/subpath-zod.ts b/tests/fixtures/architecture/dependency-graph/import-boundaries/presentation/pages/subpath-zod.ts new file mode 100644 index 00000000..3c1d4cde --- /dev/null +++ b/tests/fixtures/architecture/dependency-graph/import-boundaries/presentation/pages/subpath-zod.ts @@ -0,0 +1,5 @@ +// 0929/P-07-06: a zod subpath is the same zod, so it is reached through +// src/contracts/zod.ts too. +import { z } from "zod/v4"; + +export const subpathSchema = z.string(); From c99b7a7f63a9c5a0c498ae53f0f96dfd39abfe38 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:37:10 +0900 Subject: [PATCH 9/9] =?UTF-8?q?docs(contracts):=20=EB=91=90=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=20=EC=96=B4=ED=9C=98=EC=99=80=20commandRecovery?= =?UTF-8?q?=EB=A5=BC=20=EB=88=84=EA=B0=80=20=EC=9D=BD=EB=8A=94=EC=A7=80=20?= =?UTF-8?q?=ED=83=80=EC=9E=85=20=EC=98=86=EC=97=90=20=EC=A0=81=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 - AppFailure(닫힌 kind, retryable, action)와 AppError(열린 owner.reason kind, retryability)의 관계가 타입 옆에 없다. AppFailure.retryable과 action "retry"는 뜻이 다른데(CONFLICT는 retryable false, action retry) 설명이 없어 모순으로 읽고 "고치는" 변경이 나올 수 있다(1101/07-05). - CommandRecoveryDescriptor는 KEYED 쓰기에 필수지만 HTTP 실행기는 읽지 않는다. 결과 불명 쓰기를 기능 gateway가 수습한다는 것은 설계서 4.4절에만 있다(1101/07-07). - 07-01(c)에서 더한 읽기 retrySemantics 거절 문구가 errors.md reason 표에 없다. 고른 방법 주석만 더한다. AppFailure 위에 어느 경계에서 어느 어휘를 쓰는지와, 둘 다 재시도 동작을 바꾸지 않는다는 것. retryable 칸에 "src에서 읽는 곳이 없고, 화면 버튼은 action"이라는 것. CommandRecoveryDescriptor 위에 실행기가 읽지 않고 기능 gateway가 재전송·조회를 정한다는 것. errors.md reason 표에 한 행. 버린 대안 - retryable을 autoRetryable 같은 이름으로 바꾸기: 다운스트림 import를 깨는 비용에 비해 얻는 것이 작다. 위험·한계 - 동작은 바뀌지 않는다. "src에서 읽는 곳이 없다"는 grep으로 확인한 지금 상태다. 검증 - grep: src/presentation·bootstrap·features·application에서 AppFailure.retryable을 읽는 곳 0. commandRecovery를 읽는 곳은 플랫폼 개요 화면뿐. - eslint, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 1101/07-05, 1101/07-07 --- docs/manual/reference/errors.md | 1 + src/contracts/errors.ts | 17 +++++++++++++++++ src/contracts/external-contract-runtime.ts | 9 +++++++++ 3 files changed, 27 insertions(+) diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 8397a68f..02878ed2 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -97,6 +97,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `/: unknown authProfileId ` | V3 `frontend.authProfileId`가 없는 프로필 | V3 `frontend.authProfileId` | | `/: retry budget contradicts NEVER retry semantics` | `NEVER`인데 `retryBudget`가 0이 아니다 | V3 `frontend.retryBudget` | | `/: KEYED commands require a recovery descriptor` | `KEYED`인데 `commandRecovery`가 없다 | V3 `commandRecovery` | +| `/: is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` | | `/: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` | | `/: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` | | `: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `_CONTRACT_PACKAGE.version` | diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts index b559cc81..8e8b08af 100644 --- a/src/contracts/errors.ts +++ b/src/contracts/errors.ts @@ -118,10 +118,27 @@ export type FailureEffectCertainty = | "APPLIED_CONFIRMED" | "MAYBE_APPLIED"; +/** + * 1101/07-05. The failure that crosses an application input boundary: a + * gateway result, a query or mutation error. Its `kind` is the closed set + * above. `AppError` (`src/platform/errors/app-error.ts`) is the other + * vocabulary: an open `owner.reason` kind a feature uses inside its own + * domain, mapped from an `AppFailure` where the feature needs it. Neither + * changes how a request is retried; the HTTP executor follows the + * operation's `retrySemantics` and `retryBudget`. + */ export type AppFailure = Readonly<{ kind: FailureKind; code: string; httpStatus?: number; + /** + * Whether sending the same operation again is safe as far as this failure + * tells: the registry default, forced `false` once a write may have + * applied. Nothing in src reads it today. What the screen offers is + * `action`: `"retry"` shows a retry button even when this is `false` + * (`CONFLICT`, `QUERY_CACHE_FAILURE`): the user, not the runtime, sends + * again. + */ retryable: boolean; operationId: string; attemptCount: number; diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 2250fb90..b927e3dd 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -127,6 +127,15 @@ export function mappingViolation(code: string): MappingResult { }); } +/** + * 1101/07-07. How the package says a write whose result is unknown can be + * settled: resend with the same idempotency key, or read the operation back + * through `inspectOperationId`. Composition requires one on a KEYED command, + * and FE-REG-API records it. The HTTP executor does not read it: a write + * that ends `MAYBE_APPLIED` comes back to the feature, and the feature's + * gateway decides whether to resend or inspect (closed-deep-design.md + * §4.4 under docs/architecture). + */ export type CommandRecoveryDescriptor = Readonly<{ mode: "IDEMPOTENCY_REPLAY" | "INSPECT_OPERATION"; operationIdentityField: string;