fix(review): 2026-11-05 리뷰의 나머지 발견과 1103 이월을 고친다 #7

Merged
donghyeon.kang merged 85 commits from fix/maturity-review-2026-11-05-b into main 2026-11-07 08:19:55 +00:00
197 changed files with 8749 additions and 958 deletions
+3 -3
View File
@@ -300,11 +300,11 @@
},
{
"name": "feature-and-app-roots-do-not-reach-adapters",
"comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers the files outside a feature's layer folders (src/features/*.ts, src/features/<feature>/*.ts), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the InstalledHttpOperationExecutor type that bootstrap hands to feature adapters (type only). Owner: frontend-platform. Revisit when that type moves to an application port.",
"comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers every file under src/features outside a feature's adapters/ folder (the root files, and any folder that is not a layer, such as support/: 0929/12-03), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the InstalledHttpOperationExecutor type that bootstrap hands to feature adapters (type only). Owner: frontend-platform. Revisit when that type moves to an application port.",
"severity": "error",
"from": {
"path": "^src/(features/[^/]+\\.tsx?$|features/[^/]+/[^/]+\\.tsx?$|contexts/|apps/)",
"pathNot": "^src/features/feature-adapter-contribution\\.ts$"
"path": "^src/(features/|contexts/|apps/)",
"pathNot": "^src/features/([^/]+/adapters/|feature-adapter-contribution\\.ts$)"
},
"to": {
"path": "^src/adapters/"
+104 -17
View File
@@ -8,12 +8,35 @@
- **[보안]** 복사한 프로젝트도 가져가야 하는 보안·개인정보 수정이다.
- **[계약]** 백엔드, 배포 설정, CI, 또는 기능 코드가 함께 바뀌어야 하는 변경이다(헤더, 변수, 게이트, 공개 포트).
- 표시가 없으면 템플릿 안에서 끝나는 수정이다.
- 괄호 안 ID는 리뷰 발견 ID다. `MMDD/NN-MM`으로 적는다. `MMDD`는 리뷰 폴더 `docs/reviews/YYYY-MM-DD-maturity-review/`의 월일이고, 근거와 재현 조건은 그 폴더의 영역 문서에 있다. 복사한 프로젝트가 README대로 `docs/reviews/`를 지웠다면 이 폴더와 `PRODUCT.md`는 원본 템플릿 repo에서 찾는다. 라운드마다 `NN-MM`을 새로 매기므로 같은 `14-02`라도 라운드가 다르면 다른 결함이다. `F-N`은 그 라운드 `FOLLOW-UP.md`의 ID다. `tests/unit/changelog-review-ids.test.ts`가 라운드 없는 ID를 막는다.
- 괄호 안 ID는 리뷰 발견 ID다. `MMDD/NN-MM`으로 적는다. `MMDD`는 리뷰 폴더 `docs/reviews/YYYY-MM-DD-maturity-review/`의 월일이고, 근거와 재현 조건은 그 폴더의 영역 문서에 있다. 복사한 프로젝트가 README대로 `docs/reviews/`를 지웠다면 이 폴더와 `PRODUCT.md`는 원본 템플릿 repo에서 찾는다. 라운드마다 `NN-MM`을 새로 매기므로 같은 `14-02`라도 라운드가 다르면 다른 결함이다. `F-N`은 그 라운드 `FOLLOW-UP.md`의 ID다. 리뷰 README의 절은 `MMDD README N.N`으로 적고 다시 돌린 항목은 그 뒤에 `X2`처럼 번호를 붙인다. 영역 문서가 따로 매긴 ID는 `MMDD NN 영역 P-NN-NN`, 짝 백엔드 리뷰의 ID는 `백엔드 리뷰 MMDD/NN-MM`으로 적는다. `tests/unit/changelog-review-ids.test.ts`가 라운드 없는 ID와 이 꼴을 벗어난 참조를 막는다.
- 0.2.0의 커밋 해시는 브랜치 `fix/maturity-review-2026-09-25`에서 만들었고, `main`에서도 같은 해시로 찾을 수 있다(2026-11-03에 52개 모두 확인). 그 뒤 절은 절 머리에 범위(기준 커밋과 브랜치)를 적고, 그 절의 해시는 모두 그 범위에 있다. 0.2.0의 커밋 제목은 라운드 없이 ID만 적었다(`git log --grep '03-03'`).
## 미출시 — `409d72e` → 브랜치 `fix/maturity-review-2026-11-05`
## 미출시 — `409d72e` → 브랜치 `fix/maturity-review-2026-11-05-b`
2026-11-05 성숙도 리뷰(`docs/reviews/2026-11-05-maturity-review/`) 조치다. 범위는 `main` `409d72e`(아래 절의 묶음을 합친 커밋)부터 이 브랜치의 끝까지다. 아래 절을 아직 받지 않은 프로젝트는 아래 절부터 받는다.
2026-11-05 성숙도 리뷰(`docs/reviews/2026-11-05-maturity-review/`) 조치다. 범위는 `main` `409d72e`(아래 절의 묶음을 합친 커밋)부터 브랜치 `fix/maturity-review-2026-11-05-b`(PR B)의 끝까지다. 앞의 세 조치(`9655958`, `629c713`, `397664e`)는 PR A(PR #5, 브랜치 `fix/maturity-review-2026-11-05`)에 있고, PR B는 그 위에 쌓였다. 기준점 `409d72e`를 빼면 이 절의 해시는 모두 이 범위에 있다. 아래 절을 아직 받지 않은 프로젝트는 아래 절부터 받는다.
### 먼저 할 일 (BREAKING)
아래 절의 "먼저 할 일"을 마친 뒤 순서대로 한다. 단계 끝의 괄호는 아래 표의 근거 행이다. 두 다운스트림 코드에 적용해 게이트를 돌려 보지는 않았다(알려진 제한).
#### 옮기는 법
1. **HTTP descriptor마다 `responseEnvelope`를 적는다.** `InstalledHttpContract`의 필수 칸이 됐다. 감싸지 않는 백엔드(memento-web, TechLog)는 `"NONE" as const`, 짝 백엔드 Envelope는 `"ENVELOPE_V1" as const`다. 빠뜨리면 그 descriptor의 `satisfies InstalledHttpContract<...>`에서 `check:types`가 실패한다. 런타임 동작은 같다 (1103/16-01)
2. **뮤테이션 정책의 operation ID를 손으로 적지 않는다.** `BoundMutation.operationId`는 brand 타입 `MutationOperationId`다. `operationId: "<ID>"`와 `requiresIdempotencyKey`를 `...commandMutationIdentity(<descriptor>)`로 바꾼다. 문자열로 적으면 `check:types`가 실패한다 (1103/16-05)
3. **`refusedBeforeWrite`에서 플랫폼 code를 뺀다.** 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 code(`PLATFORM_CODES_POSSIBLY_AFTER_WRITE`: `BAD_PARAMETER`, `MAPPING_FAILED`, `DB_*` 8개, `LOCK_ACQUISITION_TIMEOUT`, Fileserver code)를 적으면 계약 조립이 거절해 부팅이 멈춘다. 그 code의 실패는 결과 불명으로 남는다 (1105/03-01)
4. **bounded poll의 `execute`는 실패를 던지지 않고 결과로 돌려준다.** 던지면(lease 자신의 abort 제외) 재시도 없이 `PROTOCOL_MISMATCH`(retryable 아님)로 lease가 끝난다. 네트워크 실패를 throw로 내던 `execute`는 retryable `PROVIDER_UNAVAILABLE` 결과로 바꾼다. 실행기에는 클로저의 descriptor 대신 `input.operation`(생성 때 검사한 descriptor)을 넘긴다 (1105/04-02, 1103/04-01)
5. **`artifacts/tests/a11y.json`을 읽는 도구는 schemaVersion 2를 읽는다.** `scope`는 실패 화면으로만 본 라우트를 빼고, 그 라우트는 새 `notChecked` 배열에 `{ routeId, reason }`으로 들어간다. 설치된 라우트 전체는 둘을 합친 것이다 (1103/11-01)
6. **제품 scope participant의 `label`은 소문자 kebab-case 48자 이하로 쓴다.** 아니면 조립이 `TypeError`로 멈춘다 (1105/02-01)
7. **레시피를 복사한 제품은 복사본을 고친다.** 쿠키 세션 모드는 `createSessionCookieRejectionHandler(context)`를 `composeProduct`의 `onCredentialRejected`에 잇는다. 잇지 않으면 서버 401이 템플릿 세션에 닿지 않는다(매뉴얼 04 4.3) (1105/09-02). OIDC PKCE owner는 sign-in transaction 키를 registry 행 `AUTH_REDIRECT_TRANSACTION`의 `physicalKey`에서 가져온다. 키 글자는 같다 (1105/05-01)
8. **Service Worker를 켠 제품은 `blockers`·`observe`를 `composeProduct`의 선택 칸 `serviceWorker`로 옮긴다.** 템플릿 파일 `src/bootstrap/create-runtime-composition.ts`는 템플릿 것으로 되돌린다 (1103/09-05)
9. **제품 merge 게이트(`config/ci/product-gates.json`의 `mergeGates`)가 있는 제품은 `corepack pnpm generate:ci-workflow`를 다시 돈다.** `release_gate`가 `product_merge_gate`도 기다리는 줄이 생긴다. 다시 돌리지 않으면 `check:ci`가 실패한다 (1105/13-02)
10. **기능 안 `adapters/` 밖에서 `src/adapters`를 import하는 파일은 `adapters/`로 옮긴다.** 아니면 `check:architecture`가 `feature-and-app-roots-do-not-reach-adapters`로 실패한다 (0929/12-03)
#### 옮긴 뒤 확인
1. 로컬 merge 게이트 14개를 돈다. 이 절 때문에 먼저 볼 것: `check:types`(1·2단계), 앱을 조립하는 `test:unit`·`test:component`(3·6단계), `check:ci`(9단계), `check:architecture`(10단계), `check:registries`(응답 스키마 행을 `REJECT_UNKNOWN`으로 좁힌 변경은 이제 breaking).
2. 한 checkout에서 브라우저 테스트 실행 두 개를 함께 돌리려면 실행마다 `TEST_RUN_ID`를 다르게 준다. 게이트(`ci:gate`)와 증거 검사는 기본 경로만 읽으므로 한 checkout에서 하나씩 돈다.
3. 배포가 있는 제품: 자산을 redirect로 주는 호스트는 FE-GATE-019가 FAIL이다.
### 보안·계약 변경
@@ -21,10 +44,68 @@
|---|---|---|---|
| [계약] | FE-GATE-013(`test:system`) 러너는 비특권 user namespace와 network namespace를 허용해야 한다(provider 샌드박스의 `bwrap --unshare-net`). 사전 점검이 bwrap을 실제로 띄워 보고, 허용하지 않는 호스트에서는 provider 테스트를 돌리기 전에 이유·호스트 설정·고치는 방법을 적고 멈춘다. 요구는 러너 요구 목록, gate 정의의 `hostRequirements`, workflow 주석에 있다 (1105/12-01) | `scripts/check-system-test-prerequisites.ts`, `scripts/lib/provider-sandbox-namespaces.ts`, `config/ci/gates.json`, `docs/operations/ci-quality-gates.md` | `9655958` |
| [계약] | release job `immutable_build`가 FE-GATE-015·027의 gate 로그·evidence와 의존성 advisory 기록을 결과와 상관없이 `immutable-gate-evidence-<run>-<attempt>`로 올린다. 후보 archive와 그 upload는 그대로다 (1105/13-01) | `scripts/generate-ci-workflow.ts`, `scripts/contracts/ci-gates.ts`, `.gitea/workflows/quality-gates.yml` | `629c713` |
| [계약] | gate 모양 기준선(`canonicalGateShapeSha256`)이 FE-GATE-013의 `hostRequirements`도 본다. 요구를 지우거나 바꾸면 `check:ci`가 기준선 차이로 실패하고, 바꿀 때는 `update:ci-contract-baseline`(owner·reason 필수)으로 다시 기록한다. 제품이 `config/ci/contract-baseline.json`을 자기 값으로 다시 기록해 두었다면 받은 뒤 다시 기록한다 (1105/12-01) | `scripts/contracts/ci-gates.ts`, `config/ci/contract-baseline.json` | `67082cc` |
| [계약] | 제품 overlay에 merge 게이트가 있으면 `release_gate`가 `product_merge_gate`를 기다린다. 제품 검사가 실패하면 같은 run의 release·immutable_build·promotion·deployment가 멈춘다. 게이트가 없으면 workflow는 그대로다. `check:ci`가 그 연결이 없는 workflow를 거절한다. 위 "먼저 할 일" 9단계 (1105/13-02) | `scripts/generate-ci-workflow.ts`, `scripts/contracts/ci-gates.ts` | `92d5019` |
| [계약] | 한 checkout에서 실행 두 개가 서로를 지우지 않는다. `TEST_RUN_ID`를 주면 Playwright 결과·report·JUnit과 서빙할 빌드가 `.tmp/runs/<id>/` 아래로 간다. 빌드 단계는 `RUN_OUTPUT_ROOT`(설정이 web server에 넘긴다) 아래에 쓴다. 다섯 Playwright 설정은 빈 포트를 골라 `TEST_E2E_PORT`·`TEST_VISUAL_PORT`·`TEST_CAPABILITIES_PORT`·`TEST_STORYBOOK_PORT`·`TEST_DEV_PORT`에 적고(미리 주면 그 포트), vite는 `--strictPort`로 뜨고, dev 설정은 떠 있는 서버를 쓰지 않는다. 변수가 없으면 출력 경로는 전과 같다. 기능 인덱스 생성기는 내용이 같으면 쓰지 않고 다르면 rename으로 바꾼다. 상세는 `docs/testing/frontend-platform-testing-strategy.md` 13.6절 (1105/12-04) | `scripts/lib/run-isolation.ts`, `playwright*.config.ts`, `vite.config.ts`, `scripts/build-frontend.ts`, `scripts/generate-product-feature-index.ts` | `ddbda4d`, `f4d5761`, `0e72c0c`, `510e2bb` |
| [계약] | `verify:documentation`이 짝 백엔드 경로·링크를 `config/contracts/backend-contract-pin.json`이 고정한 커밋의 트리(옆 checkout의 git 기록)에서 찾는다. 작업 트리와 HEAD는 보지 않는다. checkout이나 그 커밋이 없으면 확인하지 못한 것으로 남긴다. repo 밖으로 나가는 링크가 pin한 저장소가 아니면(이름 오타 포함) 실패한다 (1105/12-02) | `scripts/verify-documentation-readiness.ts` | `fc95672` |
| [계약] | `verify:documentation`은 지울 수 있는 템플릿 기능(참조 기능, 예제 화면 기능. `scripts/lib/removable-template-features.ts`)의 경로와 script를 그 기능이 설치돼 있으면 검사하고, `src/features/<id>/feature-module.ts`가 없으면 요구하지 않는다. 그래서 아래 절 6단계대로 예제 기능을 지운 제품도 문서 검사와 FE-GATE-005가 통과한다. 참조 기능 경로는 다시 백틱으로 적어 검사를 받는다. 1절 문서가 그 경로를 백틱 밖에 적으면 `test:unit`이 실패한다 (1105/14-01, 1105/14-03) | `scripts/verify-documentation-readiness.ts`, `scripts/lib/removable-template-features.ts`, `scripts/test-sample-removal.ts`, `docs/` | `50b631e`, `332bfee`, `1dda18d` |
| [계약] | 아키텍처 규칙 `feature-and-app-roots-do-not-reach-adapters`가 기능의 `adapters/` 폴더와 `feature-adapter-contribution.ts`를 뺀 `src/features` 전체를 본다. 기능 안 `support/` 같은 계층 밖 폴더가 `src/adapters`에 닿으면 실패한다. 위 "먼저 할 일" 10단계 (0929/12-03) | `.dependency-cruiser.json`, `scripts/check-architecture.ts` | `a37ebba` |
| [계약] **BREAKING** | `artifacts/tests/a11y.json`이 schemaVersion 2다. 실패 화면으로만 axe를 돌린 라우트(일반 답이 없는 상세 라우트)는 `scope`에서 빠져 `notChecked`(`{ routeId, reason }`)에 들어간다. 라우트 test가 자기 상태를 `artifacts/tests/a11y-data-state/<ROUTE_ID>.json`에 남긴다. 위 "먼저 할 일" 5단계 (1103/11-01) | `scripts/write-a11y-report.ts`, `scripts/lib/a11y-data-state.ts`, `scripts/contracts/release-artifacts.ts`, `tests/e2e/accessibility.spec.ts` | `757d1c7` |
| [계약] | lab(FE-GATE-026)이 기능 라우트 첫 진입을 잰다. 대상은 설치된 기능의 첫 공개 내비게이션 라우트(`labFeatureRoute`, 템플릿에서는 `EXAMPLES_UI`)이고 예산은 `budgets.json`의 `lab.featureRouteInteractionMs` 500 ms다. 그런 라우트가 없으면 `measured: false`로 남기고 판정하지 않는다. run마다 대상 라우트를 직접 열어 CLS도 잰다(`metrics.targetDeepLinkCls`, 예산 `lab.cls`). lab은 스크롤바를 보이게 띄운다. `lab.json` schema에 새 칸이 필수다 (1105/15-04, 1105/15-01, 1105/15-05) | `config/performance/budgets.json`, `config/schemas/lab-performance.schema.json`, `scripts/test-performance.ts`, `scripts/lib/lab-performance.ts` | `81701ad`, `138c195`, `e02f252` |
| [계약] | 초기 JS 기록 대조(`tests/unit/feature-shape-growth.test.ts`)의 합계 허용 오차가 1%(약 2 KB)가 아니라 256 B다. 초기 JS를 수백 바이트 움직이는 변경은 기록을 다시 쓴다 (1105/15-02) | `scripts/scale/measure-feature-shape-growth.ts` | `46359a1` |
| [계약] | 초기 JS 예산(`initialJsGzipBytes`)이 204,800 B가 아니라 206,848 B(202 KiB)다. 이 묶음의 검사·진단 코드가 초기 JS를 1,184 B 늘려 생성 기능 둘을 더한 드릴(FE-GATE-020)이 예산을 넘었다. 템플릿 기록은 204,111 B·초기 파일 27개로 다시 적었다. 예산을 복사한 제품은 자기 값을 그대로 두거나 같은 이유로 올린다. 재검토 조건은 `docs/operations/performance-evidence.md` (1105/15-02) | `config/performance/budgets.json`, `config/scale/feature-shape-ceilings.json` | `0fee3fe`, `287dc6f` |
| [계약] | `test:all`이 `test:coverage`(FE-GATE-005)가 도는 Vitest 경로를 모두 돈다(`tests/features` 전체, `tests/scripts`, browser-soak 계약 테스트). `tests/unit/test-all-paths.test.ts`가 대조한다 (0929/10-05) | `package.json` | `7ead8d3` |
| [계약] | 제품 기능 제거 드릴(`test:sample-removal -- --feature=<id>`)의 잔여 판정: `src`는 기능 ID·폴더 이름을 담은 파일, `tests`는 이름에 기능 ID가 있거나 그 기능 폴더에서 import하는 파일만이다. 템플릿 테스트가 예시 ID(`invoice-feature` 등)를 데이터로 쓰는 것은 잔여가 아니다. 참조 기능은 전처럼 넓게 찾는다 (1105/16-04) | `scripts/lib/feature-residue.ts`, `scripts/test-sample-removal.ts` | `b45d6a0` |
| [계약] **BREAKING** | `InstalledHttpContract`의 `contract.responseEnvelope`가 필수다. 참조 기능과 테스트 fixture는 `"NONE"`을 적는다. 조립은 빠진 값을 전처럼 `NONE`으로 읽는다. 위 "먼저 할 일" 1단계 (1103/16-01) | `src/contracts/external-contract-runtime.ts`, `scripts/create-feature.ts`, `src/features/reference-feature/contracts/` | `56272e8` |
| [계약] **BREAKING** | `refusedBeforeWrite`에 `PLATFORM_CODES_POSSIBLY_AFTER_WRITE`(계약 문서 6.1절의 "쓰기 뒤 가능" 플랫폼 code)를 적으면 `composeContractContributions`가 거절한다. 실행기의 fail-close도 그 목록을 무시한다. `tests/unit/backend-contract-pin.test.ts`가 6.1절 표와 목록을 양방향으로 대조한다. 위 "먼저 할 일" 3단계 (1105/03-01) | `src/contracts/external-contract-runtime.ts`, `src/adapters/http/backend-envelope.ts` | `5c0b37e` |
| [계약] | Envelope operation의 503 `RATE_LIMIT_UNAVAILABLE`·`RATE_LIMIT_INCOMPATIBLE`은 쓰기 전 거절(`NOT_APPLIED`)이다. kind는 `SERVER_FAILURE`(action retry)이고 IDEMPOTENT 쓰기는 `retryBudget` 안에서 다시 보낸다. KEYED·NEVER는 자동 재전송이 없다 (1105/03-02) | `src/adapters/http/backend-envelope.ts`, `config/contracts/backend-idempotency-answers.json` | `c6c37f3` |
| [계약] | 짝 백엔드 `http-contract.md` §2·§4 표를 pin 커밋 그대로 `config/contracts/backend-http-contract-excerpt.json`에 옮겼다. `test:unit`이 답 표와 사본을 행마다 대조한다(옮기지 않은 행은 pin의 `notCopied`). `check:backend-contract-drift`(게이트 밖)는 사본을 pin 커밋의 문서와 비교하고, pin의 `backend.scaffoldSources`(백엔드 생성기 템플릿 파일과 옮긴 프론트 위치)가 pin 뒤 바뀌었는지도 본다. 비교하지 못하면 rc=2다. pin을 올릴 때는 `--write-excerpt` (1105/07-01, 1105/16-02) | `config/contracts/backend-contract-pin.json`, `config/contracts/backend-http-contract-excerpt.json`, `scripts/check-backend-contract-drift.ts`, `scripts/lib/backend-contract-excerpt.ts` | `daf3474`, `f600e6b` |
| [계약] | Fileserver 업로드 client: 202 `REJECTED`는 실패 `VALIDATION_REJECTED`, code `FILE_REJECTED`, `NOT_APPLIED`다(전에는 `SCHEMA_MISMATCH`). 빈 파일은 보내지 않고 `FILE_EMPTY`, `NOT_STARTED`로 끝난다. 504 `TRANSFER_TIMEOUT`은 결과 불명(`MAYBE_APPLIED`, retryable 아님, 자동 재전송 없음)이다. 멱등성 code와 V3 판정 표에 있는 답은 V3 표대로 판정해 503 `IDEMPOTENCY_UNAVAILABLE`도 결과 불명이다. 실패 Envelope의 `meta.traceId`를 `AppFailure.traceId`로 싣는다 (1105/01-01, 1103/01-01, 1105/01-02, 1105/01-03) | `src/adapters/http/fileserver-upload.ts`, `docs/manual/` | `6608fef`, `471b001`, `8b92f45` |
| [계약] | FE-REG-SCHEMA `direction: "RESPONSE"` 행의 `unknownFieldPolicy`를 `REJECT_UNKNOWN`으로 좁히면 `check:registries`가 breaking(`response-reader-narrowed`)으로 본다. 넓히는 쪽과 REQUEST 행은 그대로 behavior-change다 (1105/07-02) | `scripts/lib/registry-compatibility.ts` | `3b62ccd` |
| [계약] **BREAKING** | `BoundMutation.operationId`와 `commandMutationIdentity`가 돌려주는 operationId가 brand 타입 `MutationOperationId`다. 위 "먼저 할 일" 2단계 (1103/16-05) | `src/contracts/server-state.ts` | `48c1ab7` |
| [계약] | 키 없는(`NEVER`) 결과 불명 요청과 같은 입력으로 `submit`하면 보내지 않고 `NOT_STARTED` `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)를 돌려준다. `AsyncSurface`는 `unknownEffectResendable === true`일 때만 재전송 버튼을 그린다. 손으로 만든 결과 불명 상태를 넘기던 화면은 버튼이 사라진다 (0929/03-03) | `src/presentation/adapters/query/application-query.ts`, `src/presentation/components/async-surface.tsx` | `683ccfb` |
| [계약] **BREAKING** | `createBoundedPollCoordinator`의 `execute`가 던지면(abort 제외) 재시도 없이 `PROTOCOL_MISMATCH`(retryable 아님)로 lease가 끝난다. `execute` 입력에 생성 때 검사한 descriptor `input.operation`이 실린다(추가만). 위 "먼저 할 일" 4단계 (1105/04-02, 1103/04-01) | `src/adapters/realtime/` | `05330e3`, `27e3dec` |
| [계약] | scope reset이 실패하면 단계마다 진단 `cache.operation.failed`(`operation: "SCOPE_RESET"`, `reason` `PARTICIPANT_FAILED`·`CACHE_RESET_FAILED`·`GENERATION_ACTIVATION_FAILED`·`PARTICIPANTS_UNREADABLE`, participant면 `scope_participant: <label>`)를 남긴다. 진단 계약에 키 `scope_participant`(값 정책 `isScopeParticipantLabel`)가 생겼다. 제품 closer는 각자 participant가 되고, 형식에 맞지 않는 label은 조립이 `TypeError`로 거절한다. 위 "먼저 할 일" 6단계 (1105/02-01) | `src/contracts/diagnostics.ts`, `src/adapters/query-cache/server-state-scope-runtime.ts`, `src/bootstrap/runtime-adapters.ts` | `f738348` |
| [계약] | `ProductCompositionContext.notifySessionUnauthenticated()`가 생겼다. 쿠키 세션 recipe의 `createSessionCookieRejectionHandler(context)`는 `SESSION_COOKIE_*` 프로필의 401만 세션에 넘긴다. 위 "먼저 할 일" 7단계 (1105/09-02) | `src/bootstrap/product-composition-contract.ts`, `recipes/session-owners/cookie-session-owner.ts` | `0007699` |
| [계약] | `ProductComposition.serviceWorker`(선택): `{ blockers?, observe? }`. 템플릿 조립이 `createOptionalRuntimeHost`에 넘긴다. `observe`가 던져도 worker 흐름은 바뀌지 않는다. 위 "먼저 할 일" 8단계 (1103/09-05) | `src/bootstrap/product-composition-contract.ts`, `src/bootstrap/create-runtime-composition.ts` | `fdc1db9` |
| [계약] | 금지된 설정 키로 멈춘 부팅 오류의 `invalidKeys`에 그 키의 점 경로가 실린다. `src/contracts/env.ts`가 `UnsafeConfigNameError`(`key`)를 새로 내보낸다(추가만) (1103/07-04) | `src/contracts/env.ts`, `src/bootstrap/load-runtime-config.ts` | `2e1acb1` |
| [계약] | 저장소 registry 행 `AUTH_REDIRECT_TRANSACTION`(`backend: "external"`, FE-REG-STORAGE additive). OIDC PKCE recipe의 sessionStorage 키가 이 행의 `physicalKey`다. 사용처가 지울 수 있는 레시피뿐이라 FE-REG-STORAGE orphan 검사에서 뺀다. 위 "먼저 할 일" 7단계 (1105/05-01) | `src/contracts/storage-keys.ts`, `recipes/session-owners/oidc-pkce-session-owner.ts`, `config/contracts/registry-governance.json` | `dc7c95b` |
| [계약] | 승인된 LOGOUT·ACCOUNT_DELETION purge가 마지막 객체까지 돌면 늘 partition을 지운다. 성공 report는 `partitionDeleted`와 `moreObjectsAvailable` 중 정확히 하나를 가진다. port의 `chunkSweep`은 아무도 채우지 않아 `@deprecated`다 (1103/05-01) | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts`, `src/application/ports/browser-file-storage/opfs-ports.ts`, `recipes/frontend-capabilities/` | `23662fb` |
| [계약] | Cache Storage: 본문을 읽지 못한 entry는 판정 `UNREADABLE`이고, 다시 stage하면 모든 asset을 다시 받아 덮어쓴다. activation은 그 경우 code는 그대로 두고 recovery를 `REHYDRATE`로 준다 (1105/02-02) | `src/adapters/cache-storage/public-response-cache-adapter.ts` | `8e9fb1f` |
| [계약] | Service Worker 사전 캐시는 `assets/`(`BUILD_ASSET_DIRECTORY`) 아래 해시 파일만 담는다. `public/`의 루트 파일(아이콘 등)은 빠진다. `build.assetsDir`를 바꾸는 제품은 이 상수도 바꾼다 (1105/06-01) | `src/contracts/service-worker.ts`, `scripts/generate-service-worker-assets.ts`, `src/adapters/service-worker/service-worker-static-assets.ts`, `scripts/lib/hosting-probe.ts` | `1c7c614` |
| [계약] | 자산 MIME probe(FE-GATE-019 live)가 redirect를 FAIL로 본다(install fetch는 `redirect: "error"`). live 분기는 `probeLiveHosting` 하나다 (1105/06-02) | `scripts/lib/hosting-probe.ts`, `scripts/verify-hosting-headers.ts` | `4d6f254` |
### 그 밖의 수정
- 테스트: 제품 확장 타입 검사 탐침이 복사본의 `product-contracts.ts`·`product-composition.ts`를 덮어쓰지 않고 덧붙인다. 기능이 제품 capability를 쓰는 다운스트림에서도 FE-GATE-005가 통과한다 (1105/09-01, `397664e`)
- 폼·화면: 기능이 `useAppForm`의 `refusalMessages`로 쓰기 전 거절 code에 자기 문구와 필드를 붙인다 (1103/03-01, `12d97d7`). 복구 버튼으로 끝낸 저장 뒤 포커스가 feedback 자리로 간다 (1105/08-01, `4f3c10b`). 다른 저장이 진행 중이면 저장 버튼을 끄고 진행 문구를 보인다 (1105/08-04, `f2b8ba7`). 생성 폼이 "변경됨으로 확인" 뒤 목록으로 간다 (1105/08-02, `90c489c`). 홈 시작 링크가 런타임에 꺼진 기능을 고르지 않는다 (1105/08-03, `f849d78`). `:root`에 `scrollbar-gutter: stable`. 스크롤바 자리만큼 내용 폭이 15 px 줄어 시각 골든 5장을 다시 찍었다. base.css를 받은 제품은 자기 골든도 다시 찍는다 (1105/15-05, `e02f252`). 플랫폼 구성 화면이 릴리스 신원 칸 자리를 처음부터 잡는다 (1105/15-01)
- 레지스트리 도구: `check:registries`가 계약 조립 실패 원인을 한 번만 적는다 (1105/09-03, `bfd9d50`)
- 문서: VD-28과 realtime 설계 3절의 poll 규칙을 V3 descriptor로 (1105/04-03, `05880d1`). 테스트 전략 11.2절의 지운 auth-recovery 테스트 (1103/12-05, `e72fb6e`). 기능마다 바뀌는 추적 파일 둘과 충돌 처리 (1105/16-01, `6d084cf`). 매뉴얼 04 §3.2 설정 키 예시의 `defaultValue`와 그 블록을 그대로 타입 검사하는 테스트 (1105/14-02, `e6b2a4f`). Cache Storage inspect의 `verified` 뜻과 비용 (0929/02-02, `f2a4f32`). 세션 파일 recipe 주석의 capability 타입 위치 (1105/02-03, `d31c7d6`). 남은 `FEATURE_OVERRIDES` 키의 경고 (0929/14-05, `1c4e57c`). 루트 `SPEC.md`·`tasks/`의 이유 (0929/14-01, `1ac336a`). README에 미출시 범위를 받는 두 명령과 기준점 기록 (0929/14-02, `57e3586`)
- CHANGELOG: 아래 절의 초기 파일 상한 32·알려진 제한 기준·FE-GATE-017 단계 (1103/14-01, 1103/15-02, `832774f`), poll 행 (1105/04-02, `1e576ef`), "옮기기 전" 2단계 목록 (1103/14-02, `f4be426`), 리뷰 참조 꼴과 그 테스트 (1101/14-02, `b834b8d`)
- 테스트 고정: interaction signal listener 정리 (1105/10-02, `dae44f5`), 조합 transport의 OFFLINE 재시도 (1105/04-01, `bde7fa4`), MAX_RETRY_ATTEMPTS·REQUEST_TIMEOUT_MS와 복구 중 세션의 보호 라우트를 샘플 밖에서 (1105/10-01, `00b12b3`), 옛 탭이 지워진 route를 reload 없이 연다 (1105/06-03, `aaa782b`), Fileserver 5xx·deadline·읽기 전 크기 거절 (1105/01-04, `f2f7dc4`), strict fixture가 preload 기록으로 test를 실패시킨다(`browserFailureVerdict`) (1105/11-01, `e025529`), 오래된 scope의 성공 응답 (0929/10-04, `c842bac`), 손상 code 목록의 경계 (1105/02-04, `56c0bd0`), 실제 시계를 기다리던 테스트 5개 (1101/10-07, `ce191be`), cross-context host의 localStorage 영역 (1101/02-04, `11a0fd0`), vite 빌드 입력 목록 한 모듈 (1105/15-03, `c9aa73f`)
### 알려진 제한
이 절의 범위 끝에서 사실인 것만 적었다. 하나씩 결정 대기·백엔드로 넘김·일부를 적는다.
- 다운스트림 이행: 위 안내를 두 제품 코드에 적용해 게이트를 돌려 보지 않았다.
- 기능 라우트 첫 진입: lab이 `EXAMPLES_UI`를 500 ms 예산으로 잰다(1105/15-04). 진입은 여전히 요청 두 묶음(context 라우트 모듈·실행부, 그다음 페이지 청크)이다. 하나로 줄이려면 초기 청크의 라우트 선언이 페이지 로더를 가져야 한다. 결정 대기(선언 모양·초기 JS). 예산 여유는 94 ms이고 lab 부하 가드는 없다(0929/11-04).
- 예제 기능 제거 드릴(`test:sample-removal -- --feature=platform-examples-feature`)은 어느 게이트도 돌리지 않는다. 문서 쪽은 `test:unit`의 사본 테스트가 본다. 일부(1105/14-01).
- 결정 대기: KEYED 결과 불명의 같은 키 재전송이 500 `IDEMPOTENCY_RECOVERY_REQUIRED`를 받아도 재전송 버튼이 남는다. 고르는 사람은 프론트 템플릿 담당이다(재전송을 거두기 / 백엔드가 롤백을 효과 없음으로 기록 / 지금대로) (1103/03-01).
- 결정 대기: 워커 없는 빌드에서 자산 MIME probe를 script·style만 보게 좁힐지. 지금은 글꼴·이미지 MIME도 FAIL이다 (1105/06-02).
- 결정 대기: Cache Storage inspect에 `signal`과 판정 불가 칸을 더할지(VD-15 목표 runtime과 함께) (0929/02-02).
- 결정 대기: dev manifest를 생성 파일로 둘지, 초기 JS 기록에서 제품 기능을 뺄지. 지금은 기능 브랜치 둘이 같은 줄에서 충돌하고 명령을 다시 돌려 푼다 (1105/16-01).
- 결정 대기: 1절 밖 문서(목표 설계)의 경로 검사. 문서별 예외 방식부터 정해야 한다 (1103/12-05).
- 결정 대기: 두 제품이 고친 템플릿 파일 중 제품 소유 자리가 없는 것을 템플릿에 들일지(아래 절 "옮기기 전" 2단계) (1103/14-02, 0929/14-03). 다운스트림이 찾은 템플릿 결함을 어디에 기록할지 (0929/14-06). 현재 계약 절과 목표 설계 절이 섞인 문서를 나눌지 (1101/14-07).
- 백엔드로 넘김: Fileserver 504 `TRANSFER_TIMEOUT`은 작업이 시작된 뒤에도 retryable로 온다. 백엔드가 `ambiguous` 표시를 주거나 504가 "READY 없음"을 보장하면 프론트 판정을 다시 본다. `POST /v1/files`는 `Idempotency-Key`를 읽지 않는다 (1105/01-02).
- 백엔드로 넘김: 백엔드 매뉴얼의 짝 경로 안내와 `docs/fileserver/http-contract.md`의 202 state 목록. 실제 백엔드 업로드는 돌리지 않았다 (1103/01-01).
- 백엔드로 넘김: `RateLimitInterceptor`가 비동기 재디스패치에서도 평가되면 503 rate-limit이 쓰기 뒤에도 나올 수 있다. 요청은 `DispatcherType.REQUEST`에서만 평가하기다. 지금 백엔드에는 그런 쓰기 컨트롤러가 없다 (1105/03-02).
- 일부: poll 조합 코드가 `input.operation`을 무시하고 다른 descriptor를 넘기면 attempt마다 요청이 최대 3번이다 (1103/04-01).
- 일부: Service Worker 활성화 화면(`onUpdateWaiting`·`requestActivation()`)과 reload 안내를 이을 제품 소유 자리가 없다. realtime·Web Worker·오프라인 명령 선택은 조립이 거절한다 (1103/09-05).
- 일부: 짝 백엔드 표 사본과 백엔드 문서의 일치, 생성기 템플릿 변경은 `check:backend-contract-drift`(게이트 밖, 옆 checkout 필요)만 본다. Fileserver 자신의 code 표는 pin 대조 밖이다 (1105/07-01, 1105/16-02, 1105/01-02).
- 일부: 실행 격리는 브라우저 테스트 실행까지다. 게이트와 증거 검사는 기본 경로만 읽고, 선택이 다른 두 실행은 `src/.generated`를 서로 바꾸고, Storybook 캐시는 공유한다 (1105/12-04).
- 일부: 쿠키 세션 handler를 잇지 않은 제품은 여전히 세션 만료를 모르고, 막는 검사는 없다. 세션 owner recipe는 실제 Keycloak·Redis에 붙여 보지 않았다 (1105/09-02).
- 일부: 아래 절 "옮기기 전" 목록(0929/14-03 포함), 루트 작업 기록 위치, README 범위 동기화 명령은 문서만 고쳤고 명령은 실행하지 않았다 (1103/14-02, 0929/14-01, 0929/14-02).
## 미출시(`main` `409d72e`에 합침) — `752a61f` → 브랜치 `fix/maturity-review-2026-11-03`
@@ -52,6 +133,10 @@
2. 제품이 고친 템플릿 파일을 뽑는다. 이 묶음은 그 일을 받을 제품 소유 파일을 새로 둔다(옮기는 법 2단계). 템플릿 파일을 고친 채로 두면 동기화마다 충돌한다.
- memento: `src/bootstrap/runtime-adapters.ts`, `src/features/feature-adapter-contribution.ts`(capability `offsetUpload`·`runtime`), `src/contracts/rest-profiles.ts`(`MEMENTO_BFF_READ`·`MEMENTO_BFF_WRITE`), `src/contracts/external-contract-runtime.ts`(출처 종류 `PRODUCT_LOCAL_CONTRACT`), `src/features/installed-feature-contracts.ts`(`APP_HOME` 다리), `src/features/installed-runtime-capabilities.ts`(Service Worker `ACTIVE`), `src/presentation/routes/app-router.tsx`(`ownsShell` 다리).
- tech-log: `src/contracts/env.ts`(`TECH_LOG_STUDIO_SOURCE`·`TECH_LOG_PUBLIC_SOURCE` 행), `src/bootstrap/create-runtime-composition.ts`(부트 전 BFF 세션 owner), `src/contracts/rest-profiles.ts`(`TECH_LOG_STUDIO_SESSION`·`TECH_LOG_STUDIO_BOOTSTRAP`), `src/bootstrap/runtime-adapters.ts`, `src/bootstrap/runtime-config-schema.ts`, `src/features/installed-*` 다섯 개(TechLog 직접 조립. 그중 `installed-feature-runtimes.tsx`는 템플릿이 지웠다), `src/presentation/routes/app-router.tsx`(PUBLIC/STUDIO 라우터).
- 위 목록은 일부다. `af3d8e6` 뒤 두 제품이 고친 템플릿 `src` 파일(기능·context 폴더 밖, `git diff --name-status af3d8e6 HEAD -- src`)은 memento 26개(수정 23, 추가 3), tech-log 40개(수정 38, 추가 2, 그 밖에 삭제. 추가 중 `reference-feature/NOT_INSTALLED`는 옮기는 법 1단계)다. 2026-11-05에 두 repo의 diff를 읽어 나눴다(1103/14-02).
- 제품 소유 자리가 있는 것. tech-log `src/contracts/release-artifacts.ts`의 `TECH_LOG_STUDIO_SOURCE`·`TECH_LOG_PUBLIC_SOURCE` 필드는 `PRODUCT_RUNTIME_CONFIG_FIELDS`로 간다(옮기는 법 2단계). memento `src/adapters/http/offset-upload.ts`(추가)와 `src/adapters/http/index.ts`의 그 export는 capability `offsetUpload`를 만드는 제품 코드라 `src/bootstrap/product-composition.ts` 쪽 제품 파일로 옮기고 HTTP 배럴은 템플릿 것으로 되돌린다. tech-log의 라우팅 파일(`src/contracts/routes.ts`·`route-runtime-contract.ts`의 `layoutGroup`과 플랫폼 라우트 삭제, 참조 기능 계약 `reference-feature-contract.ts`의 `layoutGroup`, `src/presentation/routes/` 6개와 추가 `route-url-builder.ts`)은 직접 조립의 일부라 3단계 끝의 기능 모듈 길로 바꾸면 템플릿 것으로 돌아간다.
- 제품 소유 자리가 아직 없는 것. 템플릿이 자리를 정하지 않았다. 동기화 때 충돌하거나 제품이 고친 채로 남는다(알려진 제한). memento: 요청 헤더 `if-match`(`http-contract-bridge.ts`, `http-execution-v3.ts`. V3 descriptor에는 요청 헤더 칸이 없다), Service Worker 오프라인 navigation shell(`service-worker-lifecycle.ts`)과 사전 캐시 확장자 `.html`·`.jpg`(`service-worker-static-manifest.ts`), 저장소 이름 `APP_NAMESPACE`(`storage-keys.ts`)와 OPFS 이름(`opfs-policy.ts`, `indexeddb-opfs-journal.ts`), 앱 이름 문구(`catalog.ts`의 `common.appName`·`route.APP_HOME.title`), 브랜드 토큰·글꼴·primitive(`design-system/tokens/` CSS 3개와 `token-contract.ts`, `primitives/core.tsx`, `design-system/index.ts`, `styles/theme.css`, 추가 폴더 `design-system/memento/`). tech-log: `AppFailure.detail`(`errors.ts`, `feature-http-binding.ts`), `BoundMutation.identity`(`server-state.ts`)와 그것을 쓰는 `application-query.ts`, `deriveAsyncState`와 조회 훅이 `null`을 데이터 없음이 아닌 빈 상태로 보는 것(`async-state.ts`, `application-query.ts`), 폼(`use-app-form.ts`의 select, `use-dirty-navigation-guard.tsx`), 디자인 시스템(`primitives/core.tsx`·`forms.tsx`·`navigation.tsx`, `patterns/common-patterns.tsx`, `design-system/index.ts`, `page-templates.tsx`, `app-shell.tsx`), 문구(`catalog.ts`, `message-contract.ts`), 전역 글꼴·스타일 import(`src/bootstrap/main.tsx`).
- 템플릿 결함 후보. tech-log `application-query.ts`는 마운트한 같은 이벤트 턴에 저장하면 결과 불명 채널이 아직 없어 거절되던 것을 고쳤다(채널을 제출 때도 얻는다). 템플릿은 이것을 재현하지 않았다.
3. 기능마다 HTTP descriptor를 센다. method, `retrySemantics`, `responseEnvelope`, 입력·응답·실패 검증기의 schemaId, 그 검증기가 zod인지. 옮기는 법 4·5단계의 작업량이 이 숫자로 정해진다.
- memento-web: descriptor 29개. 입력·응답 schemaId 42개와 실패 본문 `MementoProblem` 1개. 검증기는 zod가 아니라 손으로 쓴 `isRecord` 검사다. `responseEnvelope`는 없다. GET은 `SAFE`, 쓰기는 `KEYED`·`IDEMPOTENT`·`NEVER`다.
- TechLog: 검증기는 `zodValidator`다. 출력은 Envelope 뼈대만 검사하고 본문은 통과시킨다. `responseEnvelope`는 없다. GET은 `SAFE`, 쓰기는 `KEYED`나 `NEVER`(둘 다 `retryBudget` 0)다.
@@ -115,11 +200,11 @@
6. **쓰는 곳이 있을 때만.**
- V2 HTTP 클라이언트와 V2 API 행에서 지운 이름(아래 `048f490`·`12f3bb7` 행). 두 다운스트림은 앱 코드에서 V2 클라이언트를 부르지 않는다. 부르는 곳은 템플릿의 `tests/unit/runtime-adapters.test.ts`뿐이고 그 파일은 템플릿 것으로 바뀐다.
- realtime: `BoundedPollOperationContract`를 지웠다. SSE·poll이 서버에 닿지 못한 실패는 `OFFLINE` 대신 `PROVIDER_UNAVAILABLE`이다.
- 예제 화면 3개(`EXAMPLES_UI`·`EXAMPLES_STATES`·`EXAMPLES_AUTH`)가 `platform-examples-feature`로 옮겼다. 예제를 지운 제품(tech-log)은 이 기능 폴더와 `src/contexts/platform-examples-context/`를 지운다. 예제 화면을 여는 제품 테스트는 그 기능을 설치해 두거나 제품 화면으로 옮긴다. memento의 `production-csp.spec.ts`·`old-tab-chunk-recovery.spec.ts`가 `/examples/states`·`/examples/ui`에서 시작한다. `/examples/platform`(플랫폼 구성 화면)은 플랫폼 라우트로 남는다.
- 예제 화면 3개(`EXAMPLES_UI`·`EXAMPLES_STATES`·`EXAMPLES_AUTH`)가 `platform-examples-feature`로 옮겼다. 예제를 지운 제품(tech-log)은 이 기능 폴더, `tests/features/platform-examples-feature/`, `src/contexts/platform-examples-context/`를 지우고 `corepack pnpm generate:feature-index`를 돈다. 지우기 전에 `corepack pnpm test:sample-removal -- --feature=platform-examples-feature`가 사본에서 같은 삭제로 게이트를 돈다. 템플릿 문서가 지운 폴더를 계속 적어도 `verify:documentation`과 FE-GATE-005가 통과하는 것은 위 절의 수정부터다(1105/14-01). 그래서 두 절을 함께 받는다. 예제 화면을 여는 제품 테스트는 그 기능을 설치해 두거나 제품 화면으로 옮긴다. memento의 `production-csp.spec.ts`·`old-tab-chunk-recovery.spec.ts`가 `/examples/states`·`/examples/ui`에서 시작한다. `/examples/platform`(플랫폼 구성 화면)은 플랫폼 라우트로 남는다.
- 포트를 직접 구현한 코드: `OpfsJournalPort.countPartitionTransactions`·`removePartition`, worker gateway의 `removePartition`, `PublicCacheInspection.activePointer`가 필수 칸이다.
- offline-indexeddb recipe 타입: `src`와 이름이 같은 34개가 `src` 타입을 다시 내보낸다.
(1103/04-01, 1103/04-04, 1103/09-04, 1103/05-01, 0929/05-01, 1103/02-05, 0929/05-03)
7. **초기 JS 예산.** 예산은 gzip 204,800 B와 초기 파일 26개다(`config/performance/budgets.json`, merge 게이트 FE-GATE-012의 `check:bundle`). 템플릿 자체가 202,927 B를 쓴다. 여유는 1,873 B다. 측정용 기능 복사본 하나를 같은 context에 더하면 +768 B, 새 context 하나는 +233 B다(`config/scale/feature-shape-ceilings.json`. `tests/unit/feature-shape-growth.test.ts`가 기능 1 KiB·context 512 B로 막는다). 제품 기능의 선언(라우트 표, 문구)은 초기 청크에 들어간다. memento-web(라우트 14개)과 기능 모듈로 바꾼 TechLog의 크기는 템플릿이 재지 않았다. `build` 뒤 `check:bundle`이 넘은 한도와 초과량을 적는다. 예산을 올릴 때는 `docs/operations/performance-evidence.md`대로 기준선·새 측정값·이유를 같은 변경에 적는다. 초기 파일 수는 HTTP/2 서빙이 전제다.
7. **초기 JS 예산.** 예산은 gzip 204,800 B와 초기 파일 32개다(`config/performance/budgets.json`, merge 게이트 FE-GATE-012의 `check:bundle`). 템플릿 자체가 202,927 B와 파일 26개를 쓴다. 여유는 1,873 B다. 측정용 기능 복사본 하나를 같은 context에 더하면 +768 B, 새 context 하나는 +233 B다(`config/scale/feature-shape-ceilings.json`. `tests/unit/feature-shape-growth.test.ts`가 기능 1 KiB·context 512 B로 막는다). 제품 기능의 선언(라우트 표, 문구)은 초기 청크에 들어간다. memento-web(라우트 14개)과 기능 모듈로 바꾼 TechLog의 크기는 템플릿이 재지 않았다. `build` 뒤 `check:bundle`이 넘은 한도와 초과량을 적는다. 예산을 올릴 때는 `docs/operations/performance-evidence.md`대로 기준선·새 측정값·이유를 같은 변경에 적는다. 초기 파일 수는 HTTP/2 서빙이 전제다.
(1101/15-01, 1103/15-02, 1103/15-03, 1103/15-04, 1103/15-05)
#### 옮긴 뒤 확인
@@ -127,12 +212,13 @@
1. 로컬 merge 게이트 14개를 돈다(README "CI and evidence"의 반복문). `config/ci/product-gates.json`에 적은 `PRODUCT-GATE-NNN`은 workflow의 `product_merge_gate` job이 돈다.
2. 그중 이 묶음 때문에 먼저 볼 것:
- `check:registries`: `11 registries PASS`. 기준선을 다시 승인한 뒤에는 `compatibility=none`.
- `test:unit`: `schema-metadata-policy`, `env-registry-coverage`, `feature-shape-growth`.
- `test:unit`: `schema-metadata-policy`, `env-registry-coverage`, `feature-shape-growth`, `documentation-readiness`(문서 검사. 참조 기능을 지운 제품도 통과한다).
- `test:component`: `layout-landmarks`, `context-layouts`.
- `build` 뒤 `check:bundle`: 예산 안.
- `verify:documentation`(FE-GATE-017): 참조 기능을 지운 제품도 통과한다.
- `test:sample-removal -- --feature=<제품 기능 id>`: 그 기능을 지운 사본이 게이트를 통과한다.
3. 배포가 있는 제품: FE-GATE-019는 TLS ALPN `h2`와 entry 응답의 `Content-Encoding`(br·gzip·zstd)을 요구한다. HTTP/1.1이나 압축하지 않는 호스트는 FAIL이다.
3. merge 게이트 밖에서 한 번 돈다.
- `verify:documentation`(FE-GATE-017, documentation 단계). merge 단계에서는 FE-GATE-005의 `documentation-readiness`가 같은 스크립트를 돈다.
- `test:sample-removal -- --feature=<제품 기능 id>`: 그 기능을 지운 사본이 게이트를 통과한다. FE-GATE-020은 참조 기능만 지워 본다.
4. 배포가 있는 제품: FE-GATE-019는 TLS ALPN `h2`와 entry 응답의 `Content-Encoding`(br·gzip·zstd)을 요구한다. HTTP/1.1이나 압축하지 않는 호스트는 FAIL이다.
### 보안·계약 변경
@@ -147,7 +233,7 @@
| [계약] | 기능 어댑터 기여는 실행 중에도 `needs`에 적은 capability만 받는다. cast로 다른 capability를 읽던 기능은 `undefined`를 받는다 (1103/09-08) | `src/features/feature-adapter-contribution.ts` | `e7d6358` |
| [계약] | 기능 계약이 route id `APP_HOME`을 선언하면 플랫폼 홈을 대신한다. 둘이 선언하면 두 기능 id를 적고 실패한다. `src/contexts/<context>/context-layout.tsx`가 `CONTEXT_LAYOUT`을 내보내면 그 context의 라우트가 AppShell 대신 그 레이아웃 아래에 놓인다. 레이아웃은 skip link와 `<main id="main-content" tabIndex={-1}>` 하나를 그려야 하고, `tests/component/layout-landmarks.test.tsx`가 설치된 레이아웃을 모두 실행해 본다 (1101/09-03) | `src/contracts/routes.ts`, `src/contexts/bounded-context-module.ts`, `scripts/generate-product-feature-index.ts`, `tests/component/layout-landmarks.test.tsx` | `ca16187`, `27f4523` |
| [계약] | 앱 조립이 닿지 않는 기능 라우트를 앱 모듈을 평가할 때 throw로 거절한다. 소유 context 루트 밖의 라우트, 계약에 없는 route handle, 플랫폼 라우트가 먼저 받는 경로, 다른 기능과 같은 경로(파라미터 이름만 다른 것과 대소문자·끝 슬래시만 다른 것 포함)다. 시작할 런타임이 없는 선택 capability(realtime·webWorkers·offlineCommands)도 거절한다 (1101/09-06, 1101/09-07, 1103/08-04, 1101 README 14.4) | `src/apps/deployable-app-module.ts`, `src/contexts/bounded-context-module.ts`, `src/bootstrap/` | `7139c7c`, `d6e4e51`, `7d85589`, `8469554`, `851fded`, `48a4074` |
| [계약] **BREAKING** | 예제 화면 `EXAMPLES_UI`·`EXAMPLES_STATES`·`EXAMPLES_AUTH`가 끌 수 있는 기능 `platform-examples-feature`(context `platform-examples-context`, 루트 `examples/*`)로 옮겼다. 페이지 파일은 그 기능의 `presentation/`에 있다. `PLATFORM_ROUTE_REGISTRY`·`PLATFORM_ROUTE_RUNTIME_CONTRACT`·`PLATFORM_ROUTE_RUNTIME`에서 키가 빠졌다. 홈 문구 `home.starter.platform`·`ui`·`states`는 `home.starter.open({title})`로 바뀌었다. 예제를 지운 제품은 이 기능 폴더와 context를 지운다. `/examples/platform`은 플랫폼 라우트로 남는다 (1103/09-04) | `src/features/platform-examples-feature/`, `src/contexts/platform-examples-context/`, `src/contracts/routes.ts` | `b96d61d` |
| [계약] **BREAKING** | 예제 화면 `EXAMPLES_UI`·`EXAMPLES_STATES`·`EXAMPLES_AUTH`가 끌 수 있는 기능 `platform-examples-feature`(context `platform-examples-context`, 루트 `examples/*`)로 옮겼다. 페이지 파일은 그 기능의 `presentation/`에 있다. `PLATFORM_ROUTE_REGISTRY`·`PLATFORM_ROUTE_RUNTIME_CONTRACT`·`PLATFORM_ROUTE_RUNTIME`에서 키가 빠졌다. 홈 문구 `home.starter.platform`·`ui`·`states`는 `home.starter.open({title})`로 바뀌었다. 예제를 지운 제품은 이 기능 폴더, 그 테스트 폴더, context를 지운다(위 "먼저 할 일" 6단계). `/examples/platform`은 플랫폼 라우트로 남는다 (1103/09-04) | `src/features/platform-examples-feature/`, `src/contexts/platform-examples-context/`, `src/contracts/routes.ts` | `b96d61d` |
| [계약] | 계약 기여의 출처는 `EXTERNAL_PACKAGE`이고, `TEMPLATE_FIXTURE`는 참조 기능만 하나 쓸 수 있다. 다른 출처 종류는 `unknown contribution source kind`로 거절한다 (1101/07-04) | `src/contracts/external-contract-runtime.ts` | `c063389` |
| [계약] **BREAKING** | `useApplicationMutation`은 raw `{ execute, definitionId }`를 받지 않는다. `useServerStateScope()`의 scope로 만든 `BoundMutation`을 넘기고 `execute(input, { signal, intent })`로 부른다. `commandMutationIdentity(<descriptor>)`가 `operationId`·`requiresIdempotencyKey`를 descriptor에서 준다. `QueryDefinition.owner`·`operationId`와 `BoundMutation.owner`는 아무도 읽지 않아 `@deprecated` 선택 칸으로 바꿨고 다음 릴리스에서 지운다. raw query는 남았다. 세션이 바뀌면 이전 결과가 보이지 않는다(JSDoc에 위험 표기) (1101/08-03, 1103/16-05, 1101/03-03, 1103/16-06) | `src/presentation/adapters/query/application-query.ts`, `src/presentation/adapters/query/` | `1fa5f3e`, `f59a806`, `68f94f5` |
@@ -209,7 +295,7 @@
| 표시 | 변경 | 영향 경로 | 커밋 |
|---|---|---|---|
| [계약] **BREAKING** | `BoundedPollOperationContract`(V2 어휘)를 지웠다. `createBoundedPollCoordinator`의 operation과 `assertBoundedPollOperation`의 둘째 인자는 V3 descriptor(`BoundedPollOperation`)다. 조립된 행을 넘기고, `frontend.retryBudget` 0인 poll 전용 operation을 등록한다. 0이 아니면 생성 때 거절한다 (1103/04-01) | `src/adapters/realtime/` | `a65df74` |
| [계약] **BREAKING** | SSE의 fetch·reader 거절과 bounded poll의 execute 거절은 `OFFLINE` 대신 `PROVIDER_UNAVAILABLE`(retryable)로 끝난다. 브라우저가 online이면 online 이벤트를 기다리지 않고 backoff로 다시 시도하고 상한에서 끝난다. poll은 던지는 execute도 lease 안에서 다시 시도한다. `OFFLINE`은 환경 신호에서만 나온다 (1103/04-04, 0929/04-01) | `src/adapters/realtime/` | `af00067`, `4d27b20` |
| [계약] **BREAKING** | SSE의 fetch·reader 거절과 bounded poll의 execute 거절은 `OFFLINE` 대신 `PROVIDER_UNAVAILABLE`(retryable)로 끝난다. 브라우저가 online이면 online 이벤트를 기다리지 않고 backoff로 다시 시도하고 상한에서 끝난다. poll은 이 범위 끝에서 던지는 execute를 lease 안에서 다시 시도했다. 위 절에서 다시 바뀌어, 던지는 execute는 재시도 없이 `PROTOCOL_MISMATCH`로 끝난다(1105/04-02). `OFFLINE`은 환경 신호에서만 나온다 (1103/04-04, 0929/04-01) | `src/adapters/realtime/` | `af00067`, `4d27b20` |
| [계약] | stream coordinator와 live-poll handoff coordinator의 마감 실패가 `IDLE_TIMEOUT` 대신 `APPLY_FAILED`·`PROVIDER_UNAVAILABLE`로 나온다. stream coordinator의 `RealtimeObservation.reason`도 같다. `IDLE_TIMEOUT`은 전송 idle에만 쓴다 (1101/04-02) | `src/adapters/realtime/stream-coordinator.ts`, `src/adapters/realtime/` | `1196b86`, `17fa8d1` |
| [계약] | realtime 배럴이 결과 생성 함수 `realtimeSuccess`·`realtimeFailure`를 내보낸다. 동결이 필요한 경계에 직접 만든 결과를 넘기던 코드는 이 함수로 바꾼다 (1101/04-01) | `src/adapters/realtime/index.ts` | `3fe28de` |
| [계약] | Service Worker 빌드가 `public/`을 다시 복사하지 않는다(`publicDir: false`). 전에는 SW를 켠 빌드의 `dist/config.json`이 local 문서로 덮어써졌다 (0929/06-01) | `vite.service-worker.config.ts`, `scripts/build-frontend.ts` | `c7b9cb8` |
@@ -228,7 +314,7 @@
| 표시 | 변경 | 영향 경로 | 커밋 |
|---|---|---|---|
| [계약] | 번들 예산 게이트 FE-GATE-012가 merge 단계에서 돈다. 예산은 gzip 204,800 B와 초기 파일 26개(`initialJsFiles`)다. `check:bundle`은 넘은 한도와 초과량을 적고, `bundle.json`에 `initialJsFiles`·`initialFilesPassed`가 있다. 초기 JS 기준선은 `config/scale/feature-shape-ceilings.json`의 `initialJavascript`(지금 202,927 B, 26개, 기능 하나 +768 B, context 하나 +233 B)이고 `test:unit`이 빌드와 대조한다 (1101/15-01, 1103/15-05, 1103/15-03, 1103/15-02, 1103/15-04) | `config/ci/gates.json`, `config/performance/budgets.json`, `scripts/check-bundle.ts`, `config/scale/` | `f41e3d5`, `46dfe23`, `1b8cb12`, `c9e7bab`, `f887817` |
| [계약] | 번들 예산 게이트 FE-GATE-012가 merge 단계에서 돈다. 예산은 gzip 204,800 B와 초기 파일 32개(`initialJsFiles`, 템플릿 26개 + 기능 여유)다. `check:bundle`은 넘은 한도와 초과량을 적고, `bundle.json`에 `initialJsFiles`·`initialFilesPassed`가 있다. 초기 JS 기준선은 `config/scale/feature-shape-ceilings.json`의 `initialJavascript`(지금 202,927 B, 26개, 기능 하나 +768 B, context 하나 +233 B)이고 `test:unit`이 빌드와 대조한다 (1101/15-01, 1103/15-05, 1103/15-03, 1103/15-02, 1103/15-04) | `config/ci/gates.json`, `config/performance/budgets.json`, `scripts/check-bundle.ts`, `config/scale/` | `f41e3d5`, `46dfe23`, `2fef27d`, `c9e7bab`, `f887817` |
| [계약] | 호스팅 계약: 파일이 없는 모든 경로에 그 release의 `index.html`을 HTML 헤더로 준다(SPA fallback, `appRoute`). 워커를 싣는 빌드의 `service-worker.js`는 `no-cache`다. live probe는 사전 캐시 확장자마다 `Content-Type`을 확인한다. nginx 예시는 `docs/operations/release-cache-rollback.md` (1101/13-04, 1103/06-03) | `config/hosting/cache-policy.json`, `scripts/lib/hosting-probe.ts`, `scripts/verify-hosting-headers.ts` | `629c8f0`, `0f58abb` |
| [계약] | FE-GATE-019(production 단계)는 workflow의 `deployment` 슬롯이 배포한 승격 release를 본다. 슬롯이 비어 있으면 `UNVERIFIED`다. 배포된 `release-manifest.json`의 buildId·releaseId, `config.json`(비상 스위치 제외), `index.html` entry가 후보와 다르면 FAIL이다. TLS ALPN `h2`와 entry `Content-Encoding`(br·gzip·zstd)을 요구한다(`config/hosting/cache-policy.json`). HTTP/1.1이나 비압축 호스트는 FAIL이다. nginx 예시가 http2·gzip을 켠다 (1101/13-01, 1103/13-01, 1103/13-02) | `.gitea/workflows/quality-gates.yml`, `config/ci/gates.json`, `config/hosting/cache-policy.json`, `scripts/verify-hosting-headers.ts` | `de379ea`, `4bce8bf`, `2e12d2f` |
| [계약] | 제품 소유 `config/ci/product-gates.json`: 배포(`deployment`, package script와 `vars.*`·`secrets.*` 바인딩)와 제품 merge 검사(`PRODUCT-GATE-NNN`, job `product_merge_gate`). 템플릿은 승격 후보를 받아 `CANDIDATE_ARCHIVE_SHA256`으로 확인하고 푸는 단계를 만든다. 배포 슬롯은 `gates.json`이 아니라 여기서 채운다 (1103/12-07, 1103/13-01) | `config/ci/product-gates.json`, `scripts/contracts/product-ci-overlay.ts`, `scripts/generate-ci-workflow.ts` | `4c4248a`, `2e12d2f` |
@@ -261,7 +347,7 @@
- 레지스트리 도구: `check:registries`가 조립 실패의 `reason`을 적고, 읽지 못한 레지스트리를 지운 것으로 세지 않는다 (1103/14-06). FE-REG-SCHEMA 행의 `direction`·`unknownFieldPolicy`·`boundary`를 검증기·쓰임과 대조한다 (1103/07-03, 1103/16-04). 금지 조각이 든 런타임 설정 키를 `test:unit`이 이름과 함께 막는다 (1103/07-04). `check:feature-index` 예외 이유를 실제 사용처로 고쳤다 (1101/12-05)
- 아키텍처 검사: zod 하위 경로(`zod/v4` 등) import도 `src/contracts/zod.ts`를 거쳐야 한다 (`64f19ac`, 1103 07 영역 P-07-06). 금지 fixture를 그 계층의 운영 ESLint 설정으로 검사하고 fixture 전용 블록을 지웠다 (1103/12-04). adapter kernel 설명을 실제 `platform` 폴더 내용에 맞췄다 (`3f72ae7`). 두 오류 어휘(`AppFailure`·`AppError`)와 `commandRecovery`를 누가 읽는지 타입 옆에 적었다 (1101/07-05, 1101/07-07)
- 게이트·드릴: coverage 증거 검사(FE-GATE-005)가 istanbul summary의 `branchesTrue`를 받는다 (1103/12-09). compact smoke e2e가 빌드에 준 `VITE_BUILD_ID`를 기대해 CI 값에서 FE-GATE-008이 항상 실패하지 않는다 (1103/11-06). vitest와 dev server를 띄우는 Playwright 설정(capabilities, dev)이 CI의 `VITE_BUILD_ID`·`VITE_COMMIT_SHA`를 물려받지 않는다. 전에는 CI env에서 앱을 local-build fixture로 조립하는 테스트와 capability e2e가 `CONFIG_BUILD_MISMATCH`로 떨어져 FE-GATE-005·006·007·008·020이 항상 실패했다 (1103/11-07). 테스트가 만드는 로컬 빌드(fixture 빌드, 시각 골든 build, 브라우저 테스트의 dev server)는 `CI=true`에서도 release 빌드로 검사되지 않는다(`localBuildEnvironment`, `LOCAL_BUILD_IDENTITY`). 전에는 workflow env에서 FE-GATE-005·008·020이 실패했다 (1103/11-08). 브라우저 테스트의 strict fixture가 WebKit의 "preload했지만 몇 초 안에 쓰지 않았다" 경고 문구만 무시하고, 대신 preload된 build script가 실제로 실행됐는지를 세 엔진에서 검사한다(`preloadunused:`, `tests/support/browser/preload-use.ts`). WebKit은 load 3초 뒤 한 번 추정해서, 곧 쓰일 청크를 preload한 화면에서 FE-GATE-008이 가끔 떨어졌고 정말 안 쓴 preload는 놓쳤다. build script를 직접 fulfill하는 test는 `fulfillBuildScript`를 쓴다 (1103/11-09). browser capability의 파일 선택·다운로드 test가 붙이는 버튼을 앱 위 고정 층에 둔다. 앱이 그리는 도중 내용이 자라 클릭 사이에 버튼이 움직였고, 클릭이 버튼에 닿지 않아 firefox에서 FE-GATE-008이 가끔 30초 시간 초과로 떨어졌다 (1103/11-10). capability 제거 드릴 3개가 문서 테스트 `ENOENT`로 항상 실패하던 것을 고쳤다. 문서를 읽는 테스트 목록은 `scripts/lib/removal-fixture.ts` 한 곳이다 (1103/02-06). `test:sample-removal`이 문서를 복사해 `lint`·`verify:documentation`·`check:i18n`·`check:design-system`을 돈다 (1103/14-04). 제품 기능 제거 드릴이 CI 기준선 사유 공백으로 멈추지 않는다 (1103/16-02). `test:system` provider 묶음 30초 예산 (1103/11-03), scope wrapper EOF 테스트 (1103/10-01)와 IndexedDB 차단 업그레이드 테스트 (1103/11-05)의 부하 원인을 없앴다. `artifacts/**/*.log`를 추적하지 않는다 (1103/12-08)
- 기능 추가 뒤 검증(리뷰 조치 X2): [계약] `create:feature`와 기능 제거 드릴이 dev server의 manifest(`public/release-manifest.json`)의 contract set을 설치된 기능으로 다시 쓴다(`node scripts/write-dev-release-manifest.ts`). 기능과 함께 커밋한다. 낡으면 `tests/unit/dev-release-manifest.test.ts`가 실패한다. 전에는 `create:feature` 직후 dev server와 dev server를 쓰는 capability e2e가 `CONTRACT_SET_PACKAGE_MISSING`으로 부팅하지 못했다 (1103/16-09). dev server가 `artifacts/`·`dist/`·`.tmp/`를 감시하지 않는다. 기능 제거 드릴(`test:sample-removal -- --feature=<id>`)이 지운 뒤 초기 JS 기록을 다시 쓴다 (1103/15-02). 초기 JS 파일 상한이 32다(템플릿 26 + 여유) (1103/15-05). Fileserver 업로드 client가 browser-file-storage 포트를 import하지 않아 그 런타임을 지워도 남는다(`FileserverByteSource`) (1103/01-01). 제품 확장 타입 검사 탐침이 예약 이름(`typecheck-probe-*`)을 쓰고 제품의 capability 선언을 덮어쓰지 않는다 (1103/09-02). 시각 골든 build와 storybook workshop spec이 CI 식별값·a11y 애드온 자동 검사와 겹치지 않는다 (1103/11-07)
- 기능 추가 뒤 검증(1103 README 14.6 X2): [계약] `create:feature`와 기능 제거 드릴이 dev server의 manifest(`public/release-manifest.json`)의 contract set을 설치된 기능으로 다시 쓴다(`node scripts/write-dev-release-manifest.ts`). 기능과 함께 커밋한다. 낡으면 `tests/unit/dev-release-manifest.test.ts`가 실패한다. 전에는 `create:feature` 직후 dev server와 dev server를 쓰는 capability e2e가 `CONTRACT_SET_PACKAGE_MISSING`으로 부팅하지 못했다 (1103/16-09). dev server가 `artifacts/`·`dist/`·`.tmp/`를 감시하지 않는다. 기능 제거 드릴(`test:sample-removal -- --feature=<id>`)이 지운 뒤 초기 JS 기록을 다시 쓴다 (1103/15-02). 초기 JS 파일 상한이 32다(템플릿 26 + 여유) (1103/15-05). Fileserver 업로드 client가 browser-file-storage 포트를 import하지 않아 그 런타임을 지워도 남는다(`FileserverByteSource`) (1103/01-01). 제품 확장 타입 검사 탐침이 예약 이름(`typecheck-probe-*`)을 쓰고 제품의 capability 선언을 덮어쓰지 않는다 (1103/09-02). 시각 골든 build와 storybook workshop spec이 CI 식별값·a11y 애드온 자동 검사와 겹치지 않는다 (1103/11-07)
- 테스트: Testing Library 대기 기한을 `tests/setup.ts` 한 곳에서 5초로 정했다 (0929/10-01). `npx vitest`나 npm을 거친 IDE 실행기로 돌려도 실패하지 않는다 (1101/15-05). cgroup 시스템 테스트가 실행 단계가 남긴 PID·argv 기록을 읽는다 (1101/11-01). exact-five CLI 테스트가 실제 출력 문구를 기대한다 (0929/11-01). guardian이 실패하면 stdin을 기다리지 않고 끝난다 (`3c175a5`). 계약 조립기의 쓰기 API 규칙 5개 (1101/07-06), 이벤트 계약 검증 (1101/10-01), Envelope 판정 경계와 처리 중 409 무재전송 (1103/10-02), `MAX_RETRY_ATTEMPTS` 전달과 signal listener 정리 (1103/10-04)를 테스트로 고정했다. 규모 측정 기준선을 다시 쟀고 측정용 기능 복사본은 외부 패키지를 고정한다 (`9333595`, 1101/07-04). 설치 기능이 0개여도 타입 검사와 커버리지가 통과한다 (`e4ace51`, 1101/15-01)
- 테스트: 플랫폼 component 테스트가 스타터 화면 대신 테스트 전용 페이지(`tests/helpers/fixture-feature.tsx`)를 쓴다. 스타터 화면을 바꾸는 제품은 `tests/component/starter-*.test.tsx`를 함께 지운다. HTTP 시나리오 증거(FE-GATE-007)와 기능 API 타입 음성 fixture(FE-GATE-003)는 샘플을 지워도 남는다 (0929/10-02). 기능 테스트는 `createHttpScenarioHandler(<설치 계약>, { scenario, payload })`로 공유 MSW 시나리오를 쓰고, `tests/mocks/**`는 플랫폼 소유다 (1101/16-02, 1101/16-01). SW e2e가 제품이 켠 worker와 빌드가 만든 사전 캐시 목록을 쓴다 (0929/11-03, 0929/06-04). 접근성 e2e가 설치된 descriptor의 경로와 `responseEnvelope`로 빈 목록을 답하고 목록 화면에 경고 상자가 없음을 단언한다. 기능을 더해도 spec을 고치지 않는다 (1103/11-01, 1103/16-03)
- 참조 기능: 샘플 페이지가 `referenceRouteUrl(routeId, input)`으로 링크를 만들고 route 입력 cast를 없앴다. `REFERENCE_FEATURE_ROUTE_CODECS`는 `presentation/reference-route-codecs.ts`에 있다. 목록 링크 href는 `?limit=20`이 붙은 정식 URL이다 (1101/16-04). `create:feature --context reference-context`로 만들어도 참조 라우팅 테스트가 깨지지 않는다 (`e8c4197`)
@@ -270,23 +356,24 @@
### 알려진 제한
이 절을 쓴 끝 커밋(`f887817`)에서 사실인 것만 적었다.
이 절의 범위 끝(브랜치 `fix/maturity-review-2026-11-03`의 `8a44226`)에서 사실인 것만 적었다. 위 절이 바꾼 것은 위 절에 적는다.
- 다운스트림 이행: 위 안내를 두 제품 코드에 적용해 게이트를 돌려 보지 않았다. memento-web의 숫자(descriptor 29개, schemaId 42개 + `MementoProblem`)는 memento `d3810a0`을 정적으로 센 값이다.
- 두 제품이 고친 템플릿 파일 중 제품 소유 자리가 없는 것("옮기기 전" 2단계의 셋째 항목: memento의 `if-match`·오프라인 shell·저장소 이름·브랜드 토큰, tech-log의 `AppFailure.detail`·`BoundMutation.identity`·`null` 빈 상태·디자인 시스템 등)은 이 묶음이 옮길 곳을 주지 않는다. 동기화 때 충돌하거나 제품이 고친 채로 남는다. 어느 것을 템플릿에 들일지는 정하지 않았다.
- 직접 조립 제품(tech-log의 TechLog): 템플릿에 그 자리가 없다. 기능 모듈로 바꾸는 길은 fixture(`tests/helpers/fixture-layout-product.tsx`)로만 검사했고 TechLog 화면으로는 해 보지 않았다. 직접 조립을 유지하면 FE-REG-API·FE-REG-SCHEMA와 스키마 메타 대조 테스트가 TechLog descriptor를 보지 않는다.
- 제품 안에 적은 계약(memento `PRODUCT_LOCAL_CONTRACT`)에 줄 출처 종류가 없다. `EXTERNAL_PACKAGE` 신원을 어떻게 정할지(패키지 없이 digest를 붙이는 법)는 템플릿이 정하지 않았다.
- 참조 기능은 `responseEnvelope`를 선언하지 않아 DTO와 problem details만 읽는다. 짝 백엔드에 붙는 완성 예시는 `create:feature --with-create`가 만드는 기능이다.
- 참조 기능은 DTO와 problem details만 읽는다(이 범위 끝에서는 `responseEnvelope`를 선언하지 않았고, 위 절에서 필수 칸이 되어 `"NONE"`을 적는다). 짝 백엔드에 붙는 완성 예시는 `create:feature --with-create`가 만드는 기능이다.
- 짝 백엔드 생성기(`new-feature.sh`)에 목록 GET이 없다. `create:feature` 목록 화면은 백엔드가 `GET /<plural>`을 더한 뒤에야 닿는다 (1103/03-07).
- 짝 백엔드 계약 pin은 `45d2a478`(2026-11-05)이다. 그 뒤 백엔드가 바뀌면 `check:backend-contract-drift --backend <백엔드 checkout>`가 알린다. 이 검사는 게이트 밖이라 CI는 알리지 않는다.
- 업로드: 백엔드 `POST /v1/files`는 `Idempotency-Key`를 읽지 않는다. 결과 불명 뒤 같은 키로 다시 보내도 파일이 둘 생길 수 있다. client의 code 목록은 백엔드 기준점에 묶여 있다. `EXTERNAL_BEARER`로 올리려면 제품 provider가 필요하다. 실제 백엔드 업로드와 firefox·webkit은 돌리지 않았다.
- 세션 owner recipe는 실제 Keycloak·Redis와 붙여 보지 않았다. jwt 모드: 백엔드 realm에 브라우저용 public client가 없어 제품이 더한다(매뉴얼 04에 JSON). redis-session 모드: 백엔드 운영 코드에 로그인·로그아웃·세션 조회·CSRF 발급 엔드포인트가 없어 owner가 URL을 기본값 없이 받는다. OIDC owner는 토큰을 메모리에 두어 새로고침하면 로그아웃되고, ID token 서명을 검사하지 않는다.
- 플랫폼 구성 화면(`EXAMPLES_PLATFORM`, `/examples/platform`)은 플랫폼 라우트라 끌 수 없고 FE-GATE-028 서명 대상이다. 예제 기능을 뺀 제품에서 예제 화면을 여는 e2e·visual spec은 실패한다 (1103/09-04).
- 기능 라우트 첫 진입(실행부 청크, 약 430 ms)은 어느 게이트도 재지 않는다.
- 기능 라우트 첫 진입(실행부 청크, 약 430 ms)은 이 범위 끝에서 어느 게이트도 재지 않았다. 위 절에서 lab이 `EXAMPLES_UI` 첫 진입을 500 ms 예산으로 잰다. 요청 두 묶음은 그대로다(1105/15-04).
- 초기 JS 여유가 1,873 B다. `--with-create` 기능 하나(약 +964 B)를 넣으면 약 900 B가 남는다.
- 운영 의존성 high advisory 2건이 남았다: `zod` 4.4.3 GHSA-mrhx-c7xc-m3w5(고치는 버전은 초기 JS 약 +7 KB로 예산을 넘는다), `react-router` 7.18.1 GHSA-qwww-vcr4-c8h2(약 +470 B). 둘 다 owner와 다른 reviewer의 `config/security/dependency-change-evidence.json` 항목이 필요하다. moderate 2건(`minimatch`, `glob`)은 major 범위 밖이다.
- 실제 Gitea runner, 실제 HTTPS 호스트, nginx 예시에서는 돌리지 않았다. FE-GATE-019 배포 슬롯은 주입한 fetcher로만 시험했다.
- `test:feature-scaffold` 한 번이 513~866초 걸린다(부하에 따라). FE-GATE-020 job 상한은 45분이다. 브라우저 게이트는 scaffold 드릴 밖이다. 짝 저장소 참조(1103/12-05)는 CI와 중첩 worktree에서 `not verified`다.
- Service Worker를 켠 제품의 `composeProduct` 쪽 칸(SW blocker·observe)은 없다 (1103/09-05). SW e2e와 실제 live probe는 이 묶음에서 돌리지 않았다.
- Service Worker를 켠 제품의 `composeProduct` 쪽 칸(SW blocker·observe)은 이 범위 끝에서 없었다. 위 절에서 `ProductComposition.serviceWorker`가 생겼다 (1103/09-05). SW e2e와 실제 live probe는 이 묶음에서 돌리지 않았다.
- OPFS: `logicalKey`까지 깨진 행은 staging에 남을 틈이 있고, 같은 lock 대기 상한이 partition 삭제에도 걸린다. `dispose()`는 `scopeParticipants`를 부르지 않는다. 실제 로그아웃 E2E는 없다.
- 라우트 계약의 `title`·`navigationLabel`은 화면이 읽지 않는다(catalog가 읽는다) (1103/16-06). 키보드 저장 실패 포커스는 스크린리더로 확인하지 않았다 (1103/08-02).
+1 -1
View File
@@ -30,7 +30,7 @@ web
- 하나의 디자인 시스템으로 세 종류의 서비스를 받칩니다. 업무용·관리 도구(대시보드, 어드민, 설정), 일반 사용자용 웹 서비스, 소개·랜딩 페이지입니다.
- 디자인 시스템 위치는 `src/presentation/design-system/`입니다. 토큰은 primitive → semantic → component 세 단계로 파생됩니다(`tokens/primitive.css`, `semantic.css`, `component.css`).
- 시각 회귀 골든이 `tests/visual/__snapshots__/`에 있습니다. 화면을 바꾸면 골든도 의도적으로 갱신해야 합니다.
- 참조 기능(`src/features/reference-feature/`)은 `test:sample-removal`로 지울 수 있습니다. 예제 라우트 4개(`/examples/platform`, `ui`, `states`, `auth`)와 홈은 기본 구성이고 제거 드릴이 없습니다. 그래서 예제 화면에만 넣은 디자인은 파생 서비스에 그대로 남습니다.
- 참조 기능(`src/features/reference-feature/`)은 `test:sample-removal`로 지울 수 있습니다. 예제 화면 3개(`/examples/ui`, `states`, `auth`)도 기능 `platform-examples-feature`라서 같은 드릴(`test:sample-removal -- --feature=platform-examples-feature`)로 지울 수 있습니다. 플랫폼 구성 화면(`/examples/platform`)과 홈은 기본 구성이고 제거 드릴이 없습니다. 그래서 예제 화면 3개에만 넣은 디자인은 예제를 지운 파생 서비스에서 함께 사라지고, 홈과 플랫폼 구성 화면에 넣은 디자인은 남습니다.
- 어떤 서비스가 먼저 만들어질지, 서비스별 우선순위는 아직 정하지 않았습니다.
## Brand Commitments
+29 -4
View File
@@ -174,7 +174,7 @@ See
`docs/architecture/frontend-application-foundation.md`,
`docs/architecture/overview.md`, `docs/architecture/layers.md`, and
`docs/architecture/starter-experience.md`. The removable vertical slice is
the reference sample, src/features/reference-feature; its domain, application input, HTTP
under `src/features/reference-feature`; its domain, application input, HTTP
binding, contracts, route runtime, and presentation own their contributions.
The central installed catalogs only aggregate selected contributions. The
generic starter routes continue to typecheck, test, and build after that
@@ -232,8 +232,12 @@ reads them, except the one file noted below
The reference feature is not in this list: deleting its directory alone
leaves tests, policy entries and CI scripts behind that fail the gates.
`scripts/test-sample-removal.ts` removes it from a copy of
the repository and lists everything that has to go with it (its header comment
and `SAMPLE_EXTRAS`); do the same in your project and run the gates.
the repository and lists everything that has to go with it (its header comment,
and the files outside the feature's folders in
`scripts/lib/removable-template-features.ts`); do the same in your project and
run the gates. The documents keep naming the sample's paths: the documentation
check accepts them once `src/features/reference-feature/feature-module.ts` is
gone.
## Verification
@@ -333,7 +337,7 @@ bubblewrap may create unprivileged user and network namespaces, which Ubuntu
23.10 and later refuse by default — its first step says so, and
`docs/operations/ci-quality-gates.md` lists the fixes). Product checks listed in
`config/ci/product-gates.json` (`PRODUCT-GATE-NNN`) run in the workflow's own
`product_merge_gate` job:
`product_merge_gate` job, which the release stage waits for:
```bash
for gate in 001 002 003 004 005 006 007 008 009 010 011 012 013 020; do
@@ -355,6 +359,13 @@ export CI=true VITE_COMMIT_SHA="$(git rev-parse HEAD)" VITE_BUILD_ID=local-ci-1
Machine-readable evidence is written below `artifacts/`; generated evidence is
ignored by Git while `.gitkeep` files preserve the taxonomy.
Run the gates one at a time in a checkout: they and the evidence checks read
the fixed `dist/` and `artifacts/` paths. Two Playwright runs can share a
checkout when each has its own `TEST_RUN_ID`; its build, results and report go
below `.tmp/runs/<id>/`. The test servers always pick a free port. The
variables are listed in `docs/testing/frontend-platform-testing-strategy.md`
(13.6).
Operational details are in `docs/operations/`, with incident procedures in
`docs/runbooks/`.
@@ -382,6 +393,20 @@ git log --oneline <your origin>..template/main # what changed since you copied
git cherry-pick -x <commit> # one fix; -x records its origin
```
Take an unreleased range as a whole. A repository that shares the template's
history merges the range's branch. One that does not (it started from a copy
of the files) merges three-way against the range base, which leaves the files
both sides changed as conflicts; resolve them and commit:
```bash
git merge --no-ff template/<range branch> # shared history
git merge-recursive <range base> -- HEAD template/<range branch> # no shared history
```
Keep the base you synced from where your project records it: `.template-origin`
(below), or your own lock file (tech-log keeps it as `sourceRevision` in
`template.lock.json`). Move it to the range end once the range is in.
When the files have moved or diverged too far for a clean pick, read the
change as a diff and apply it by hand:
+2 -2
View File
@@ -1,11 +1,11 @@
{
"schemaVersion": 1,
"owner": "DongHyeonka",
"reason": "1103/13-03: FE-GATE-027 also runs scan:dependency-advisories, a non-blocking release-stage advisory signal",
"reason": "1105/12-01: FE-GATE-013 hostRequirements are part of the reviewed gate shape",
"gates": 27,
"commands": 100,
"commandReferences": 104,
"artifacts": 110,
"stages": 5,
"gateShapeSha256": "6225494d6447a2065d921a34597a744d180a7a68e601119e32f8fc42e18eb1c1"
"gateShapeSha256": "7bebafe65d528be6a59d4bb70edd2cad99455b2b49087e4a46b83d77bfd163de"
}
+1 -1
View File
@@ -3,7 +3,7 @@
"entries": [
{
"script": "check:backend-contract-drift",
"reason": "1103/12-06. Compares the paired backend checkout next to this repository with the commit config/contracts/backend-contract-pin.json pins. CI checks out this repository alone, so a gate has no backend to read; with no checkout the script reports skipped. The gated half of the pin is tests/unit/backend-contract-pin.test.ts (test:unit), which holds the Envelope table to the copied backend answer table. Run this before moving the pin."
"reason": "1103/12-06, 1105/07-01. Compares the paired backend checkout (--backend, or beside the main checkout) with config/contracts/backend-contract-pin.json: the copied table excerpt and the answer table against the pinned document, and the document between the pin and the backend's HEAD. CI checks out this repository alone, so a gate has no backend to read; with no checkout the script exits 2 (not compared), never 0. The gated half is tests/unit/backend-contract-pin.test.ts (test:unit), which holds the Envelope table to the answer table and the answer table to the excerpt. Run this after pulling the backend and before moving the pin (docs/manual/01-add-a-feature.md)."
},
{
"script": "check:feature-index",
+37 -3
View File
@@ -4,7 +4,39 @@
"repository": "clean-architecture-backend-template",
"commit": "45d2a478b800586f1d84151723629a560265d58e",
"document": "docs/web/http-contract.md",
"sectionsCompared": ["1", "2", "4"]
"sectionsCompared": ["1", "2", "4"],
"scaffoldSources": [
{
"path": "scripts/new-feature.sh",
"fact": "path segment: camel-case name plus es, ies or s",
"copiedTo": { "file": "scripts/create-feature.ts", "symbol": "backendPathSegment" }
},
{
"path": "scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl",
"fact": "NAME_MAX_LENGTH 100",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "BACKEND_NAME_MAX_LENGTH" }
},
{
"path": "scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/__Feature__ErrorCode.java.tmpl",
"fact": "error codes <FEATURE>_INVALID and <FEATURE>_NOT_FOUND",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "invalidCode" }
},
{
"path": "scripts/feature-scaffold/templates/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__ControllerTest.java.tmpl",
"fact": "400 <FEATURE>_INVALID and 404 <FEATURE>_NOT_FOUND bodies",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "notFoundCode" }
},
{
"path": "scripts/feature-scaffold/templates/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/__feature__/__Feature__Controller.java.tmpl",
"fact": "POST /<plural> answers 201, GET /<plural>/{id} reads one",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "renderWriteDescriptors" }
},
{
"path": "scripts/feature-scaffold/templates/src/application-core/src/main/java/dev/caskeleton/application/__feature__/Create__Feature__UseCase.java.tmpl",
"fact": "permission, then name check, then the write: refused before the write",
"copiedTo": { "file": "scripts/create-feature-write-slice.ts", "symbol": "refusedBeforeWrite" }
}
]
},
"frontend": {
"contractDocument": "docs/architecture/backend-api-and-server-state-contract.md",
@@ -12,8 +44,10 @@
"readers": ["src/adapters/http/backend-envelope.ts"]
},
"tables": {
"idempotencyAnswers": "config/contracts/backend-idempotency-answers.json"
"idempotencyAnswers": "config/contracts/backend-idempotency-answers.json",
"backendExcerpt": "config/contracts/backend-http-contract-excerpt.json"
},
"notCopied": [],
"owner": "frontend-platform",
"comparedOn": "2026-11-04"
"comparedOn": "2026-11-05"
}
@@ -0,0 +1,37 @@
{
"schemaVersion": 1,
"source": {
"repository": "clean-architecture-backend-template",
"commit": "45d2a478b800586f1d84151723629a560265d58e",
"document": "docs/web/http-contract.md"
},
"sections": {
"2": [
[
"| 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 |",
"| --- | --- | --- | --- | --- | --- |",
"| 재생(replay): 같은 키·같은 본문, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | — | 없음 | 첫 요청의 결과로 받아들인다. `meta`의 id는 이번 요청의 것이다 |",
"| 처리 중(in-flight): 같은 키, 첫 요청이 아직 실행 중(Redis 저장소. PostgreSQL 저장소는 409 대신 첫 요청이 끝날 때까지 기다린다 — 아래 \"첫 시도가 lease보다 오래 걸릴 때\") | 409 | `IDEMPOTENT_IN_FLIGHT` | `true` | `2` | 결과 불명. **같은 `Idempotency-Key`로** `Retry-After` 뒤 재전송한다. **새 키 금지** |",
"| 본문 불일치(mismatch): 같은 키·다른 본문 | 422 | `IDEMPOTENT_REQUEST_MISMATCH` | `false` | 없음 | 클라이언트 버그. 다시 보내지 않는다. 새 작업이면 새 키를 만든다 |",
"| 키 누락·형식 오류 | 400 | `IDEMPOTENCY_KEY_INVALID` (`details.reason` = `MISSING`/`MALFORMED`) | `false` | 없음 | 문법에 맞는 키를 붙여 다시 보낸다 |"
],
[
"| 경우 | status | `error.code` | `retryable` | `Retry-After` | 클라이언트 행동 |",
"| --- | --- | --- | --- | --- | --- |",
"| 작업 실행 전(claim·시작 단계) 멱등성 저장소 응답 없음. 또는 claim의 processing lease가 작업 시작 전에 끝나 저장소가 시작을 거절함 | 503 | `IDEMPOTENCY_UNAVAILABLE` | `true` | 없음 | 작업은 실행되지 않았다. 같은 키로 나중에 다시 보낸다(다음 요청이 그 claim을 넘겨받아 실행한다) |",
"| 작업 실행 뒤 결과 기록(complete 단계) 중 저장소 응답 없음 — **결과 불명** | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | `true` | 없음 | \"적용되지 않았다\"고 알리지 않는다. **같은 키로** 나중에 다시 보낸다. 새 키 금지 |",
"| 이전 시도의 효과를 증명할 수 없음 | 500 | `IDEMPOTENCY_RECOVERY_REQUIRED` | `false` | 없음 | 자동 재시도하지 않는다. 같은 키 재전송은 안전하다 — 서버는 효과가 있었을 수 있는 작업을 다시 돌리지 않고, 첫 시도가 늦게 끝났으면 그 결과를 재생하며, 효과 없이 끝났으면 실행하고, 아니면 다시 500이다. 결과는 업무 데이터로 확인하고, 효과가 없다고 확인된 뒤에만 운영 절차(`docs/runbooks/idempotency-unavailable.md`)에 따라 새 키로 다시 보낸다 |"
]
],
"4": [
[
"| 코드 | status | category | `retryable` | `Retry-After` | 언제 |",
"| --- | --- | --- | --- | --- | --- |",
"| `REQUEST_TIMEOUT` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 없음 | 비동기 요청(`Callable`·`DeferredResult`·스트리밍)이 시간 안에 끝나지 않았다. GraphQL도 같은 이름을 쓰지만 그쪽 `category`는 GraphQL 전용 어휘 `TIMEOUT`이다(`src/adapter/inbound/graphql/README.md`) |",
"| `IDEMPOTENCY_KEY_INVALID` | 400 | `VALIDATION` | `false` | 없음 | 2절 |",
"| `RATE_LIMIT_UNAVAILABLE` | 503 | `TRANSIENT_DEPENDENCY` | `true` | 있음 | rate-limit 저장소 응답 없음(`docs/web/runbook.md`) |",
"| `RATE_LIMIT_INCOMPATIBLE` | 503 | `INTERNAL` | `false` | 없음 | rate-limit 제공자가 계약과 맞지 않음 |"
]
]
}
}
@@ -54,6 +54,20 @@
"status": 503,
"refusedBeforeWrite": false,
"sameKeyResend": false
},
{
"section": "4",
"code": "RATE_LIMIT_UNAVAILABLE",
"status": 503,
"refusedBeforeWrite": true,
"sameKeyResend": false
},
{
"section": "4",
"code": "RATE_LIMIT_INCOMPATIBLE",
"status": 503,
"refusedBeforeWrite": true,
"sameKeyResend": false
}
]
}
+1 -1
View File
@@ -373,7 +373,7 @@
},
"consumerIdentityField": "logicalName",
"consumerDirectories": ["src", "tests"],
"orphanExemptRows": ["QUERY_PERSISTENCE", "AUTH_TOKEN"],
"orphanExemptRows": ["QUERY_PERSISTENCE", "AUTH_TOKEN", "AUTH_REDIRECT_TRANSACTION"],
"breakingFields": [
"logicalName",
"physicalKey",
+3 -2
View File
@@ -1,14 +1,15 @@
{
"schemaVersion": 1,
"bundle": {
"initialJsGzipBytes": 204800,
"initialJsGzipBytes": 206848,
"initialJsFiles": 32,
"lazyChunkGzipBytes": 122880
},
"lab": {
"lcpMs": 2500,
"cls": 0.1,
"namedInteractionMs": 200
"namedInteractionMs": 200,
"featureRouteInteractionMs": 500
},
"field": {
"p75LcpMs": 2500,
+3 -3
View File
@@ -39,9 +39,9 @@
}
],
"initialJavascript": {
"gzipBytes": 202927,
"files": 26,
"gzipBytes": 204111,
"files": 27,
"perFeatureGzipBytes": 768,
"perContextGzipBytes": 233
"perContextGzipBytes": 218
}
}
+1 -1
View File
@@ -20,7 +20,7 @@
},
"metrics": {
"type": "object",
"required": ["lcpMs", "cls", "namedInteractionMs"]
"required": ["lcpMs", "cls", "namedInteractionMs", "targetDeepLinkCls", "featureRouteInteractionMs"]
},
"thresholds": { "type": "object" },
"fixtures": { "type": "array", "minItems": 2 },
+9 -3
View File
@@ -43,11 +43,17 @@ README와 입구 문서는 영어, recipe·ledger·스타일 문서는 한국어
`verify:documentation`은 이 파일과 이 절에서 링크한 문서(폴더 링크는 그 안의 `.md` 전부)에
적힌 repo 경로·링크·package script·FE-GATE ID가 실제로 있는지 검사한다. 명령(인라인 코드와
셸 코드 블록) 안의 경로 인자도 본다. 짝 백엔드 템플릿(`clean-architecture-backend-template`)의
경로와 링크는 그 checkout이 이 checkout 옆에 있을 때만 확인하고, 없으면 실패 대신 확인하지
못한 것으로 출력과 `artifacts/quality/documentation-review.json`에 남긴다. `CHANGELOG.md`는
경로와 링크는 `config/contracts/backend-contract-pin.json`이 고정한 커밋의 트리에서 찾는다.
이 checkout 옆에 있는 짝 checkout의 git 기록을 읽고, 그 작업 트리와 HEAD는 보지 않는다. 짝
checkout이 없거나 그 커밋이 없으면 실패 대신 확인하지 못한 것으로 출력과
`artifacts/quality/documentation-review.json`에 남긴다. repo 밖으로 나가는 링크가 짝 저장소를
가리키지 않으면(저장소 이름 오타 포함) 실패한다. `CHANGELOG.md`는
지난 상태를 적는 문서라 빼고, git이 무시하는 생성 산출물과 복사한 프로젝트가 지운 작업 이력은
없어도 된다. 설명·수치가 코드와 맞는지는 검사하지 않는다. 규칙과 예외의 정본은
`scripts/verify-documentation-readiness.ts`다.
복사한 프로젝트가 지울 수 있는 템플릿 기능(참조 기능, 예제 화면. 목록은
`scripts/lib/removable-template-features.ts`)의 경로와 script는 그 기능이 설치돼 있을 때
(`src/features/<id>/feature-module.ts`가 있을 때) 검사하고, 지운 뒤에는 없어도 된다.
게이트가 직접 읽는 파일이라 지우거나 옮기면 게이트가 실패한다.
@@ -82,4 +88,4 @@ README와 입구 문서는 영어, recipe·ledger·스타일 문서는 한국어
|---|---|
| [`superpowers/`](superpowers/) | 과거 작업 계획과 스펙 |
| [`reviews/`](reviews/) | 리뷰 결과와 리뷰 가이드. `reviews/adapters/INVENTORY.md`만 게이트가 읽는다. `reviews/adapters/`는 지우지 않는다: INVENTORY의 행과 `operations/adapter-remediation-ledger.md`가 그 안의 리뷰로 링크한다 |
| [`../SPEC.md`](../SPEC.md), [`../tasks/`](../tasks/) | 2026-09-25 리뷰 수정 라운드의 요구사항과 작업 목록. 이 라운드가 쓰는 중이라 `docs/` 밖에 그대로 둔다 |
| [`../SPEC.md`](../SPEC.md), [`../tasks/`](../tasks/) | 2026-09-25 리뷰 수정 라운드의 요구사항과 작업 목록. 그 라운드는 0.2.0(`CHANGELOG.md`)으로 끝났다. 그때 리뷰 문서(`reviews/2026-09-25-maturity-review/`)가 이 경로(`SPEC.md:18` 등)로 가리키므로 옮기지 않는다 |
+1 -1
View File
@@ -77,5 +77,5 @@ What the automated run scans:
annotation.
- The reference sample's list in its success, empty and error states, its
detail, its form with submit errors and its status page, each after that
state is on screen (tests/e2e/reference-form.spec.ts, removed with the
state is on screen (`tests/e2e/reference-form.spec.ts`, removed with the
sample).
@@ -167,18 +167,35 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정
1절 "Envelope 키 존재 규칙"
- 기준 커밋: 백엔드 `45d2a478`. 기계가 읽는 정본은
`config/contracts/backend-contract-pin.json`(repo, 전체 SHA, 대조한 절 §1·§2·§4,
담당)이다. 백엔드 §2 표와 §4 `REQUEST_TIMEOUT`은
담당)이다. 백엔드 §2 표와 §4의 503 셋(`REQUEST_TIMEOUT`, `RATE_LIMIT_UNAVAILABLE`,
`RATE_LIMIT_INCOMPATIBLE`)은
`config/contracts/backend-idempotency-answers.json`에 code·status·쓰기 전 거절·같은 키
재전송 열로 옮겨 두었다. `tests/unit/backend-contract-pin.test.ts`가 그 표와
`backend-envelope.ts`의 판정을 양방향으로 대조한다. 값이 null인 필드는 키째
생략한다. 백엔드 기준 커밋을 올리면 pin, 답 표 JSON, 6.1절 표를 같은 변경에서
다시 확인한다. 형제 디렉터리에 백엔드 checkout이 있으면
`corepack pnpm check:backend-contract-drift`가 pin 뒤 `http-contract.md`가
바뀌었는지 알려 준다(게이트 밖).
다시 확인한다.
- 백엔드 §2·§4 표의 행은 pin 커밋 그대로
`config/contracts/backend-http-contract-excerpt.json`에 옮겨 두었다. 같은 테스트가
답 표의 code·status를 이 사본과 대조한다. 사본에만 있는 행은 답 표에 옮기거나 pin의
`notCopied`에 이유와 함께 적는다(지금은 없다). pin의
`sectionsCompared`의 §4에서 답 표가 옮긴 행은 503 셋(`REQUEST_TIMEOUT`,
`RATE_LIMIT_UNAVAILABLE`, `RATE_LIMIT_INCOMPATIBLE`)이다.
`IDEMPOTENCY_KEY_INVALID`는 §2 행으로 옮겼다.
- 사본이 백엔드 문서와 같은지는 `corepack pnpm check:backend-contract-drift --backend <백엔드 checkout>`이
본다(게이트 밖. CI는 이 repo만 checkout한다). pin 커밋의 표와 사본·답 표를
비교하고, pin 뒤 백엔드 HEAD에서 바뀐 표 행을 알린다. 1은 어긋남, 2는 비교하지
못함(통과가 아니다)이다. 짝 백엔드를 새로 받을 때마다 돌린다. pin을 올릴 때는
`--write-excerpt`가 사본을 pin 커밋에서 다시 옮긴다.
- `create:feature --with-create`는 백엔드 생성기 템플릿의 사실 넷(경로 복수형,
이름 상한 100, 오류 code, 검사 순서)을 생성기 문자열로 옮겼다. 그 파일들은
pin의 `backend.scaffoldSources`에 있고, 각 항목이 옮긴 곳(프론트 파일과
이름)을 적는다. drift 검사는 pin 뒤 HEAD에서 이 파일들이 바뀌었는지도 보고,
바뀐 파일마다 다시 볼 프론트 위치를 말하며 1로 끝난다(1105/16-02).
- 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와
해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다.
`create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 선언하지 않고
DTO와 problem details를 검증한다.
`create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 `"NONE"`을
선언하고 DTO와 problem details를 검증한다. 이 칸은 descriptor 타입의 필수
칸이라 빠뜨리면 `check:types`가 실패한다(1103/16-01).
- 실패 Envelope의 `error.code`가 "적용 안 됨"인지는 6.1절이 정한다.
- 페이지 목록의 `meta.page`(`number`·`size`·`total`·`sort`)는 기능의
`mapSuccess(value, { page })` 두 번째 인자로 간다(`FeatureHttpSuccessContext`).
@@ -266,8 +283,8 @@ backend idempotency를 대체하지 않는다.
`src/presentation/adapters/query/application-query.ts`
- Envelope operation의 거절 판정: `src/adapters/http/backend-envelope.ts`
`REFUSED_BEFORE_WRITE`(6.1절 표)
- 참조 기능(Envelope 없음) 판정: src/features/reference-feature/contracts/reference-feature-contract-contribution.ts
(effect), src/features/reference-feature/adapters/reference-http-gateway.ts
- 참조 기능(Envelope 없음) 판정: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`
(effect), `src/features/reference-feature/adapters/reference-http-gateway.ts`
(code)
### 6.1 거절 code와 적용 여부
@@ -317,6 +334,16 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
`IDEMPOTENCY_RECOVERY_REQUIRED`, §4의 503 `REQUEST_TIMEOUT`이다. 실행기가
자동으로 다시 보내는 것은 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE`뿐이다.
나머지는 결과 불명 화면에서 사용자가 같은 키로 다시 보낸다.
- §4의 503 `RATE_LIMIT_UNAVAILABLE`(rate-limit 저장소 응답 없음, `Retry-After` 있음)과
503 `RATE_LIMIT_INCOMPATIBLE`(rate-limit 제공자가 계약과 맞지 않음)은 status와 code가
함께 맞으면 기능 분류기와 상관없이 `NOT_APPLIED`다(1105/03-02, `backend-envelope.ts`
`REFUSED_BEFORE_WRITE`). 백엔드 `RateLimitInterceptor.java`의 `preHandle`이 컨트롤러 전에
`false`를 돌려주며 낸다. `45d2a478`의 main 소스에서 이 두 code를 내는 곳은 그 두
줄뿐이다. 자동 재전송은 없다(KEYED도 같다). 남은 위험(추론, 실행 확인 안 함): Spring MVC는
비동기 처리(`Callable`·`DeferredResult`)가 끝난 뒤의 ASYNC 재디스패치에서도 interceptor의
`preHandle`을 다시 부른다. 그 interceptor는 dispatcher 종류를 보지 않으므로 비동기 쓰기
컨트롤러라면 이 503(그리고 429)이 쓰기 뒤에도 나올 수 있다. `45d2a478`에는 Envelope을
돌려주는 비동기 쓰기 컨트롤러가 없다(web-advanced 스트리밍과 fileserver 전송뿐).
- 파일 위치(백엔드 repo `clean-architecture-backend-template` 기준):
- `GlobalExceptionHandler.java`, `HttpStatusErrorCodes.java`: `clean-architecture-backend-template/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/`
- `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/`
@@ -330,6 +357,22 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
`RepoStatsAclMapper.java`, `DomainExceptionHandler.java`: `clean-architecture-backend-template/src/sample-portfolio/`
- `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`:
`clean-architecture-backend-template/src/application-fileserver/`
- Fileserver 한 번 업로드(`POST /v1/files`)는 V3 실행기가 아니라
`src/adapters/http/fileserver-upload.ts`의 client가 부른다(1105/01-02). 이 client는
위 표의 fileserver 행과 달리 4xx를 `NOT_APPLIED`로 본다. 업로드 use case
(`UploadFileApplicationUseCase.java`)가 모호하지 않은 실패에서 업로드를 취소하므로
`READY` 파일이 남지 않는다. `MALWARE_DETECTED`처럼 레코드를 `REJECTED`로 쓴 뒤
던지는 code도 그 레코드는 공개되지 않는다. 위 행은 fileserver 응답을 V3 실행기로
읽을 때의 판정이다.
- 멱등성 code와 V3 표(`REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`)에 있는 답은
client도 V3 표로 판정한다. 그래서 503 `IDEMPOTENCY_UNAVAILABLE`은 `MAYBE_APPLIED`다.
`tests/integration/fileserver-upload.test.ts`가 복사한 답 표의 행마다 둘이 같은지 본다.
- 5xx는 작업 스레드가 게시 전에 내는 code 넷(`PARTIAL_WRITE`,
`ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `STORAGE_FULL`)만
`NOT_APPLIED`다. 504 `TRANSFER_TIMEOUT`은 `MAYBE_APPLIED`다. 대기 스레드가
작업 단계와 상관없이 내고, 게시 rename과 `READY` 커밋은 interrupt로 멈추지 않는다
(`BlockingTransferExecutor.java`, `FinalizeUploadApplicationUseCase.java`). 백엔드는
이 code를 `retryable: true`, `ambiguous` 없이 보낸다. 이 차이는 백엔드 결정으로 남는다.
**operation이 선언하는 쓰기 전 거절**(1103/03-01): 업무 code는 엔드포인트마다
단계가 달라 위 표에 "쓰기 뒤 가능"으로 둔다. 쓰기 전에만 그 code를 내는 엔드포인트를
@@ -343,6 +386,13 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
- 위 표의 code(`VALIDATION_FAILED` 등)는 적어도 표의 status 규칙을 따른다.
`IDEMPOTENT_*`·`IDEMPOTENCY_*`는 적을 수 없다. 계약 조립이 거절하고, 실행기도
무시한다. 409 `IDEMPOTENT_IN_FLIGHT`의 앞선 요청은 적용될 수 있기 때문이다.
- 위 표에서 "쓰기 뒤 가능"인 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_*` 8개,
`LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다(1105/03-01). 계약 조립이
거절하고 실행기도 무시한다. 목록은 `src/contracts/external-contract-runtime.ts`의
`PLATFORM_CODES_POSSIBLY_AFTER_WRITE`이고, `tests/unit/backend-contract-pin.test.ts`가
이 표의 "쓰기 뒤 가능" 행과 대조한다. 참조 도메인 code와 web-advanced patch code는
엔드포인트가 단계를 정하므로 그 엔드포인트를 확인한 기능 작성자가 적을 수 있다. 이 표에
"쓰기 뒤 가능" 플랫폼 code를 더하면 그 목록도 같은 변경에서 고친다.
- `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에는 적을 수 없다. 실행기가
백엔드 code를 읽지 않는다.
- 판정은 `src/adapters/http/backend-envelope.ts` `envelopeFailureEffect`, 조립 검사는
@@ -376,6 +376,10 @@ digest 또는 별도 검토된 streaming hash adapter를 사용한다.
`scopeParticipants`로 `dispose()`를 돌려주면 템플릿이 로그아웃·계정 전환마다
FENCED와 READY 사이에서 부르고, 실패하면 READY로 가지 않는다
(`ProductScopeParticipant`, `src/bootstrap/product-composition-contract.ts`).
실패한 close마다 진단 `cache.operation.failed`(`operation: SCOPE_RESET`,
`reason: PARTICIPANT_FAILED`, `scope_participant: <label>`)가 하나 남는다
(1105/02-01). 그래서 `label`은 소문자 kebab-case 토큰이어야 하고, 아니면
조립이 `TypeError`로 멈춘다.
`composeProduct`는 부팅 때 한 번만 불리므로 기능에는 runtime 대신 getter를
주고 그 뒤에서 세대마다 새 runtime을 만든다. 예제는
`recipes/frontend-capabilities/browser-file-session-capability.ts`이고
@@ -965,6 +969,20 @@ build-produced manifest
```
한 entry라도 실패하면 candidate는 incomplete이며 active로 전환하지 않는다.
이미 있는 candidate를 같은 manifest로 다시 stage하면 entry를 하나씩 다시
검증한다. 모두 맞으면 그대로 쓴다. entry가 없거나 바이트·헤더가 manifest와
다르면(`INTEGRITY_FAILED`·`CORRUPT_DATA`·`POLICY_REJECTED`·`LIMIT_EXCEEDED`)
모든 asset을 다시 받아 같은 cache에 덮어쓴다. entry는 있는데 저장된 본문을
읽지 못해도(`UNAVAILABLE`·`NOT_READABLE` 등) 같은 길로 다시 쓴다(1105/02-02).
본문 읽기 실패는 손상의 증거가 아니라서 activation은 그 code를 그대로
돌려주지만, recovery는 `REHYDRATE`(같은 manifest로 다시 stage)다. 다시 쓰기
전까지 계속 읽히지 않는 entry(blob 손실 등)는 이 길로만 돌아온다. rollback
대상 release와 서비스 중인 release도 같다. 덮어쓰는 바이트는 digest로 검증한
같은 바이트이고 cache를 지우지 않으므로, 서비스 중인 release를 해치지 않는다.
일시 오류에서는 다시 받는 비용이 든다. 중단(`ABORTED`)과 `cache.match` 자체의
실패는 다시 쓰지 않고 실패를 돌려준다. 조회(`matchActiveExact`)의 본문 읽기
실패는 그대로 `UNAVAILABLE`/`RETRY`다.
static Cache-only 조합은 waiting worker, `skipWaiting()`, `clients.claim()` 또는
controlled-client drain을 activation 전제나 성공 증거로 사용하지 않는다.
composition owner가 exact release ID와 manifest digest로
@@ -114,9 +114,10 @@ protocol-specific terminal proof와 protobuf decode/schema/mapper를 끝낸
runtime-wide notification branch에서만 공통
scope/gap/resync coordinator를 재사용한다. frame/media/trailer, reconnect와
operation deadline owner를 SSE/WebSocket adapter로 합치거나 protobuf message를
`REALTIME_EVENT_V1` JSON으로 다시 감싸지 않는다. Polling의 개별 attempt는 VD-23의
terminal·replay-safe REST `QUERY` execution contract를 재사용하되 transport/Query
retry는 끄고, 이 결정은 attempt 사이 bounded lease만 소유한다.
`REALTIME_EVENT_V1` JSON으로 다시 감싸지 않는다. Polling의 개별 attempt는 V3
contract executor가 실행하는 V3 REST descriptor 하나다(GET·HEAD, SAFE·IDEMPOTENT,
`frontend.retryBudget: 0`, 상세 설계 9.2). transport/Query retry는 끄고, 이 결정은
attempt 사이 bounded lease만 소유한다.
### 2. source of truth는 서버다
@@ -438,10 +439,11 @@ Service Worker를 선택해도 offline fetch, PWA shell cache나 background sync
각 lease는 operation owner, minimum/success/max interval, max attempts,
max elapsed, response byte cap, visible-only policy와 terminal states를 가진다.
- operation은 registered terminal·replay-safe REST `QUERY`여야 함
- Poll `maxAttempts`는 physical request 하나인 logical completion을 셈
- Poll-bound VD-23 budget은 `maxAttempts=1`, `authRecoveryCount=0`,
`maxCumulativeSleepMs=0`; TanStack Query retry도 끔
- operation은 설치된 V3 REST descriptor(`InstalledHttpContract`)로, method가
GET·HEAD이고 `retrySemantics`가 SAFE·IDEMPOTENT여야 함
- descriptor의 `frontend.retryBudget`은 0이어야 함. 아니면 poll coordinator 생성이
거절한다(상세 설계 9.2, 1103/04-01). V3 실행기는 재시도 상한을 이 칸에서 읽으므로
Poll `maxAttempts`의 한 attempt가 physical request 하나다. TanStack Query retry도 끔
- completion-chained timeout으로 single-flight
- hidden/offline/pagehide/unmount/scope change/user cancel에서 stop
- ETag/`If-None-Match` 또는 server cursor 사용
+1 -1
View File
@@ -63,7 +63,7 @@ Each row is one `forbidden` rule in `.dependency-cruiser.json`, by its `name`.
| `adapter-groups-are-reached-through-their-barrel` | code outside `src/adapters` | adapter files other than a group's `index.ts` and the `storage/indexeddb` and `storage/opfs` sub-barrels |
| `features-do-not-import-other-features` | each feature | another feature |
| `contexts-do-not-import-other-contexts` | each context | another context |
| `feature-and-app-roots-do-not-reach-adapters` | `src/features/*.ts`, `src/features/<id>/*.ts`, `src/contexts`, `src/apps`, except the type-only `src/features/feature-adapter-contribution.ts` | `src/adapters` |
| `feature-and-app-roots-do-not-reach-adapters` | every file in `src/features` outside a feature's `adapters/` folder (the root files and any folder that is not a layer, such as `support/`), `src/contexts`, `src/apps`, except the type-only `src/features/feature-adapter-contribution.ts` | `src/adapters` |
| `presentation-does-not-import-apps-or-contexts` | generic and feature presentation, except `src/presentation/routes/app-router.tsx`, which mounts the app's route tree | `src/apps`, `src/contexts` |
| `observability-vendors-live-behind-adapters` | code outside `src/adapters` | vendor telemetry SDKs |
| `platform-kernel-is-product-neutral` | `src/platform`, except `routing/`, which reads app descriptors by type | features, contexts, apps, adapters, bootstrap, presentation, application |
+18 -8
View File
@@ -124,8 +124,9 @@ type은 facade 밖으로 노출하지 않는다.
SSOT다. 문서와 catalog가 다르면 gate가 검사하는 catalog를 우선 고치고 이 표도
같이 갱신한다.
Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시작 실패
이벤트만 갖고 있다.
Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시작 실패
이벤트, 2의 `observe`와 3을 제품 소유 파일에서 잇는 자리를 갖고 있다. 4·5를
잇는 제품 소유 자리는 아직 없다.
1. 제품 소유 파일 `src/features/product-capabilities.ts`의 `SERVICE_WORKER`를
`ACTIVE`로 바꾼다. `scripts/build-frontend.ts`가 worker 빌드를 추가로 돈다.
@@ -139,11 +140,18 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시
`tests/component/runtime-composition-service-worker-telemetry.test.ts`가
확인한다. 템플릿이 연결하지 않은 것은 셋이다. 업데이트 설치 실패
(`watchForUpdates`, `src/adapters/service-worker/service-worker-page-controller.ts`)는
이벤트를 남기지 않는다. page controller의 `observe`는 composition이 넘기지
않는다. `OptionalRuntimeHost.health()`는 `src` 안에서 읽는 코드가 없다.
필요하면 다운스트림이 `createRuntimeComposition`에서 연결한다.
3. blockers: 저장하지 않은 편집이 있는 탭이 활성화를 거절하게
`createOptionalRuntimeHost`에 `blockers`를 넘긴다. 템플릿은 넘기지 않는다.
이벤트를 남기지 않는다. page controller의 `observe`는 제품이
`src/bootstrap/product-composition.ts`의 `composeProduct`에서
`serviceWorker.observe`로 돌려준다(1103/09-05). 템플릿 조립이 그것을 optional
host에 넘기고, 던지면 무시한다. `OptionalRuntimeHost.health()`는 `src` 안에서
읽는 코드가 없다.
3. blockers: 저장하지 않은 편집이 있는 탭이 활성화를 거절하게 `composeProduct`가
`serviceWorker.blockers`를 돌려준다. 하나가 true를 돌려주거나 던지면
`requestActivation()`이 `BLOCKED_DIRTY_CLIENT`로 거절한다. 템플릿 파일
`src/bootstrap/create-runtime-composition.ts`는 고치지 않는다. 실제 조립에서 두
값이 page controller에 닿는 것은
`tests/component/runtime-composition-service-worker-product-wiring.test.ts`가
확인한다.
4. 활성화 UI: `ServiceWorkerRuntimeHost.onUpdateWaiting`을 구독하고, 사용자가
동의하면 `requestActivation()`을 부른다(`src/contracts/service-worker.ts`).
5. reload 처리: `onReloadRequired`를 구독해 reload를 안내한다.
@@ -158,7 +166,9 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시
오프라인 셸(0929/06-03): reference 워커는 navigation을 가로채지 않는다
(`service-worker-static-assets.ts` navigation `NETWORK_ONLY`,
`service-worker-lifecycle.ts` `intercepts`). 사전 캐시는 해시 이름의
`assets/`뿐이고 `index.html`은 넣지 않는다(`scripts/generate-service-worker-assets.ts`).
`assets/`(`src/contracts/service-worker.ts` `BUILD_ASSET_DIRECTORY`)뿐이고 `index.html`은
넣지 않는다(`scripts/generate-service-worker-assets.ts`). `public/`에서 dist 루트로 복사된
PWA 아이콘 같은 파일은 이름이 해시처럼 보여도 넣지 않는다(1105/06-01).
설계가 cached `index.html` fallback을 금지한다(closed deep design 18.8). 오프라인
셸이 필요한 제품은 템플릿 워커를 켜는 것으로 얻지 못한다. 별도 제품 capability로
설계하고, 그때 넘겨받는 파일은 위 세 파일과 `vite.service-worker.config.ts`다.
@@ -362,12 +362,14 @@ Connect/gRPC-Web server stream과 향후 GraphQL subscription은 이 문서의 S
VD-29/VD-27 규칙을 우선한다.
- API operation registry의 현재 `SERVER_STREAM`은
`CONNECT_HTTP | GRPC_WEB + rpcKind=SERVER_STREAM`만 허용한다. SSE, WebSocket과 Web Push는
realtime registry가 소유하고, bounded polling은 terminal·replay-safe REST
`QUERY` operation에 적용하는 scheduling policy다.
- bounded polling의 한 logical attempt는 REST operation registry의 credential,
conditional request, schema/mapper와 deadline을 재사용한다. Poll 전용
operation은 transport retry를 끄며 이 문서는 완료된 attempt 사이 cadence와
failure backoff만 소유한다.
realtime registry가 소유하고, bounded polling은 V3 REST descriptor 중
GET·HEAD이고 SAFE·IDEMPOTENT인 읽기 operation에 적용하는 scheduling policy다.
- bounded polling의 한 logical attempt는 V3 contract executor가 실행하고, 그
실행기의 credential, schema/mapper와 deadline을 재사용한다. conditional
request(ETag)는 V3 실행기에 아직 없다(VD-23 conditional execution
`DESIGNED_NOT_IMPLEMENTED`). Poll 전용
operation은 `frontend.retryBudget: 0`으로 transport retry를 끈다(9.2). 이 문서는
완료된 attempt 사이 cadence와 failure backoff만 소유한다.
같은 stream을 Connect/gRPC-Web과 SSE로 자동 failover하지 않는다. wire와 resume 의미가
같다는 backend contract와 별도 rollout evidence가 있을 때만 명시된 fallback으로
@@ -1666,8 +1668,11 @@ poll coordinator는 실행할 V3 descriptor(`InstalledHttpContract`, 조립된
`min(retryBudget, maxRetryAttempts, 2)`번 다시 보낸다
(`http-execution-v3.ts` `retryCeiling`). 이 값을 descriptor에서 읽으므로, poll에
묶은 descriptor가 0이면 실행기의 `maxRetryAttempts`(`MAX_RETRY_ATTEMPTS`)와 상관없이
poll 한 attempt가 요청 한 번이다. 같은 descriptor를 `execute` 안에서 실행기에
넘긴다. 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때
poll 한 attempt가 요청 한 번이다. coordinator는 생성 때 검사한 그 descriptor를
`execute` 입력의 `operation`으로 넘긴다. `execute`는 그것을 실행기에 넘긴다.
같은 경로의 다른 행(예: 기본 GET, `retryBudget: 2`)을 넘기면 막는 것이 없고
attempt마다 요청이 최대 3번이다. `execute`는 서버·네트워크 실패도 결과로 돌려준다. 던지면 조합 코드
결함으로 보고 재시도 없이 `PROTOCOL_MISMATCH`로 lease를 끝낸다(1105/04-02). 기능의 기본 GET descriptor(`create:feature`는 `retryBudget: 2`)는 생성 때
거절된다. poll 전용 operation을 따로 등록한다. V3에는 401 재전송이 없다.
command/mutation, GraphQL subscription, Connect/gRPC-Web server stream과 arbitrary
status URL은 poll하지 않는다. TanStack Query retry도 `false`여야 한다.
@@ -1958,8 +1963,8 @@ credential을 보호할 수 있다고 주장하지 않는다.
| `AUTH_REQUIRED` | session expired/recovery 실패 | sign-in UX |
| `FORBIDDEN` | stream/resource 거절 | retry 없음 |
| `RATE_LIMITED` | connection/request/provider limit | bounded server hint |
| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`, poll `execute` 거절)도 세 transport 모두 이 kind다(1103/04-04, `retryable: true`). stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 |
| `PROTOCOL_MISMATCH` | version/subprotocol/content type | terminal/rollout rollback |
| `PROVIDER_UNAVAILABLE` | backend/push/hosting unavailable. 환경은 online인데 서버·프록시에 닿지 않은 것(SSE fetch·reader 거절, WebSocket `error`)도 이 kind다(1103/04-04, `retryable: true`). poll은 `execute`가 돌려준 결과의 kind를 쓴다. V3 실행기는 fetch 거절을 던지지 않고 `NETWORK_FAILURE` 결과로 돌려주므로, `execute`가 그 결과를 이 kind로 바꾼다. stream coordinator의 recovery deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: false`). live↔Poll handoff coordinator의 checkpoint deadline 초과(operation `RECOVER`)와 close drain deadline 초과(operation `CLOSE`)도 이 kind다(`retryable: true`) | bounded retry 또는 degraded. stream coordinator 마감은 재연결로 풀리지 않는다: task가 settle할 때까지 `DRAINING`을 유지한다. settle 뒤 recovery 마감은 다음 event가 recovery부터 하고, close 마감은 `CLOSED`가 된다. handoff checkpoint 마감은 그 전환을 fail-close하므로 새 handoff만 돌 수 있다. handoff close 마감 뒤에는 writer·checkpoint task가 settle하면 다시 부른 `close()`가 성공한다 |
| `PROTOCOL_MISMATCH` | version/subprotocol/content type. poll `execute`가 던지거나 모양이 틀린 결과를 돌려준 것도 이 kind다. 조합 코드 결함이라 서버 장애로 재시도하지 않는다(1105/04-02, `retryable: false`) | terminal/rollout rollback |
| `MALFORMED_EVENT` | state-bearing syntax/schema/exact-key 실패 | cursor 미진행, freshness `UNKNOWN`, close + registered recovery |
| `MAPPING_CONTRACT_VIOLATION` | validated DTO의 registered mapper 실패 | effect/cache/cursor write 0, close + registered recovery |
| `EVENT_CONFLICT` | 같은 ID/sequence가 다른 event를 가리킴 | terminal protocol conflict + resync/rollback |
+17 -10
View File
@@ -104,11 +104,18 @@ layouts"). Its starter links are the first three screens of the navigation.
The example screens `/examples/ui`, `/examples/states` and `/examples/auth`
are one feature, `src/features/platform-examples-feature/`, in its own context
`src/contexts/platform-examples-context/` (1103/09-04). A product turns them
off like any feature: leave the id out of `VITE_PRODUCT_FEATURES`, or remove
it with `corepack pnpm test:sample-removal -- --feature=platform-examples-feature`
as the drill. Their routes then leave the registry, the navigation, the
bundle and the manual accessibility list (FE-GATE-028). Their component tests
are in `tests/features/platform-examples-feature/` and go with them.
off like any feature: leave the id out of `VITE_PRODUCT_FEATURES`, or delete
the feature. To delete it, remove those two folders and
`tests/features/platform-examples-feature/` (its component tests), then run
`corepack pnpm generate:feature-index`;
`corepack pnpm test:sample-removal -- --feature=platform-examples-feature`
does the same in a copy of the repository and runs the gates there. Their
routes then leave the registry, the navigation, the bundle and the manual
accessibility list (FE-GATE-028). This document keeps naming the three
folders after they are gone: `verify:documentation` checks the paths of a
removable template feature (`scripts/lib/removable-template-features.ts`)
while the feature is installed and accepts them once its `feature-module.ts`
is gone (1105/14-01).
The platform overview (`/examples/platform`,
`src/presentation/examples/platform-overview-page.tsx`) stays a platform
@@ -161,8 +168,7 @@ selected app. Every build and check script runs it first; run it yourself with
invalidation, topic versions and the external `contractPackages` the
release manifest is checked against at boot), its message catalogs, and
`loadRuntime`, which imports `feature-runtime.ts` dynamically.
The reference sample's feature-module.ts (src/features/reference-feature,
while it is installed) is the complete example.
`src/features/reference-feature/feature-module.ts` is the complete example.
2. Create `src/features/<feature>/feature-runtime.ts` with
`defineFeatureRuntime`: the `schemas` (FE-REG-SCHEMA rows for the
feature's route and API schemas), the adapter contributions
@@ -172,8 +178,7 @@ selected app. Every build and check script runs it first; run it yourself with
it (`application.features.load`) when one of the feature's routes is
entered. Do not import it statically from anywhere: each feature would add
its whole executable code to the initial chunk again, about 3.9 KB gzip
(tests/unit/feature-shape-growth.test.ts, which goes with the reference
sample, bounds one feature at 1 KiB).
(`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB).
An HTTP API is written once, as its contract contribution descriptor: it
executes, and `check:registries` governs the FE-REG-API row projected from
it (`projectApiOperationRows` in `src/contracts/api-operations.ts`).
@@ -184,7 +189,7 @@ selected app. Every build and check script runs it first; run it yourself with
`FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here, and each
route handle carries the route's params/search `codecs`; the owning context
loads this file only when its route root is visited
(the reference sample's context-routes.ts shows one). Each handle's
(`src/features/reference-feature/context-routes.ts`). Each handle's
`routeId` must be a route of a feature contract in the same context; the
context refuses the routes when they load, naming the route, context and
features (`src/contexts/bounded-context-module.ts`).
@@ -215,6 +220,8 @@ Files outside the feature directory. Everything else a feature needs is in
| File | When | What fails without it |
| --- | --- | --- |
| `src/.generated/*` | never by hand: every build and check script regenerates it | — |
| `public/release-manifest.json` (tracked, the dev server's manifest) | every added or removed feature: `create:feature` rewrites it (`node scripts/write-dev-release-manifest.ts`). Commit it with the feature. Two feature branches change its `setDigest` line; on a merge conflict take either side and run the command again (1105/16-01) | `test:unit` (`tests/unit/dev-release-manifest.test.ts`) names the command; the dev server does not boot (`CONTRACT_SET_PACKAGE_MISSING`) |
| `config/scale/feature-shape-ceilings.json` `initialJavascript` (tracked, only while the sample is installed) | every added or removed feature, and every template change that moves the initial JavaScript: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. Commit it with the change; on a merge conflict run the command again | `test:unit` (the feature-shape growth test compares it with a build) |
| `src/contexts/<context>/context-module.ts` | the feature needs a new context | `generate:feature-index`: `Feature <id> belongs to undeclared context <context>` |
| `src/contexts/<context>/context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` |
| `artifacts/tests/a11y-manual/<ROUTE_ID>.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release |
+1 -1
View File
@@ -43,7 +43,7 @@ immutable release has a coherent HTML/assets/config/API/manifest tuple.
Serve the app over HTTP/2 or later. The entry preloads every initial
JavaScript file in parallel (`initialJsFiles` in
`config/performance/budgets.json` bounds how many; the current count is
`initialJavascript.files` in config/scale/feature-shape-ceilings.json, which goes with the sample feature). Over HTTP/1.1 they queue for six connections per
`initialJavascript.files` in `config/scale/feature-shape-ceilings.json`, which goes with the sample feature). Over HTTP/1.1 they queue for six connections per
host, and the first screen on Fast 3G came about one second later than with the
initial chunks grouped (2026-11-03). Over HTTP/2 the difference was under
100 ms, so the template keeps the chunks split. A product that can only serve
@@ -327,9 +327,9 @@ export function useCreateResourceMutation() {
return useApplicationMutation({
definitionId: "resource-create-v1",
definitionVersion: 1,
operationId: "CREATE_RESOURCE",
requiresIdempotencyKey: true,
owner: RESOURCE_FEATURE_ID,
// operationId·requiresIdempotencyKey는 descriptor에서 받는다(1103/16-05).
// 문자열로 적으면 MutationOperationId가 아니라 check:types가 실패한다.
...commandMutationIdentity(CREATE_RESOURCE_CONTRACT),
duplicatePolicy: "REJECT_WHILE_ACTIVE",
invalidate: [RESOURCE_INVALIDATION_TOPIC],
scope,
+6 -1
View File
@@ -25,11 +25,16 @@ reader that accepts it must ship before any writer sends it.
| `FEATURE_OVERRIDES` | record; unknown feature id ignored | additive | `featureOverrideArtifactSchema` in `src/contracts/release-artifacts.ts` |
| Release manifest V2 | strict object | breaking | `releaseManifestV2ArtifactSchema` in `src/contracts/release-artifacts.ts` |
| HTTP success/failure envelope (V3 with `responseEnvelope: "ENVELOPE_V1"`) | strict object (`meta` strips) | breaking | `successEnvelopeSchema`, `failureEnvelopeSchema` in `src/adapters/http/backend-envelope.ts` |
| HTTP V3 response DTO (reference feature) | `.strip()` drops unknown fields | additive | `referenceResourceDtoSchema` in the reference sample's contracts/reference-schemas.ts |
| HTTP V3 response DTO (reference feature) | `.strip()` drops unknown fields | additive | `referenceResourceDtoSchema` in `src/features/reference-feature/contracts/reference-schemas.ts` |
| Realtime envelope | exact key set; unknown `eventType` is `MALFORMED_EVENT` | breaking | `decodeUnsafe` in `src/adapters/realtime/event-codec.ts` |
| Browser RPC transport error code | closed vocabulary; unknown code is a protocol violation | breaking | `decodeTransportFailure` in `src/adapters/browser-rpc/browser-rpc-runtime.ts` |
| Persisted client storage | versioned key; incompatible value discarded | use a new key version | `defineStorageKey` in `src/contracts/storage-keys.ts` |
Turning a response DTO strict changes its row in this table. `check:registries`
grades it as breaking (`response-reader-narrowed`) when the FE-REG-SCHEMA row
of a `RESPONSE` schema goes from `STRIP_UNKNOWN` to `REJECT_UNKNOWN`, so the
change needs registry evidence (1105/07-02).
`CAPABILITY_OVERRIDES` and `FEATURE_OVERRIDES` differ on purpose. Feature ids
vary per build because each downstream project installs its own features, and
one shared config document may cover several builds. The capability set is
+37 -21
View File
@@ -5,7 +5,7 @@
- 뼈대는 손으로 만들지 않는다. `corepack pnpm create:feature <id>`로 만든다.
- 뼈대를 실제 기능으로 바꾸는 순서가 아래 0~11단계다.
참조 기능(src/features/reference-feature/)을 복사해 이름을 바꾸는 방법은 쓰지 않는다.
참조 기능(`src/features/reference-feature/`)을 복사해 이름을 바꾸는 방법은 쓰지 않는다.
그 방법은 접두어 없는 전역 ID, 참조 전용 계약 출처, 기능 밖 테스트 의존 때문에 여러 번 막힌다.
생성 명령은 이 문제를 미리 피한 파일을 쓴다.
@@ -103,9 +103,12 @@ corepack pnpm create:feature invoice-feature
→ 파일 쓰기 (있는 파일은 덮어쓰지 않음)
→ 생성기 실행
→ 생성기가 거부하면 만든 파일을 모두 지움
→ dev server manifest(public/release-manifest.json, 추적 파일) 다시 쓰기
→ 만든 파일과 다음 할 일 출력
```
- 기능과 함께 커밋할 추적 파일은 둘이다. dev server manifest와, 참조 기능이 있는 동안의 초기 JS 기록이다. 기능 브랜치 둘이 같은 줄에서 충돌하면 명령을 다시 돌린다. 표와 명령은 [03 문서 A](03-outside-feature-folder.md#a-생성-명령이-만든다)에 있다.
① **정할 것**
- `--context <context id>`: 0단계에서 기존 context를 골랐을 때만 준다.
@@ -148,7 +151,7 @@ corepack pnpm create:feature invoice-feature
- 있으면 `domain/<model>.ts`에 둔다.
- 생성 함수에서 불변식을 검사하고 `Object.freeze`로 고정한다.
- 이름은 와이어 필드가 아니라 업무 이름으로 짓는다(참조 기능은 `name`을 `displayName`으로 바꾼다).
- 예제(참조 기능): src/features/reference-feature/domain/
- 예제(참조 기능): `src/features/reference-feature/domain/`
- 길이 제한(예: 제목 100자)은 domain이 아니라 경계 검증에 둔다.
- 경계 검증: 값이 앱에 들어오거나 나가는 자리(요청·응답 스키마, 폼 스키마)에서 하는 검사다.
- 서버가 정한 제한이면 `contracts/<base>-schemas.ts`에 상수로 두고 요청 스키마와 폼 스키마가 같은 상수를 쓴다. 숫자가 두 곳에서 갈라지지 않는다.
@@ -208,9 +211,10 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope
- 성공: `{ "success": true, "data": ..., "meta": ... }`
- 실패: `{ "success": false, "error": { "code", ... }, "meta": ... }`
- 이 모양을 읽게 하는 것은 V3 descriptor(`<base>-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 생성된 operation에는 모두 들어 있다.
- operation을 손으로 더할 때마다 이 줄을 적는다. 이 값은 operation마다 따로다.
- 한 계약 기여 안에서 이 값이 다른 operation이 있으면 계약 조립이 거부한다(`<id>/<operationId>: responseEnvelope NONE, but <other> in the same contribution reads ENVELOPE_V1; ...`). 기여 하나는 백엔드 하나의 패키지라서다. 그래서 줄을 빠뜨리면 앱을 조립하는 테스트와 `check:registries`가 실패한다.
- **못 잡음**: 기여 안의 operation 모두에서 이 줄을 빼는 것. 그때는 아래 MSW 줄의 손글씨 gateway 테스트만 잡는다.
- operation을 손으로 더할 때마다 이 줄을 적는다. 이 값은 operation마다 따로다. 감싸지 않는 백엔드면 `"NONE"`을 적는다. 줄은 빼지 않는다.
- 줄을 빠뜨리면 `check:types`가 그 descriptor의 `satisfies InstalledHttpContract<...>`에서 실패한다(`Property 'responseEnvelope' is missing ...`, 1103/16-01). 기여 안의 operation 모두에서 빼도 같다.
- 한 계약 기여 안에서 이 값이 다른 operation이 있으면 계약 조립이 거부한다(`<id>/<operationId>: responseEnvelope NONE, but <other> in the same contribution reads ENVELOPE_V1; ...`). 기여 하나는 백엔드 하나의 패키지라서다. 그래서 값을 잘못 적으면 앱을 조립하는 테스트와 `check:registries`가 실패한다.
- **못 잡음**: 기여 안의 operation 모두에 같은 틀린 값을 적는 것(짝 백엔드인데 모두 `"NONE"`). 그때는 아래 MSW 줄의 손글씨 gateway 테스트만 잡는다.
```text
성공 status → Envelope 확인 → data를 outputValidator로 검증 → mapSuccess
@@ -219,7 +223,10 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope
- 백엔드는 값이 null인 필드를 키째 뺀다. `data` 키가 없으면 `null`로 읽는다. DTO 안에서 null일 수 있는 필드는 스키마에서 `.optional()`로 받는다.
- problem 스키마(`<base>-schemas.ts`의 `<base>ProblemSchema`)는 Envelope의 `error` 객체다. 분기는 `code`로 한다. `message`는 버린다.
- 400·409·422와 백엔드가 정한 5xx 넷이 적용됐는지는 실행기가 백엔드 기준 표로 정한다. 목록은 [02 결정표 4절](02-decision-tables.md#4-결과-불명)이다.
- 400·409·422와 백엔드가 정한 5xx 여섯이 적용됐는지는 실행기가 백엔드 기준 표로 정한다. 목록은 [02 결정표 4절](02-decision-tables.md#4-결과-불명)이다.
- 기준 표는 백엔드 커밋 하나에 묶여 있다(`config/contracts/backend-contract-pin.json`). 백엔드 표의 행은 `config/contracts/backend-http-contract-excerpt.json`에 그대로 옮겨 두었고, `test:unit`이 답 표(`config/contracts/backend-idempotency-answers.json`)를 그 사본과 대조한다.
- **짝 백엔드를 새로 받을 때마다** `corepack pnpm check:backend-contract-drift --backend <백엔드 checkout>`을 돌린다. 게이트 밖이라 CI는 돌리지 않는다. 1이면 pin 뒤 백엔드 표가 바뀌었거나 사본·답 표가 pin과 다르다. 출력이 그 행을 말한다. 2는 비교하지 못했다는 뜻이고 통과가 아니다(checkout이 없거나 pin 커밋이 없다).
- pin을 올릴 때: pin의 `backend.commit`과 답 표의 `source.commit`을 바꾸고 같은 명령에 `--write-excerpt`를 붙여 사본을 다시 옮긴다. 그다음 답 표와 [백엔드 계약 6.1절](../architecture/backend-api-and-server-state-contract.md) 표를 명령이 통과할 때까지 고친다. 옮기지 않는 행은 pin의 `notCopied`에 이유와 함께 적는다.
- 업무 규칙 거절(`<FEATURE>_INVALID`, `*_ALREADY_EXISTS` 등)은 표에 없어 결과 불명이 된다. 그 엔드포인트가 쓰기 전에만 내는 code면 `commandEffect.refusedBeforeWrite`에 적는다. 적어야 사용자가 값을 고쳐 다시 저장할 수 있다(02 결정표 4절).
- `mapProblem`이 없거나 `undefined`를 돌려주면 백엔드 code·필드 오류·status별 kind로 읽는다(`src/adapters/http/backend-envelope.ts`).
- 바이트 상한(`responseByteLimit`)과 구조 예산은 Envelope 전체에 걸린다.
@@ -230,11 +237,11 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope
DTO와 problem details(`type`·`title`·`status`)를 감싸지 않고 보내는 백엔드에 붙일 때:
1. descriptor에서 `responseEnvelope` 줄을 지운다.
1. 모든 descriptor의 `responseEnvelope`를 `"NONE" as const`로 바꾼다. 줄을 지우면 `check:types`가 실패한다.
2. problem 스키마를 problem details 모양으로 바꾼다.
3. `classifyProblem`이 모든 판정을 정한다. 실행기가 먼저 정하는 판정은 없다.
참조 기능(src/features/reference-feature/)이 이 모양이다. 참조 기능의 MSW 본문도 DTO와 problem details다.
참조 기능(`src/features/reference-feature/`)이 이 모양이다. 참조 기능의 MSW 본문도 DTO와 problem details다.
**입력과 스키마 메타데이터**
@@ -371,13 +378,13 @@ projectRequest: (input) => Object.freeze({
- 참조 기능은 생성 operation에 목록 route(`REFERENCE_RESOURCE_LIST`)를 적었다. 실제로 보내는 화면은 폼 route다. 동작은 같고 기록의 이름표만 다르다. 새 기능은 위 기준을 따른다.
- `needs`에는 실제로 쓰는 것만 적는다.
- 템플릿이 만들지 않는 capability(예: `indexedDb`)는 `src/bootstrap/product-composition.ts`에서 만든다. 제품이 새로 만드는 capability의 타입은 `src/features/product-capabilities.ts`에 적는다. [03 문서](03-outside-feature-folder.md)를 본다.
- 문제 응답 매핑 예제(참조 기능): src/features/reference-feature/adapters/reference-http-gateway.ts
- 문제 응답 매핑 예제(참조 기능): `src/features/reference-feature/adapters/reference-http-gateway.ts`
③ **잡는 검사 / 못 잡는 것**
- presentation이 기능 `adapters/`를 import하면 `feature-presentation-does-not-know-outbound-adapters`로 막는다.
- adapters가 presentation을 import하면 `feature-adapters-do-not-know-presentation`으로 막는다.
- 기능 루트 파일(`feature-module.ts` 등)이 `src/adapters`에 닿으면 `feature-and-app-roots-do-not-reach-adapters`로 막는다.
- 기능 루트 파일(`feature-module.ts` 등)이나 계층이 아닌 폴더(`support/` 등)의 파일이 `src/adapters`에 닿으면 `feature-and-app-roots-do-not-reach-adapters`로 막는다. 기능 안에서 `src/adapters`에 닿을 수 있는 곳은 `adapters/` 폴더뿐이다.
- operation ID·route ID·입력 타입을 틀리면 `check:types`가 막는다. 음성 fixture: `check:types:fixture:http-operation-id`, `check:types:fixture:http-route-id`, `check:types:fixture:http-operation-input`.
- 호스트가 주지 않는 capability를 `needs`에 적으면 조립이 실패한다.
- 메시지: `feature <id> needs <capability>, which the host did not provide`
@@ -415,8 +422,8 @@ projectRequest: (input) => Object.freeze({
② **기준**
- 경로는 계약에만 적는다. 페이지와 링크는 route ID와 `buildRouteUrl`로 URL을 만든다. 경로 문자열을 페이지에 다시 적지 않는다.
- 파라미터나 검색값이 있는 라우트는 `context-routes.ts`의 handle에 `codecs`를 싣는다. 예제(참조 기능): src/features/reference-feature/context-routes.ts.
- 링크용 URL 함수도 같은 codec을 `buildRouteUrl`의 세 번째 인자로 넘긴다. 기본 생성 판의 목록 라우트는 파라미터가 없어서 넘기지 않는다. `--with-create` 판의 상세 라우트는 codec을 넘긴다. 안 넘기면 `Unregistered route codec: <codecId>`로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제(참조 기능): src/features/reference-feature/presentation/reference-routes.ts.
- 파라미터나 검색값이 있는 라우트는 `context-routes.ts`의 handle에 `codecs`를 싣는다. 예제(참조 기능): `src/features/reference-feature/context-routes.ts`.
- 링크용 URL 함수도 같은 codec을 `buildRouteUrl`의 세 번째 인자로 넘긴다. 기본 생성 판의 목록 라우트는 파라미터가 없어서 넘기지 않는다. `--with-create` 판의 상세 라우트는 codec을 넘긴다. 안 넘기면 `Unregistered route codec: <codecId>`로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제(참조 기능): `src/features/reference-feature/presentation/reference-routes.ts`.
- 상세 경로는 목록 경로 뒤에 `/items/:<id 이름>`을 붙인다. 예: `/notice/items/:noticeId`. `/notice/:noticeId`로 두지 않는다.
- 라우터(React Router)는 같은 자리에서 정적 경로를 먼저 고른다. 작성 폼 `/notice/new`가 있으면 id가 `new`인 공지는 `/notice/:noticeId`로 열 수 없다.
- `items/`를 끼우면 정적 경로와 겹치지 않는다. 참조 기능도 이렇게 한다(`/examples/reference-resources/items/:resourceId`).
@@ -480,7 +487,7 @@ projectRequest: (input) => Object.freeze({
});
```
- 예제(참조 기능): src/features/reference-feature/presentation/use-reference-feature.ts의 생성 뮤테이션 정책.
- 예제(참조 기능): `src/features/reference-feature/presentation/use-reference-feature.ts`의 생성 뮤테이션 정책.
③ **잡는 검사 / 못 잡는 것**
@@ -489,7 +496,8 @@ projectRequest: (input) => Object.freeze({
- 등록되지 않은 profile은 실행 때 `Unregistered server-state profile: <id>`로 실패한다.
- topic·namespace·edge를 더하기만 하면 레지스트리 기준선은 바뀌지 않는다(additive). 9단계에서 할 일이 없다.
- 뮤테이션 정책의 operation ID를 `commandMutationIdentity`로 받으면 descriptor 상수 이름의 오타는 `check:types`가 막는다. 쓰기 descriptor 대신 GET descriptor를 넘기면 바인딩 때 `commandMutationIdentity: <operationId> is a GET; a mutation binds a write operation`으로 throw한다.
- **못 잡음**: 뮤테이션 정책에 operation ID를 문자열로 직접 적은 것. 타입이 `string`이라 오타가 통과하고, 저장할 때 실행기가 보내기 전에 거부한다(`MISSING_IDEMPOTENCY_KEY` 위반). `commandMutationIdentity`를 쓴다.
- 뮤테이션 정책에 operation ID를 문자열로 직접 적으면 `check:types`가 실패한다. `BoundMutation.operationId`는 `MutationOperationId`이고, 이 값은 `commandMutationIdentity`만 만든다. 오류는 그 문자열을 `MutationOperationId`에 넣을 수 없다고 말한다.
- **못 잡음**: `commandMutationIdentity`에 descriptor 상수 대신 손으로 만든 객체(`{ contract: { operationId: "…", … } }`)를 넘기는 것. 그 오타는 저장할 때 실행기가 보내기 전에 거부한다(`MISSING_IDEMPOTENCY_KEY` 위반).
- `bindQuery`의 `owner`·`operationId`, 뮤테이션 정책의 `owner`는 적지 않는다. 읽는 곳이 없어 `@deprecated` 선택 칸이 됐고, 다음 릴리스에서 지운다. 요청 기록의 operation ID는 descriptor의 것이다.
- **못 잡음**: `definitionId` 중복. 유일성 검사가 없다.
@@ -504,14 +512,14 @@ projectRequest: (input) => Object.freeze({
① **정할 것**
- 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿)
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다.
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. 폼 밖에서 `mutation.submit`을 부르는 화면도 `NEVER` 쓰기의 같은 입력을 다시 보낼 수 없다. 훅이 `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)로 거절한다. `AsyncSurface`에 손으로 만든 상태를 넘기면 재전송 버튼은 그려지지 않는다(코디네이터의 `state`를 넘긴다).
- 폼이면 서버 필드 오류를 받을 필드(`useAppForm`의 `allowedServerFields`). 짝 백엔드는 필드 검증 거절을 400 `VALIDATION_FAILED`와 `details[{field, code}]`로 보낸다(422가 아니다). 공유 MSW 시나리오에는 짝 백엔드가 보내지 않는 `validation-422`만 있고, Envelope operation에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`<base>-create-page.test.tsx`)처럼 400 본문을 손으로 적는다.
② **기준**
- 화면 문구는 모두 catalog에서 가져온다(`message(key)`).
- 링크는 6단계의 URL 함수로 만든다.
- 결과 불명 화면 예제: `create:feature <id> --with-create`의 `presentation/<base>-create-page.tsx`(짝 백엔드 Envelope), 참조 기능의 src/features/reference-feature/presentation/reference-resource-form-page.tsx(problem details)
- 결과 불명 화면 예제: `create:feature <id> --with-create`의 `presentation/<base>-create-page.tsx`(짝 백엔드 Envelope), 참조 기능의 `src/features/reference-feature/presentation/reference-resource-form-page.tsx`(problem details)
③ **잡는 검사 / 못 잡는 것**
@@ -539,6 +547,7 @@ projectRequest: (input) => Object.freeze({
- 행을 **빼거나** 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에서 본다.
- FE-REG-SCHEMA 예: 응답 DTO를 `.strict()`로 바꾸고 스키마 메타 행을 `REJECT_UNKNOWN`으로 고치면(`direction: "RESPONSE"`) `response-reader-narrowed` breaking이다. 백엔드가 응답에 필드를 하나 더하면 그 API가 `SCHEMA_MISMATCH`로 실패하기 때문이다. 반대(`REJECT_UNKNOWN`→`STRIP_UNKNOWN`)와 요청 행은 behavior-change다.
- breaking 변경이면 둘 중 하나를 한다.
- `REGISTRY_BASELINE_OWNER`, `REGISTRY_BASELINE_REASON`을 주고 `corepack pnpm update:registry-baseline`을 돌린다.
- 또는 `config/contracts/registry-change-evidence.json`에 항목을 더한다. 칸 설명은 `docs/operations/ci-quality-gates.md`에 있다.
@@ -607,7 +616,7 @@ projectRequest: (input) => Object.freeze({
expect(await posts[0]!.json()).toEqual({ title: "새 공지", body: "본문입니다." });
```
- 핸들러를 직접 써서 요청을 모으는 방법도 있다. 예제(참조 기능): tests/features/reference-feature/reference-production-vertical.test.tsx의 504 재전송 테스트.
- 핸들러를 직접 써서 요청을 모으는 방법도 있다. 예제(참조 기능): `tests/features/reference-feature/reference-production-vertical.test.tsx`의 504 재전송 테스트.
- 빠르게 돌리기: `node scripts/run-vitest.ts run tests/features/<id>`
- CI에서는 `test:coverage`(FE-GATE-005)가 `tests/features`를 돈다. `test:unit`은 `tests/unit`만 돈다.
@@ -634,7 +643,8 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature
기능 폴더를 가리키는 커버리지 정책 행, owner가 기능 ID인 증거 정책 행을 지움
→ 레지스트리 기준선을 다시 찍음 (빼는 변경은 breaking이라서)
→ 타입·아키텍처·레지스트리·테스트·커버리지·CI 계약·빌드 게이트
→ src와 tests에 기능 ID나 폴더 이름이 남았는지 찾음
→ 지운 기능을 가리키는 파일이 남았는지 찾음
(src: 기능 ID·폴더 이름을 담은 파일, tests: 이름에 기능 ID가 있거나 기능 폴더에서 import하는 파일)
```
① **정할 것**: 없음. 확인 단계다.
@@ -646,9 +656,10 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature
③ **잡는 검사 / 못 잡는 것**
- 남은 파일이 기능 ID나 폴더 이름을 담고 있으면 실패한다.
- 남은 파일이 지운 기능을 가리키면 실패한다. `src`는 기능 ID나 폴더 이름을 담은 파일, `tests`는 이름에 기능 ID가 있거나 기능 폴더에서 import하는 파일이다.
- 메시지: `<id> removal failed:` 다음 줄 `fixture-id-residue: residue: <files>`
- **못 잡음**: 기능 ID를 담지 않은 폴더 밖 파일. 예: route ID만 적은 e2e spec, `artifacts/tests/a11y-manual/<ROUTE_ID>.md`. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다.
- 템플릿 테스트가 예시 ID(`invoice-feature` 등)를 데이터로 쓰는 것은 잔여로 세지 않는다(1105/16-04). 그래서 매뉴얼 예시 이름으로 만든 기능도 이 단계를 통과한다.
- **못 잡음**: 기능을 가리키지 않는 폴더 밖 파일. 예: route ID만 적은 e2e spec, `artifacts/tests/a11y-manual/<ROUTE_ID>.md`. `tests` 안에서 기능 ID를 글자로만 적은 테스트도 잔여로 세지 않는다. 그 테스트가 지운 기능에 기대면 같은 드릴의 `test:all`이 실패한다. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다.
④ **쓸 스킬**: `documentation-and-adrs`, `deprecation-and-migration`
@@ -665,6 +676,11 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature
- 지연 페이지가 셸과 같은 구성요소(`Button`, `SearchField` 등)를 쓰면 그 구성요소가 공유 청크로 떨어져 초기 파일 수도 하나 늘 수 있다. 파일 수 상한(`initialJsFiles`)은 여유가 있다.
- 예산은 `config/performance/budgets.json`에 있다. 넘었을 때 고르는 법은 `docs/operations/performance-evidence.md`에 있다. 넘으면 예산을 올리기 전에 팀이 정한다.
- 생성 명령의 드릴(`test:feature-scaffold`)도 merge 단계 명령으로 이 검사를 돈다.
- 참조 기능이 설치돼 있으면 초기 JS 기록(config/scale/feature-shape-ceilings.json)도 기능과 함께 바뀐다. test:unit이 빌드와 대조한다. 생성 명령 출력 `Next:` 3번의 명령으로 다시 쓰고 같은 커밋에 넣는다. 기능 제거 드릴(`test:sample-removal -- --feature=<id>`)은 지운 뒤 기록을 다시 쓰고 검사한다.
- 참조 기능이 설치돼 있으면 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 기능과 함께 바뀐다. `test:unit`이 빌드와 대조한다. 생성 명령 출력 `Next:` 3번의 명령으로 다시 쓰고 같은 커밋에 넣는다. 기능 제거 드릴(`test:sample-removal -- --feature=<id>`)은 지운 뒤 기록을 다시 쓰고 검사한다.
- 로컬에서 FE-GATE-013을 돌리려면 `VITE_COMMIT_SHA=$(git rev-parse HEAD)`를 준다. 없으면 release candidate가 `source.revision`을 거절한다. 실패한 게이트의 로그는 `artifacts/quality/gates/FE-GATE-<NNN>.txt`에 있다.
- workflow와 같은 조건으로 돌리려면 README 로컬 merge 게이트 반복문 아래의 env 블록대로 `CI=true`와 CI 빌드 식별값(`VITE_COMMIT_SHA`, `VITE_BUILD_ID`, `RELEASE_ID`, `CI_RUNNER_IMAGE` digest)을 주고 깨끗한 clone에서 돌린다. 이 값 없이 통과해도 CI에서 떨어질 수 있다(1103/11-07, 11-08).
- 게이트는 한 checkout에서 하나씩 돌린다. 게이트와 증거 검사는 `dist`와 `artifacts/`의 고정 경로를 읽는다.
- 브라우저 테스트(`playwright test`)를 한 checkout에서 둘 이상 동시에 돌릴 때는 실행마다 다른 `TEST_RUN_ID`를 준다. 예: `TEST_RUN_ID=a corepack pnpm exec playwright test`. 그 실행의 빌드·결과·report는 `.tmp/runs/<id>/` 아래에 생긴다.
- 서버 포트는 run ID가 없어도 빈 포트를 고른다. 같은 기계의 두 worktree도 부딪히지 않는다. 고정하려면 `TEST_E2E_PORT` 같은 포트 변수를 준다.
- `ci:gate`에는 `TEST_RUN_ID`를 주지 않는다. 주면 증거가 기본 경로에 생기지 않아 게이트가 `command-generated evidence was not freshly produced`로 실패한다.
- 변수 표와 한계는 [테스트 전략 13.6절](../testing/frontend-platform-testing-strategy.md)에 있다(1105/12-04).
+28 -13
View File
@@ -122,7 +122,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
| `commandEffect.refusedBeforeWrite` | `["<FEATURE>_INVALID"]` | 같다 | 이름 규칙을 트랜잭션 전에 검사한다(4절) |
| `acceptedStatuses` | `[201]` | `[201]` | `ResponseEntity.created`. 같은 키 재생도 첫 요청과 같은 201이다 |
| 결과 불명 화면 | 확인만. 다시 보내기 버튼 없음 | "같은 요청으로 다시 보내기"가 같은 키로 보낸다 | 키 없는 재전송은 서버가 새 요청으로 본다 |
| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송 | `tests/features/<id>/<base>-create-page.test.tsx`, `<base>-http-gateway.test.ts` |
| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음. "변경됨으로 확인" → 목록 화면 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송. "변경됨으로 확인" → 목록 화면 | `tests/features/<id>/<base>-create-page.test.tsx`, `<base>-http-gateway.test.ts` |
- 테스트 하네스의 재시도 상한: 생성된 gateway 테스트는 앱 기본값(`maxRetryAttempts: 2`)으로 돈다. 그래야 `retryBudget: 1`의 재전송이 보인다. 페이지 테스트(`<base>-test-app.tsx`)는 실패를 바로 보이려고 `MAX_RETRY_ATTEMPTS: 0`이다.
@@ -172,8 +172,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
- 같은 status라도 code로 나뉠 수 있다. 예: 409 중 "처리 중"은 `MAYBE_APPLIED`여야 한다. `NOT_APPLIED`로 보면 다음 저장이 새 키를 만들어 같은 작업이 두 번 적용된다.
- 401·403·429는 문제 응답 본문을 읽기 전에 status로 나뉜다. 서버가 상태를 안 바꾼다고 보장하면 `classifyStatus`로 `NOT_APPLIED`를 돌려준다. 없으면 `MAYBE_APPLIED`다.
- 문제 응답 본문이 기능의 problem 스키마를 통과하지 못하면 `classifyProblem`을 부르지 않는다. 쓰기는 `MAYBE_APPLIED`가 된다(`src/adapters/http/http-execution-v3.ts`).
- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 백엔드가 직접 정한 5xx 네 가지의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다.
- `NOT_APPLIED`(쓰기 전 거절): 400 `VALIDATION_FAILED`(details 모양과 상관없음), 400 `IDEMPOTENCY_KEY_INVALID`, 422 `IDEMPOTENT_REQUEST_MISMATCH`
- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 백엔드가 직접 정한 5xx 여섯 가지의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다.
- `NOT_APPLIED`(쓰기 전 거절): 400 `VALIDATION_FAILED`(details 모양과 상관없음), 400 `IDEMPOTENCY_KEY_INVALID`, 422 `IDEMPOTENT_REQUEST_MISMATCH`, 503 `RATE_LIMIT_UNAVAILABLE`·`RATE_LIMIT_INCOMPATIBLE`(rate-limit 저장소 장애·제공자 불일치. 컨트롤러 전에 거절한다)
- `MAYBE_APPLIED`: 그 밖의 400·409·422. 409 `IDEMPOTENT_IN_FLIGHT`, `BAD_PARAMETER`, 도메인 code, fileserver의 422가 여기 든다. 그리고 status와 code가 함께 맞는 5xx 넷: 503 `IDEMPOTENCY_UNAVAILABLE`, 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`(실행 뒤 결과 기록 실패, 새 키 금지), 500 `IDEMPOTENCY_RECOVERY_REQUIRED`(이전 시도 효과를 증명 못 함), 503 `REQUEST_TIMEOUT`(비동기 요청 시간 초과, 처리가 계속될 수 있음)
- 이 넷은 실행기가 자동으로 다시 보내지 않는다. 결과 불명 화면에서 같은 키로 다시 보낸다. 예외는 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE` 하나다(아래)
- 짝 백엔드가 모든 엔드포인트에서 쓰기 전에 거절하는 code를 새로 만들면 계약 문서 6.1절과 이 표를 함께 고친다. 표에 없으면 `MAYBE_APPLIED`다
@@ -182,7 +182,9 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
- 짝 백엔드 `new-feature.sh`가 만든 create는 이름을 트랜잭션 전에 검사하고 400 `<FEATURE>_INVALID`를 준다(백엔드 `Create__Feature__UseCase.java.tmpl`). 이 code는 적는다. 예: 기능 `worklog`이면 `refusedBeforeWrite: ["WORKLOG_INVALID"]`.
- 고르는 기준: 백엔드 코드에서 그 code를 던지는 곳이 모두 쓰기(트랜잭션, 외부 호출) 전인지 확인했을 때만 적는다. 확인하지 못했으면 적지 않는다. 쓰기 뒤에도 나오는 code를 적으면 결과 불명 요청을 새 키로 다시 보내 중복이 생길 수 있다.
- 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`).
- 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_UNIQUE_VIOLATION` 등 `DB_*`, `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다. 폼을 막는 400 `BAD_PARAMETER`나 409 `DB_UNIQUE_VIOLATION`은 어느 층에서든, 트랜잭션 안에서도 나온다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...; contract 6.1 reads this platform code as possibly raised after the write`로 거부한다.
- 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다.
- 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다.
**503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.**
@@ -207,7 +209,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
**정본**: 어떤 status·code가 "적용 안 됨"인지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2다.
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 예제(참조 기능): src/features/reference-feature/contracts/reference-feature-contract-contribution.ts의 `CREATE_EFFECT`.
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 예제(참조 기능): `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`의 `CREATE_EFFECT`.
**틀리면**
@@ -233,6 +235,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
- 제품 프로필 ID는 템플릿 프로필 ID와 겹치면 안 된다.
- 쿠키 인증과 CSRF 헤더는 인증 프로필의 헤더 집합으로 표현한다. 예제: `tests/unit/product-composition-fixture.test.ts`.
- 서버가 401을 주면 그 요청의 자격 증명을 낸 쪽만 안다. `ANONYMOUS` 요청의 401은 세션을 바꾸지 않는다. 템플릿 세션이 낸 자격 증명이면 세션이 로그아웃된다. 제품 `credentialProviders`가 낸 자격 증명이면 세션은 그대로이고 `composeProduct`가 돌려준 `onCredentialRejected`가 불린다(선택).
- provider가 템플릿 세션 자신의 자격 증명(BFF 쿠키 세션)을 보낸다면 `onCredentialRejected`에서 `context.notifySessionUnauthenticated()`를 부른다. 그래야 그 401이 세션을 로그아웃시킨다. 쿠키 recipe는 이 handler를 `createSessionCookieRejectionHandler`로 준다([04 문서](04-paired-backend-session.md) 4.3).
- 짝 백엔드에 붙일 때 세션 owner와 프로필은 [04 문서](04-paired-backend-session.md)가 모드별로 정한다. JWT 모드는 `EXTERNAL_BEARER`, Redis session 모드는 `SESSION_COOKIE_READ`·`SESSION_COOKIE_WRITE`다.
**기준**: 백엔드가 그 API에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다.
@@ -286,7 +289,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
→ FileContentPort.openSource(ref) → FileByteSource
→ 기능 어댑터: upload({ source, filename, mediaType, idempotencyKey, signal })
→ POST /v1/files (multipart, 파트 이름 file)
→ 201 READY 또는 202 VERIFYING + 저장된 파일 정보(fileId, sha256 …)
→ 201 READY 또는 202 VERIFYING·QUARANTINED + 저장된 파일 정보(fileId, sha256 …)
202 REJECTED는 저장된 파일이 아니다 → 실패 FILE_REJECTED
```
- `FileByteSource`: 고른 파일의 바이트를 조각으로 읽는 값이다. `File`·`Blob`은 파일 어댑터 밖으로 나오지 않는다.
@@ -308,16 +312,23 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
**결과 읽기**: `upload()`는 `Result<FileserverUploadedFile, AppFailure>`를 돌려준다.
- 성공 `state`가 `READY`(201)면 바로 내려받을 수 있다. 그 밖(202 `VERIFYING` 등)은 서버가 아직 검사 중이다.
- 성공 `state`가 `READY`(201)면 바로 내려받을 수 있다. 202는 아직 내려받을 수 없다. 짝 백엔드는 업로드 요청 안에서 검증을 끝내고, `READY`가 아닌 state는 모두 202로 답한다.
- `VERIFYING`: 검증기가 나중에 다시 보자고 했다. 서버가 다시 검사하면 `READY`가 될 수 있다.
- `QUARANTINED`: 격리됐다. 이름·타입 불일치, 스크립트 같은 이유다. 관리자가 정하기 전까지 내려받을 수 없다. "검사 중"으로 보이면 화면이 끝나지 않는 대기가 된다.
- `REJECTED`: 검증기가 거절했다(악성 코드 말고 다른 이유). 저장된 파일이 아니므로 성공으로 돌려주지 않는다. 실패 `VALIDATION_REJECTED`, code `FILE_REJECTED`, `NOT_APPLIED`다. 사용자가 다른 파일을 골라야 한다.
- 빈 파일은 보내지 않는다. 짝 백엔드 기본 검증기가 빈 파일을 거절하기 때문이다. `VALIDATION_REJECTED`, code `FILE_EMPTY`, `NOT_STARTED`다.
- 실패 `effect`:
- `NOT_STARTED`: 보내지 않았다. 입력, 크기, 자격 증명에서 거절했다.
- `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 정한 code(`STORAGE_UNAVAILABLE` 등)다.
- `MAYBE_APPLIED`: 올라갔을 수도 있다. 응답을 잃음, 시간 초과, `details.ambiguous: true`, 409 `IDEMPOTENT_IN_FLIGHT`, 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`, 그 밖의 5xx다. 다시 보낼 때는 같은 `idempotencyKey`를 쓴다.
- `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 작업 스레드가 게시 전에 내는 code 넷(`PARTIAL_WRITE`, `ATOMIC_PUBLISH_UNSUPPORTED`, `STORAGE_UNAVAILABLE`, `STORAGE_FULL`)이다.
- `MAYBE_APPLIED`: 올라갔을 수도 있다. 응답을 잃음, 시간 초과, `details.ambiguous: true`, 그 밖의 5xx다. 504 `TRANSFER_TIMEOUT`도 여기 든다. 백엔드는 대기 시간이 지나면 작업이 어느 단계에 있든 이 code를 내고, 작업은 그 뒤에 끝나 `READY`가 될 수 있다. 다시 보낼 때는 같은 `idempotencyKey`를 쓴다.
- 멱등성 응답(`IDEMPOTENT_*`, `IDEMPOTENCY_*`)과 V3 표에 있는 web 공통 응답은 V3 실행기와 같은 표(`backend-envelope.ts`, 4절)로 판정한다. 400 `IDEMPOTENCY_KEY_INVALID`·422 `IDEMPOTENT_REQUEST_MISMATCH`는 `NOT_APPLIED`, 409 `IDEMPOTENT_IN_FLIGHT`·503 `IDEMPOTENCY_UNAVAILABLE`·503 `IDEMPOTENCY_COMPLETION_UNKNOWN`·500 `IDEMPOTENCY_RECOVERY_REQUIRED`는 `MAYBE_APPLIED`다.
- `APPLIED_CONFIRMED`: 서버는 만들었다고 답했지만 응답을 읽지 못했다. 다시 올리지 않는다.
- `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 화면 문구는 기능이 code로 고른다.
- `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 백엔드가 code를 주지 않는 거절은 client가 이름을 붙인다(`FILE_REJECTED`, `FILE_EMPTY`, `FILE_NOT_READABLE`). 화면 문구는 기능이 code로 고른다.
- 실패 Envelope의 `meta.traceId`는 실패의 `traceId`로 온다. V3 실행기와 같다. 지원 담당이 서버 로그에서 그 요청을 찾을 때 쓴다.
- client는 스스로 다시 보내지 않는다. `retryable: true`이고 `retryAfterMs`가 있으면 그만큼 기다린 뒤 기능이 다시 부른다. 서버가 상한(`maxRetryAfterMs`, 기본 30초)보다 길게 기다리라고 하면 `retryable: false`다.
- `MAYBE_APPLIED`는 언제나 `retryable: false`다. 백엔드가 Envelope에 `retryable: true`와 `Retry-After`를 붙여도(504 `TRANSFER_TIMEOUT`) 기능이 자동으로 다시 부르지 않는다. 아래 주의대로 먼저 확인한다.
**주의 — 멱등 키**: 짝 백엔드(`bbe944bd`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`).
**주의 — 멱등 키**: 짝 백엔드(`45d2a478`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`).
- 그래서 `MAYBE_APPLIED` 뒤 다시 보내면 같은 파일이 두 개 생길 수 있다.
- 같은 키 재전송이 중복을 막는 것은 배포가 업로드를 백엔드 멱등성 executor 뒤에 둘 때뿐이다.
@@ -361,6 +372,8 @@ export function composeProduct(context: ProductCompositionContext) {
},
},
credentialProviders: { BACKEND_SESSION: sessionCredentials },
// BACKEND_SESSION은 세션 쿠키 그 자체다. 그 401은 세션을 로그아웃시킨다(5절).
onCredentialRejected: () => context.notifySessionUnauthenticated(),
} satisfies ProductComposition;
}
```
@@ -390,6 +403,8 @@ export const createAttachmentFeatureInput = defineFeatureAdapterContribution({
**틀리면**
- 프로필의 필수 헤더가 없으면 `fetch`를 부르지 않고 `MISSING_REQUIRED_CREDENTIAL_HEADER`로 끝난다.
- 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다.
- 백엔드가 Fileserver 응답 모양이나 code를 바꾸면 검사가 잡지 못한다. 실패 판정 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`, `MAYBE_APPLIED_CODES`)는 백엔드 `bbe944bd` 기준이다. 백엔드 SHA가 바뀌면 같이 다시 본다.
- 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 계약대로 답하는 MSW).
- 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다. 비어 있으면 `FILE_EMPTY`(`NOT_STARTED`)다.
- 202 응답을 모두 "검사 중"으로 보이면 `QUARANTINED` 파일의 화면이 끝나지 않는다. state마다 따로 보인다.
- 멱등성·web 공통 응답의 판정은 V3 표를 그대로 쓴다. `tests/integration/fileserver-upload.test.ts`가 pin 옆에 복사한 백엔드 답 표(`config/contracts/backend-idempotency-answers.json`)의 행마다 client와 V3 표가 같은지 본다. pin을 옮기면 같이 다시 돈다.
- 백엔드가 Fileserver 응답 모양이나 Fileserver 자신의 code를 바꾸면 검사가 잡지 못한다. 그 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`)는 백엔드 `45d2a478`(pin) 코드를 읽은 것이다. 백엔드 SHA가 바뀌면 `FileserverErrorCode`, `BlockingTransferExecutor`, 게시 경로를 같이 다시 본다. 4xx를 `NOT_APPLIED`로 보는 이유는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절에 있다.
- 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 코드가 답하는 대로 답하는 MSW. 백엔드 문서는 202 `VERIFYING`만 적는다).
+34 -4
View File
@@ -19,7 +19,7 @@
## A. 생성 명령이 만든다
`corepack pnpm create:feature`가 쓰는 폴더 밖 파일은 둘이다. 있는 파일은 덮어쓰지 않는다.
`corepack pnpm create:feature`가 새로 만드는 폴더 밖 파일은 둘이다. 있는 파일은 덮어쓰지 않는다. 이미 있는 추적 파일 중 다시 쓰는 것은 아래 "기능마다 바뀌는 템플릿 추적 파일"에 있다.
- `src/contexts/<context>/context-module.ts`
- 새 context일 때만 만든다. `--context`를 주면 만들지 않는다.
@@ -31,6 +31,19 @@
`src/.generated/`도 기능 폴더 밖이다. 생성기가 매번 다시 만든다. 손으로 고치지 않는다.
### 기능마다 바뀌는 템플릿 추적 파일 (1105/16-01)
새 파일 말고도, 기능 하나를 더하면 이미 있는 추적 파일 두 개가 바뀐다. 둘 다 명령이 쓰고, 기능과 같은 커밋에 넣는다.
| 파일 | 누가 쓰나 | 다시 쓰는 명령 | 안 넣으면 |
|---|---|---|---|
| `public/release-manifest.json` (dev server의 manifest) | `create:feature`가 생성 뒤 바로 쓴다. 설치된 계약 패키지 목록(`packages`)과 그 다이제스트(`setDigest`) | `node scripts/write-dev-release-manifest.ts` | `test:unit`(`tests/unit/dev-release-manifest.test.ts`)이 다시 쓰는 명령을 말하며 실패한다. dev server가 `CONTRACT_SET_PACKAGE_MISSING`으로 부팅하지 못한다 |
| `config/scale/feature-shape-ceilings.json`의 `initialJavascript` (초기 JS 기록) | 사람이 명령으로 쓴다. 참조 기능이 설치돼 있는 동안만 있다(참조 기능과 함께 지워진다) | `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write` | `test:unit`이 빌드와 대조해 실패한다 |
- **브랜치 둘이 충돌한다.** `setDigest`는 설치된 패키지 전체의 해시 한 줄이고, `initialJavascript`는 빌드 전체의 합계다. 기능을 하나씩 더한 두 브랜치는 같은 줄을 다른 값으로 바꾼다. 둘째 브랜치를 합칠 때 텍스트 충돌이 난다.
- **충돌하면 손으로 값을 합치지 않는다.** 아무 쪽이나 고른 뒤 위 명령을 다시 돌려 그 결과를 커밋한다. 두 기능이 다 들어간 상태의 값이 나온다. 손으로 합친 값이 틀리면 `test:unit`이 같은 명령을 말하며 실패한다.
- 레지스트리 기준선(`config/contracts/registry-baseline.json`)은 기능을 더하기만 하면 바뀌지 않는다(아래 C).
---
## B. 사람이 꼭 해야 한다
@@ -106,11 +119,13 @@ release admission refused for staging:
- `product-composition.ts` 안에서 `FeaturePlatformCapabilities`를 보강(`declare module`)하면 `check:types:node`가 그 키를 보지 못한다.
- `src/bootstrap/product-composition.ts`: 위 capability의 값을 돌려줄 때. 제품 인증 프로필의 자격 증명도 여기서 준다.
- 로그아웃·계정 전환 때 닫아야 하는 것(파일 runtime 등)은 `scopeParticipants`로 돌려준다. 예제: `recipes/frontend-capabilities/browser-file-session-capability.ts`.
- `label`은 `browser-files` 같은 소문자 kebab-case 토큰으로 쓴다. 다른 형식이면 조립이 `TypeError`로 멈춘다.
- `close`가 던지면 scope가 `FAILED`에 머물고 모든 서버 요청이 `SCOPE_FENCED`로 막힌다. 진단 `cache.operation.failed`에 `reason: PARTICIPANT_FAILED`와 `scope_participant: <label>`이 남으니 그 기록으로 원인 closer를 찾는다.
- 템플릿 파일 `src/bootstrap/runtime-adapters.ts`는 고치지 않는다.
- 실시간 갱신: 짝 백엔드의 실시간 출구(STOMP·NDJSON)와 프론트 realtime 어댑터(SSE·`realtime.v1` WebSocket)는 그대로 연결되지 않는다. 지금 되는 경로는 bounded polling이다. 대응표: [realtime 설계 0.1절](../architecture/realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02).
- `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: <키>`로 실패한다.
- 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈추고, 오류 화면의 "잘못된 설정 키"에 그 키 이름(값은 아님. 중첩 키는 `CAPABILITY_OVERRIDES.AUTH_TOKEN`처럼 경로)이 나온다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다.
- FE-REG-ENV 행의 `required`·`defaultValue`는 zod 필드가 키가 없을 때 하는 것과 같게 적는다. 기본값이 없으면 `defaultValue: null`이다. 같은 테스트가 대조한다.
- `config/runtime/<profile>.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`).
- `src/features/product-capabilities.ts`의 선택 런타임(`PRODUCT_RUNTIME_CAPABILITY_SELECTION`): Service Worker를 켤 때. 아래 "SW 켜기"를 본다.
@@ -151,7 +166,22 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE)
4. 지우려면 한 번에 `null`로 가지 않는다. `REMOVE_REGISTRATION` → `PURGE_OWNED_RESOURCES` → `null` 순서로 릴리스한다. 이미 설치된 브라우저의 worker를 먼저 내려야 한다.
- 고치지 않는다: `src/features/installed-runtime-capabilities.ts`(템플릿 소유, D절).
- 템플릿이 아직 연결하지 않은 것: 저장하지 않은 편집이 있는 탭의 활성화 거절(`blockers`), page controller의 `observe`, 활성화 화면. 지금은 `src/bootstrap/create-runtime-composition.ts`(템플릿 소유)를 고쳐야 연결된다. 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다.
- 저장하지 않은 편집이 있는 탭의 활성화 거절(`blockers`)과 page controller의 `observe`는 제품 소유 `src/bootstrap/product-composition.ts`에서 잇는다. `composeProduct`가 `serviceWorker`를 돌려주면 템플릿 조립이 그대로 넘긴다(1103/09-05). `observe`가 던져도 worker 흐름은 바뀌지 않는다.
```ts
export function composeProduct(context: ProductCompositionContext) {
return {
capabilities: {},
credentialProviders: {},
serviceWorker: {
blockers: [() => hasUnsavedEdits()],
observe: (observation) => reportServiceWorker(observation),
},
} satisfies ProductComposition;
}
```
- 템플릿이 아직 연결하지 않은 것: 활성화 화면(`onUpdateWaiting`·`requestActivation()`). 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다.
- realtime·Web Worker·오프라인 명령을 고르면 조립이 `Selected optional capabilities have no runtime to start them`로 거절한다. 템플릿 조립에 아직 그 런타임이 없다.
---
@@ -182,7 +212,7 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE)
- `config/testing/risk-coverage.json`에서 그 기능을 가리키는 행
- 그 기능만 쓰던 제품 capability, 제품 인증 프로필, 계약 패키지 의존성
그다음 dev manifest(`public/release-manifest.json`)의 계약 패키지를 `node scripts/write-dev-release-manifest.ts`로 다시 쓰고, 레지스트리 기준선을 다시 찍는다. 행을 빼는 것은 breaking 변경이다.
그다음 dev manifest(`public/release-manifest.json`)의 계약 패키지를 `node scripts/write-dev-release-manifest.ts`로 다시 쓰고, 참조 기능이 설치돼 있으면 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`로 다시 쓴다(위 A의 표). 그리고 레지스트리 기준선을 다시 찍는다. 행을 빼는 것은 breaking 변경이다.
```bash
REGISTRY_BASELINE_OWNER=<담당> REGISTRY_BASELINE_REASON="<id> removed" corepack pnpm update:registry-baseline
+12 -4
View File
@@ -44,6 +44,7 @@
- `fetcher`는 마감이 없다. owner에서 쓰지 않는다. 응답하지 않는 호출 하나가 세션을 "복구 중"에 영원히 둔다.
- `page`: 지금 URL, URL 바꾸기, 다른 페이지로 이동. 로그인 리다이렉트에 쓴다.
- `redirectStorage`: 페이지의 sessionStorage. 리다이렉트 한 번 동안의 상태만 둔다. 토큰은 두지 않는다(`AUTH_TOKEN`은 `src/contracts/storage-keys.ts`에서 `forbidden`이다).
- 키는 registry의 `AUTH_REDIRECT_TRANSACTION`(`backend: "external"`)에서 가져온다. 그래야 `APP_NAMESPACE`를 바꿀 때 같이 바뀐다. 새 owner도 키를 글자로 적지 않는다.
- `readCookie`: 페이지 쿠키 읽기.
4. recipe는 `src/bootstrap/` 아래로 **복사**한다. import하지 않는다.
- `src`가 `recipes/`를 import하면 `check:optional-recipes`가 `PRODUCTION_IMPORTS_RECIPE`로 막는다.
@@ -125,12 +126,13 @@ export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({
});
export const PRODUCT_ENV_REGISTRY = Object.freeze({
OIDC_ISSUER: { phase: "runtime", classification: "public", required: false },
OIDC_CLIENT_ID: { phase: "runtime", classification: "public", required: false },
OIDC_ISSUER: { phase: "runtime", classification: "public", required: false, defaultValue: null },
OIDC_CLIENT_ID: { phase: "runtime", classification: "public", required: false, defaultValue: null },
} as const);
```
- `.optional()`로 둔다. 값이 비면 owner는 `integration-failed`로 닫힌다. 잘못된 곳으로 로그인하지 않는다.
- 행의 `required`·`defaultValue`는 그 키가 없을 때 스키마가 하는 것과 같아야 한다. `.optional()`이면 `required: false, defaultValue: null`이다(`tests/unit/env-registry-coverage.test.ts`). 이 블록은 그대로 `tests/unit/manual-paired-backend-settings.test.ts`가 타입 검사와 그 대조를 돌린다.
- `config/runtime/local.json`에 `"OIDC_ISSUER": "http://localhost:8081/realms/ca-skeleton"`, `"OIDC_CLIENT_ID": "ca-frontend"`를 더한다.
- `OIDC_ISSUER`는 백엔드 `APP_SECURITY_JWT_ISSUER`와 글자 하나까지 같아야 한다. 끝의 `/`도 같아야 한다.
- 원격 issuer는 HTTPS만 받는다. HTTP는 `localhost`, `127.0.0.1`, `[::1]`에서만 받는다.
@@ -183,9 +185,10 @@ export function composeProductSessionOwner(
읽기 요청 (SESSION_COOKIE_READ) → 쿠키만
쓰기 요청 (SESSION_COOKIE_WRITE) → 쿠키 + X-XSRF-TOKEN: <XSRF-TOKEN 쿠키 값>
서버 401 → [unauthenticated]
서버 401 → onCredentialRejected → 템플릿 세션 [unauthenticated]
```
- 서버 401이 세션에 닿는 길은 4.3의 `onCredentialRejected` 한 줄뿐이다. 템플릿은 제품 provider가 낸 자격 증명의 401을 제품에만 알린다([02 결정표](02-decision-tables.md) 5절). 이 줄을 빼면 서버 세션이 끝나도(Redis TTL 만료, 다른 탭·서버에서 로그아웃) 화면은 로그인 상태로 남고, 요청마다 `AUTH_REQUIRED` 실패 화면만 보인다.
- CSRF: 다른 사이트가 사용자의 쿠키로 쓰기를 보내는 공격이다. 백엔드는 스크립트가 읽을 수 있는 `XSRF-TOKEN` 쿠키를 주고, 쓰기 요청의 `X-XSRF-TOKEN` 헤더가 그 값과 같은지 본다. 다른 사이트의 스크립트는 이 쿠키를 읽지 못한다.
- 백엔드는 plain 방식이다(`CsrfTokenRequestAttributeHandler`). 쿠키 값을 그대로 헤더에 넣는다.
@@ -215,6 +218,7 @@ recipe를 `src/bootstrap/` 아래로 복사한 뒤 `src/bootstrap/product-compos
import {
createCookieSessionOwner,
createSessionCookieCredentialProviders,
createSessionCookieRejectionHandler,
} from "./cookie-session-owner.ts";
export function composeProductSessionOwner(
@@ -241,12 +245,16 @@ export function composeProduct(context: ProductCompositionContext) {
credentialProviders: createSessionCookieCredentialProviders({
readCookie: context.readCookie,
}),
// 서버 401 → 세션 unauthenticated. 빼면 세션이 끝나도 화면은 로그인 상태다.
onCredentialRejected: createSessionCookieRejectionHandler(context),
} satisfies ProductComposition;
}
```
- 위 경로(`api/session` 등)는 예시다. 4.1에서 만든 엔드포인트 주소를 쓴다.
- provider는 세션 상태를 묻지 않는다. 쿠키가 증명이고 서버가 판정한다. 서버의 401은 owner에게 간다.
- provider는 세션 상태를 묻지 않는다. 쿠키가 증명이고 서버가 판정한다.
- 서버의 401은 `onCredentialRejected`를 거쳐 세션에 간다. handler는 `SESSION_COOKIE_*` 프로필의 401만 `context.notifySessionUnauthenticated()`로 넘긴다. 그러면 세션이 `unauthenticated`가 되고 서버 상태 캐시가 비워진다. 다른 제품 프로필(외부 API 토큰 등)의 401은 넘기지 않는다.
- 제품에 다른 `onCredentialRejected`가 이미 있으면 그 함수 안에서 이 handler도 부른다.
### 4.4 페이지와 API는 같은 host여야 한다
+2 -1
View File
@@ -94,7 +94,8 @@ corepack pnpm create:feature <id> [--context <context id>] [--with-create [--key
- 모든 operation이 `responseEnvelope: "ENVELOPE_V1"`이다.
- 쿼리 1개: `LIST_STANDARD` profile.
- 무효화 topic 1개, namespace 1개, edge 1개.
- 빈 배열 응답은 공유 빈 상태 화면으로 그린다. `tests/e2e/accessibility.spec.ts`는 이 목록 조회에 빈 목록을 Envelope 모양으로 답하고, 경고 상자가 없는지 본 뒤 axe를 돌린다. 그래서 생성한 라우트는 빈 상태 화면으로 검사된다.
- 빈 배열 응답은 공유 빈 상태 화면으로 그린다. `tests/e2e/accessibility.spec.ts`는 이 목록 조회에 빈 목록을 Envelope 모양으로 답하고, 경고 상자가 없는지 본 뒤 axe를 돌린다. 그래서 생성한 목록 라우트는 빈 상태 화면으로 검사된다.
- `--with-create`의 상세 라우트는 자원 하나를 읽는다. 빈 목록으로 답할 수 없어 실패 화면에서만 axe를 돌린다. 그래서 `artifacts/tests/a11y.json`은 이 라우트를 통과(`scope`)로 세지 않고 `notChecked`에 이유와 함께 적는다. 화면 내용의 접근성은 수동 검토 기록(`artifacts/tests/a11y-manual/<ROUTE_ID>.md`)이 맡는다.
한도·마감 같은 숫자는 `scripts/create-feature.ts`의 템플릿이 정본이다.
+5 -3
View File
@@ -103,8 +103,10 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `<id>/<operationId>: KEYED commands require a recovery descriptor` | `KEYED`인데 `commandRecovery`가 없다 | V3 `commandRecovery` |
| `<id>/<operationId>: <GET·HEAD> is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` |
| `<id>/<operationId>: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` |
| `<id>/<operationId>: refusedBeforeWrite cannot declare <code>; contract 6.1 reads this platform code as possibly raised after the write` | `commandEffect.refusedBeforeWrite`에 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `DB_*` 등)를 적었다 | 그 code를 목록에서 지운다. 그 실패는 결과 불명으로 남는다([02 결정표 4절](../02-decision-tables.md#4-결과-불명)) |
| `<id>/<operationId>: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` |
| `<id>/<operationId>: responseEnvelope NONE, but <other> in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `responseEnvelope` 줄을 빠뜨린 경우다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 |
| `<id>/<operationId>: responseEnvelope NONE, but <other> in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `"NONE"`을 적었거나, TypeScript 밖에서 만든 descriptor가 줄을 뺐다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 |
| `check:types`: `Property 'responseEnvelope' is missing in type ...` (descriptor의 `satisfies InstalledHttpContract<...>`) | descriptor에 응답 모양 줄이 없다. 1103/16-01부터 필수 칸이다 | 짝 백엔드면 `responseEnvelope: "ENVELOPE_V1" as const`, 감싸지 않는 백엔드면 `"NONE" as const` |
| `<id>: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `<BASE>_CONTRACT_PACKAGE.version` |
### 라우트·context
@@ -151,7 +153,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `FE-REG-ROUTE.<ROUTE_ID>.<field> has unknown value <value>` | `access`·`errorSurface`가 정해진 값이 아니다 | 계약 `routes` |
| `FE-REG-ROUTE.<ROUTE_ID>.paramsSchema references unknown FE-REG-SCHEMA.schemaId=<id>` | 라우트 스키마 ID를 기능이 등록하지 않았다 (`searchSchema`도 같은 꼴) | 계약 스키마 메타 |
| `FE-REG-API.<operationId> has no executable consumer for operationId=<operationId>` | 계약의 operation을 기능 `adapters/`·`application/`에서 쓰지 않는다 | 쓰지 않으면 descriptor를 지운다 |
| `missing registry source <path>: <message> (reason: <reason>)` | 레지스트리 source를 읽다가 오류가 났다. 계약 조립 실패면 `<reason>`이 위 `reason` 표의 값이다. 읽지 못한 레지스트리는 `removed` 증거를 요구하지 않는다 | `<reason>`이 가리키는 곳 |
| `missing registry source <path>: <message>` | 레지스트리 source를 읽다가 오류가 났다. 계약 조립 실패면 `<message>`가 `Installed contract contribution is not composable: <reason>`이고 `<reason>`이 위 `reason` 표의 값이다. 다른 오류가 `reason` 속성을 message와 따로 가지면 끝에 ` (reason: <reason>)`이 붙는다. 읽지 못한 레지스트리는 `removed` 증거를 요구하지 않는다 | `<reason>`이 가리키는 곳 |
| `breaking change missing evidence: <changeId>` | 행을 빼거나 바꿨는데 승인이 없다 | `update:registry-baseline` 또는 `config/contracts/registry-change-evidence.json` |
| `stale breaking evidence <changeId>: no breaking change in the current diff has this changeId. ...` | 지금 diff와 맞지 않는 증거 행 | 그 행을 지운다 |
| `registry baseline approval digest mismatch: approved=<digest> actual=<digest>` | 기준선 파일을 손으로 고쳤다 | `update:registry-baseline`으로 다시 찍는다 |
@@ -194,6 +196,6 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| 메시지 | 원인 | 고칠 곳 |
|---|---|---|
| `<id> removal failed:` 다음 `fixture-id-residue: residue: <files>` (`test:sample-removal`) | 기능을 지운 뒤에도 `src`·`tests`에 기능 ID를 담은 파일이 남았다 | 그 파일을 기능 폴더 안으로 옮기거나, 기능 ID를 담지 않게 한다 |
| `<id> removal failed:` 다음 `fixture-id-residue: residue: <files>` (`test:sample-removal`) | 기능을 지운 뒤에도 그 기능을 가리키는 파일이 남았다. `src`는 기능 ID나 폴더 이름을 담은 파일, `tests`는 이름이 기능 ID를 담거나 기능 폴더(`src/features/<id>/`, `tests/features/<id>/`)에서 import하는 파일이다 | 그 파일을 기능 폴더 안으로 옮기거나, 기능을 가리키지 않게 한다. 목록에 템플릿 파일이 나오면 템플릿 결함이다. 그 파일을 고치지 말고 템플릿에 알린다 |
| `No installed feature declares FEATURE_MODULE_ID "<id>"` | `--feature=`에 없는 기능 ID | 명령 인자 |
| `feature scaffold failed:` 다음 `<check>: <failure>` (`test:feature-scaffold`) | 생성한 기능이 게이트 하나를 통과하지 못했다 | `scripts/create-feature.ts`의 템플릿. 제품 팀이 아니라 템플릿을 고칠 일이다 |
+4 -4
View File
@@ -3,7 +3,7 @@
기능을 만들 때 쓰는 패턴과, 그 패턴의 정의와 예제가 어디 있는지 적는다.
- **정의**: 플랫폼(기능 밖)에서 패턴을 제공하는 파일.
- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature <id> --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `참조 기능`은 src/features/reference-feature/다(Envelope가 아닌 problem details 모양). 참조 기능은 지울 수 있으므로 그 경로는 백틱 없이 적는다. 백틱 경로는 문서 검사(`verify:documentation`)가 존재를 확인한다.
- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature <id> --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `참조 기능`은 `src/features/reference-feature/`다(Envelope가 아닌 problem details 모양). 참조 기능 경로도 다른 경로처럼 백틱으로 적는다. 문서 검사(`verify:documentation`)는 참조 기능이 있는 동안 그 경로가 있는지 확인하고, 참조 기능을 지운 사본에서는 없어도 된다고 본다(`scripts/lib/removable-template-features.ts`).
- 예제가 없는 패턴은 **없음**이라고 적었다. 그 패턴은 정의를 읽고 직접 쓴다.
참조 기능은 예제일 뿐이다. 복사해 이름을 바꾸지 않는다. 모양을 보고 생성 뼈대에 옮긴다.
@@ -13,12 +13,12 @@
| 패턴 | 정의 | 예제 | 검사 |
|---|---|---|---|
| 기능 모듈 등록 | `src/features/feature-module.ts` (`defineFeatureModule`, `defineFeatureRuntime`), 생성기 | 생성 뼈대 `feature-module.ts`, `feature-runtime.ts` | 생성기, 기능 ID와 계약 `featureId` 일치 |
| context 소속 선언 | `src/contexts/bounded-context-module.ts` | 참조 기능의 src/contexts/reference-context/context-module.ts | 생성기(없는 context, 예산), 앱 모듈(루트 밖 라우트) |
| context 소속 선언 | `src/contexts/bounded-context-module.ts` | 참조 기능의 `src/contexts/reference-context/context-module.ts` | 생성기(없는 context, 예산), 앱 모듈(루트 밖 라우트) |
| context 전용 레이아웃 | `docs/architecture/starter-experience.md` "Product home and layouts" | `tests/helpers/fixture-layout-product.tsx` (테스트 fixture) | `tests/component/context-layouts.test.tsx` |
| 앱 홈 대신하기 | `src/contracts/routes.ts`의 `FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` | 없음 (기능 예제) | 조립 (두 기능이 `APP_HOME`을 선언하면 실패) |
| 조립 기여(`needs`) | `src/features/feature-adapter-contribution.ts` | 생성 뼈대 `adapters/create-<base>-feature-input.ts` | 조립 (없는 capability, 다른 기능의 input) |
| 제품 capability | `src/features/product-capabilities.ts`(타입), `src/bootstrap/product-composition.ts`(값), `src/bootstrap/product-composition-contract.ts` | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | `check:types` |
| 기능 끄기 | `config/runtime/<profile>.json`의 `FEATURE_OVERRIDES` | `config/runtime/local.json` | 참조 기능의 tests/component/product-feature-switch.test.tsx |
| 기능 끄기 | `config/runtime/<profile>.json`의 `FEATURE_OVERRIDES` | `config/runtime/local.json` | 참조 기능의 `tests/component/product-feature-switch.test.tsx` |
## 라우트
@@ -95,7 +95,7 @@ const search = (q: string) =>
|---|---|---|---|
| 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use-<base>-items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 |
| 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) |
| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/<base>-contract-contribution.ts`, `presentation/use-<base>-create.ts`), 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름), 기능 테스트 |
| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/<base>-contract-contribution.ts`, `presentation/use-<base>-create.ts`), 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/<base>-create-page.tsx`, 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만(쓰기 slice는 `<base>-create-page.test.tsx`) |
| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (참조 기능은 생성 명령만 있다) | — |
| 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 |
@@ -194,7 +194,7 @@ Captured after every correctness task landed.
| `git diff --check` | 0 | clean |
| `corepack pnpm test:component` | 0 | 126 passed |
| `corepack pnpm test:integration` | 0 | 52 passed |
| test:reference-feature (the reference sample's script) | 0 | 26 passed |
| `corepack pnpm test:reference-feature` | 0 | 26 passed |
| `corepack pnpm test:recipes` | 0 | 17 passed |
| `corepack pnpm test:unit` | 1 | 1585 passed / 19 failed tests; the 19 are the unchanged pre-existing `ci-artifact-contract` sandbox failures |
| `corepack pnpm check:registries` | 0 | 11 registries PASS |
@@ -340,7 +340,7 @@ Run on the landed tree. Only what actually passed is claimed as passing.
| `tests/unit` + `tests/integration`, no exclusions | — | 1643 passed / 1747; the 104 failures are the four environmental files below |
| `corepack pnpm test:component` | 0 | 126 passed |
| `corepack pnpm test:recipes` | 0 | 17 passed |
| test:reference-feature (the reference sample's script) | 0 | 26 passed |
| `corepack pnpm test:reference-feature` | 0 | 26 passed |
### Environmental failures, not claimed as green
@@ -257,7 +257,11 @@ diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그
key다. 자동 재전송은 없다(`src/presentation/adapters/query/application-query.ts`
`submit`·`resendUnknownEffect`, 화면 `src/presentation/components/async-surface.tsx`).
키가 없는 command(`NEVER`)는 서버가 두 번째 요청을 가려내지 못하므로 재전송 버튼을
그리지 않는다(`canResendUnknownEffect`, 0929/03-03).
그리지 않는다(`canResendUnknownEffect`, 0929/03-03). 같은 canonical input의 재저장도
보내지 않는다. 훅의 `submit`이 `NOT_STARTED` `DUPLICATE_IN_FLIGHT`(code
`UNKNOWN_EFFECT_PENDING`)를 돌려주고, 결과 불명 요청이 확인될 때까지 그대로다. 폼
밖에서 `submit`을 부르는 화면도 같다. 화면은 상태에 `unknownEffectResendable: true`가
있을 때만 재전송 버튼을 그린다.
5. backend status/receipt로 `COMMITTED`면 cache reconcile/invalidate한다. 화면의
"변경됨으로 확인"이 이 경로다.
6. `NOT_APPLIED`가 증명된 경우만 정책에 따라 retry한다. 화면은 근거 없는
@@ -40,23 +40,24 @@ cleanup 결과를 확인하지 못하면 성공 값이 아니라 실패로 답
계속 돌고, 관측은 `OBJECT_RECONCILE` `DEGRADED` / `CORRUPT_DATA`로 남는다
([0929] 05-01). reconcile은 그 row를 지우지 않는다. 그 partition이 승인된
purge로 통째로 지워질 때 함께 지워지는 것은 partition 키(`logicalKey`)를
읽을 수 있는 row뿐이다(§7). 승인된 LOGOUT/ACCOUNT_DELETION purge는 그런
row를 보면 그 partition을 지운다(2026-11-03 05-01).
읽을 수 있는 row뿐이다(§7). 승인된 LOGOUT/ACCOUNT_DELETION purge는 객체를
끝까지 돌면 늘 그 partition을 지운다(1103/05-01 잔여).
- `unattributedCorruptTransactions`: 위 수 가운데 `logicalKey`까지 읽을 수
없는 row 수다. 어느 partition에도 속하지 않아 partition 삭제도 지우지
못한다. 그래서 따로 세고 `DEGRADED` 관측에서 뺀다(2026-11-03 05-03). 예전에는
이런 row 하나가 reconcile마다 `DEGRADED`를 남겨 경보가 늘 켜졌다. 같은 수로
남아 있으면 할 일이 없다. 수가 늘면 키 없는 row를 쓴 writer(다른 release,
외부 도구)를 찾는다. 이 row도 수동으로 지우지 않는다(3번). 그 row의
staging은 partition 디렉터리 안에 있어 그 partition이 지워지면 함께
지워지지만, 이 row는 purge의 partition 삭제 조건에 들지 않는다.
staging은 partition 디렉터리 안에 있어 승인된 purge가 그 partition을
지울 때 함께 지워진다. 예전에는 purge가 이 row를 세지 못해 chunk sweep으로
끝났고, staging receipt가 지킨 chunk·manifest가 `COMPLETED` 뒤에도
남았다(1103/05-01 잔여).
3. journal row를 수동으로 삭제하지 않는다. row가 사라지면 stale staging을 추적할
근거가 사라지고 quota만 누수된다.
4. OPFS root나 journal database를 통째로 삭제하거나 schema를 downgrade하지
않는다. rollback은 새 v2 write admission을 닫고 v1+v2 reader를 유지하는 것으로
수행한다. runtime이 스스로 지우는 것은 승인된 purge가 손상이나 끝나지 않은
transaction 때문에 끝나지 못할 때의 그 partition 디렉터리 하나와 그 partition의
journal row뿐이다(§7).
수행한다. runtime이 스스로 통째로 지우는 것은 승인된 LOGOUT/ACCOUNT_DELETION
purge의 그 partition 디렉터리 하나와 그 partition의 journal row뿐이다(§7).
## 1. 공통 원칙
@@ -450,27 +451,33 @@ VD-15 목표 runtime을 먼저 구현한다.
- `COMMITTED` + file missing/corrupt: reconstructable만 server rehydrate;
user-created private는 read-only/export/recovery
- stale staging/orphan chunk는 grace period와 bounded mark/sweep 후 제거
- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 모두 지운 뒤 그 partition의 journal
row를 센다. 하나라도 있으면(다른 tab에서 진행 중인 put·delete, crash가 남긴
`PREPARING`·`FILES_READY`, 키는 읽히는 손상 row) sweep 대신 아래 partition
삭제로 간다(2026-11-03 05-01). 예전에는 이 row를 보지 않고 `COMPLETED`를
돌려줬다. 그래서 진행 중 put의 객체가 purge 뒤에도 읽혔고, `FILES_READY` row는
다음 reconcile이 commit해 객체로 되살렸다. row가 없으면 그 partition의 chunk를
grace 없이 sweep한다(05-04, `opfs-byte-store-adapter.ts` `enforcePolicies`).
staging receipt가 참조하는 chunk는 이때도 지우지 않는다. 이 두 reason에서는
report의 `chunkSweep`이 `COMPLETED`이거나 `partitionDeleted`가 있을 때 그
partition의 bytes가 지워진 것이다. `DEADLINE_REACHED`면 같은
purge를 다시 호출하고, `STAGING_STATE_UNREADABLE`이면 읽을 수 없는 staging부터
처리한다. 다른 탭이 바꾸고 있던 객체를 지우지 못하면 report는
`moreObjectsAvailable: true`이고 `chunkSweep`이 없다. 이때도 같은 purge를 다시
호출한다([0929] 05-02)
- 손상이나 끝나지 않은 transaction 때문에 끝나지 못하는 `LOGOUT`/
`ACCOUNT_DELETION` purge는 partition을 통째로 지운다([0929] 05-01,
2026-11-03 05-01, `opfs-byte-store-adapter.ts` `enforcePolicies`).
- `LOGOUT`/`ACCOUNT_DELETION` purge는 객체를 하나씩 지운 뒤, 마지막 객체까지
돌았으면 늘 아래 partition 삭제로 끝낸다(1103/05-01 잔여,
`opfs-byte-store-adapter.ts` `enforcePolicies`). chunk sweep으로 끝내지 않는다.
- 예전 동작: 객체를 다 돈 뒤 journal row를 한 번 세고, 0이면 chunk를 grace 없이
sweep해 `chunkSweep: "COMPLETED"`를 돌려줬다(05-04, 2026-11-03 05-01). 목록과
세기는 각각 한 순간만 본다. 그래서 두 경우에 bytes가 남은 채 `COMPLETED`였다.
① 다른 tab이 새 객체를 put하는 중이고 partition에 객체가 3개 이상이면, 그 put이
목록 뒤에 commit하고 세기 전에 끝났다. 목록에도 row 수에도 없어 sweep이 그
chunk를 건너뛰었고, 그 파일이 계정 삭제 뒤에도 읽혔다(메모리 20/20, Chromium
6/6). ② 멈춘 put의 journal row가 `logicalKey`를 잃으면 세지 못했고, 그
staging receipt·chunk·manifest가 purge마다 남았다.
- 이제 결과: 그 partition의 bytes가 지워진 것은 report에 `partitionDeleted`가
있을 때다. `chunkSweep`은 더 이상 채우지 않는다(port 타입에는 호환을 위해
남겼다).
- 예산(`budgetMs`·`maxObjects`)이나 다른 tab의 변경 때문에 객체를 끝까지 돌지
못하면 report는 `moreObjectsAvailable: true`이고 `partitionDeleted`가 없다.
같은 purge를 다시 호출한다([0929] 05-02). 다만 이때 그 partition의 journal
row(다른 tab에서 진행 중인 put·delete, crash가 남긴 `PREPARING`·`FILES_READY`,
키는 읽히는 손상 row)가 하나라도 있으면 그 호출이 바로 partition을 지운다
(2026-11-03 05-01).
- 승인된 `LOGOUT`/`ACCOUNT_DELETION` purge의 partition 삭제([0929] 05-01,
2026-11-03 05-01, 1103/05-01 잔여, `opfs-byte-store-adapter.ts`
`enforcePolicies`).
- 조건: 정책이 그 reason을 허용하고, authority가 이번 purge의 proof를 내주고
consumer가 소비했을 때(IndexedDB의 database 전체 삭제와 같은 승인). 그리고
다음 중 하나를 만났을 때: 목록에서 건너뛴 손상 object row, 손상 row 때문에
`CORRUPT_DATA`로 끝난 remove나 chunk sweep, `STAGING_STATE_UNREADABLE`, 그
다음 중 하나일 때: 마지막 객체까지 돌았다, 목록에서 건너뛴 손상 object row,
손상 row 때문에 `CORRUPT_DATA`로 끝난 remove, 끝까지 돌지 못한 호출에서 그
partition 키를 가진 journal row(`countPartitionTransactions`가 1 이상).
TTL·SESSION_END·UNTIL_SYNCED·PRESSURE는 손상 row를 건너뛰고 세기만 한다.
- 범위: worker가 origin mutation lease를 쥔 채
@@ -482,8 +489,9 @@ VD-15 목표 runtime을 먼저 구현한다.
row는 남긴다. 다른 partition은 건드리지 않는다.
- 결과: `partitionDeleted: true`, `moreObjectsAvailable: false`, 건너뛴 row 수
`corruptObjects`. 이 report면 그 partition의 bytes는 모두 지워진 것이다.
`chunkSweep`은 없다. 디렉터리는 지웠는데 journal 정리가 실패하면 실패를
반환한다. 같은 purge를 다시 호출하면 이어서 끝난다.
`removedObjects`·`releasedBytes`는 삭제 전에 하나씩 지운 객체만 센다.
디렉터리는 지웠는데 journal 정리가 실패하면 실패를 반환한다. 같은 purge를
다시 호출하면 이어서 끝난다.
- 다른 tab의 put·delete와의 순서: 모든 put·delete는 journal `begin`부터 끝날
때까지 partition lock(Web Lock
`<mutationLockName>:partition:<authorityToken>:<namespaceToken>:<partitionToken>`)을
@@ -504,9 +512,10 @@ VD-15 목표 runtime을 먼저 구현한다.
멈추고 `ABORTED`를 반환한다. 삭제 뒤에 줄 선 put·delete도 자기 `signal`로
기다림을 멈춘다. 어느 쪽이든 partition lock 기다림은
`mutationLockWaitTimeoutMs`(기본 10분)에서 `BLOCKED`(retryable)로 끝난다
(2026-11-03 05-02). purge가 journal row를 센 뒤에 시작한 put, 삭제가
lock을 요청한 뒤 온 put의 데이터는 남는다(point-in-time). purge 전에 그
partition의 쓰기를 멈추는 것이 composition의 몫이다.
(2026-11-03 05-02). 삭제가 lock을 요청한 뒤 온 put의 데이터는 남는다
(point-in-time). 그 전에 시작한 put은 삭제가 기다렸다가 함께 지운다.
모든 승인 purge가 이제 이 lock을 기다리므로, 다른 tab에서 오래 걸리는 put이
있으면 purge도 그만큼 늦게 끝난다.
- lock/worker 문제면 OPFS write off → approved capped fallback 또는 online-only
- scope binding mismatch면 affected scope를 read-only로 격리하고 registry/
composition을 forward fix; 다른 token path로 bytes를 이동하거나 추측 복구 금지
+12 -5
View File
@@ -66,7 +66,7 @@ package script 그래프로 닿거나, 게이트가 이미 돌리는 Vitest 경
| CI 계약 크기·게이트 모양 | `config/ci/contract-baseline.json` | `update:ci-contract-baseline` (`CI_CONTRACT_BASELINE_OWNER`·`_REASON` 필수) | `scripts/contracts/ci-gates.ts` `assertCiContractBaseline` |
| registry 스냅샷과 승인 | `config/contracts/registry-baseline.json`, `registry-baseline.approval.json` | `update:registry-baseline` (`REGISTRY_BASELINE_OWNER`·`_REASON` 필수). 기준선을 새로 찍지 않고 breaking 변경을 유지하려면 `config/contracts/registry-change-evidence.json`에 항목을 추가(`changeId`, 그 변경 뒤 값 `after`(삭제는 생략, 값은 JSON 그대로이고 키·원시값 배열 순서는 상관없다), `versionBump`·`migration`·`compatibilityWindow`·`rollback`·`owner`). 같은 칸을 다시 바꾸면 `after`가 달라 새 항목이 필요하다. 지금 diff의 breaking 변경과 changeId가 맞지 않는 항목이 있으면 게이트가 그 항목을 나열하며 실패한다. `update:registry-baseline`은 새 기준선이 설명하는 항목을 모두 지운다(지운 항목은 git 이력에 남는다) | `scripts/check-registries.ts`의 baseline 비교 |
| 커버리지 모듈 수 하한 | `config/testing/risk-coverage.json`의 `repositoryBaseline` | 직접 수정. 지운 production 모듈 수만큼 줄인다(`scripts/test-sample-removal.ts`가 같은 계산을 한다) | `scripts/lib/risk-coverage.ts` "repository module baseline" |
| 기능 끄기 설정 | `config/runtime/<profile>.json`의 `FEATURE_OVERRIDES` | 직접 수정. 지운 기능의 키를 뺀다(`scripts/test-sample-removal.ts`가 같은 일을 한다) | 없음. 남은 키는 조용히 무시된다(리뷰 09-09) |
| 기능 끄기 설정 | `config/runtime/<profile>.json`의 `FEATURE_OVERRIDES` | 직접 수정. 지운 기능의 키를 뺀다(`scripts/test-sample-removal.ts`가 같은 일을 한다) | 실패하는 검사는 없다. 남은 키는 아무것도 끄지 않고, `check:release-admission`(FE-GATE-027)이 `release admission warning: FEATURE_OVERRIDES.<id> … the override does nothing`을, 부팅이 진단 `feature.override.unknown`(warn)을 남긴다(리뷰 09-09) |
| 의존성 목록 | `config/security/dependency-baseline.json`, `dependency-baseline.approval.json` | `update:dependency-baseline` (`DEPENDENCY_BASELINE_OWNER`·`_REASON` 필수) | `scripts/generate-supply-chain.ts` |
Contract loading validates every registered command entry against the
@@ -132,7 +132,9 @@ DOCUMENTATION_READY (off-chain)
- 입구 문서가 실제 `src` 최상위 폴더와 `.dependency-cruiser.json` 규칙 이름을
적는지
- `docs/README.md` 1절의 현재 계약 문서에 적힌 repo 경로·링크·package script·
FE-GATE ID가 실제로 있는지
FE-GATE ID가 실제로 있는지. 짝 백엔드 경로는 옆 checkout의 작업 트리가 아니라
`config/contracts/backend-contract-pin.json`이 고정한 커밋에서 찾고, 그 커밋을
읽을 수 없으면 확인하지 못한 것으로 남긴다
- 2026-07-18 diagram 리뷰 기록의 두 사본(`docs/architecture/review-ledger.json`,
`review-evidence.md`)이 같은 해시·점수를 담는지. 원본 diagram은 repo 밖에
있으므로 이 항목은 구조가 바뀌어도 통과한다
@@ -419,9 +421,14 @@ the paired backend: `{ "id": "PRODUCT-GATE-001", "name": "backend-contract",
`FE-GATE-NNN` ids, their commands, artifacts and readiness formula stay the
template's. Each runs as `corepack pnpm <script>` in the `product_merge_gate`
job, on the same condition as `merge_gate`, without browsers and without the
gate log and evidence artifacts of `ci:gate`. Make that job a required check
of the branch where it has to block a merge. `check:ci` refuses a script that
`package.json` does not define and counts these scripts as gated.
gate log and evidence artifacts of `ci:gate`. `release_gate` waits for that job
as it waits for `merge_gate`, so a failing product gate also stops the release
build, promotion and deployment of the same run (1105/13-02); with no product
gates the workflow is the template's own. A required check of the branch is
what blocks a pull request merge, so make the job one where it has to. `check:ci`
refuses a script that `package.json` does not define, and a workflow whose
`release_gate` does not wait for the product job, and counts these scripts as
gated.
The slot as stored in `config/ci/gates.json` still follows the same contract
rules. The contract allows the steps `checkout`, `setup-node`,
+46 -7
View File
@@ -3,7 +3,7 @@
Performance evidence is deliberately split by measurement context:
- `bundle.json` records production build output and enforces initial JavaScript
at 200 KiB gzip, the number of initial JavaScript files (`initialJsFiles`),
at 202 KiB gzip, the number of initial JavaScript files (`initialJsFiles`),
and every lazy chunk at 120 KiB gzip. A failure names each exceeded limit,
the measured value and the excess (1103/15-03).
- `lab.json` records Chromium/runner/viewport/network/CPU/cache/build context and
@@ -20,8 +20,9 @@ Performance evidence is deliberately split by measurement context:
보고 예산을 정한다.
기준선 숫자는 이 문서에 적지 않는다. 손으로 적은 숫자는 두 번 낡았다. 기록은
config/scale/feature-shape-ceilings.json의 `initialJavascript` 한 곳이다. 이 파일과 아래
측정 테스트는 참조 기능을 복사해 재므로 샘플과 함께 지워진다. 그래서 경로를 백틱 없이 적는다.
`config/scale/feature-shape-ceilings.json`의 `initialJavascript` 한 곳이다. 이 파일과 아래
측정 테스트는 참조 기능을 복사해 재므로 샘플과 함께 지워진다. 문서 검사는 샘플을 지운 사본에서
이 경로들을 요구하지 않는다(`scripts/lib/removable-template-features.ts`).
| 칸 | 뜻 |
|---|---|
@@ -29,13 +30,27 @@ config/scale/feature-shape-ceilings.json의 `initialJavascript` 한 곳이다.
| `perFeatureGzipBytes` | 있는 context에 참조 기능 모양 기능을 하나 더할 때 느는 초기 JS. 상한 1 KiB |
| `perContextGzipBytes` | 새 context를 하나 더할 때 느는 초기 JS. 상한 512 B |
- tests/unit/feature-shape-growth.test.ts(unit, merge 단계)가 매번 빌드해 이
값을 재고, 상한을 넘거나 기록과 다르면(합계 1% 초과, 파일 수 불일치, 기능·
- `tests/unit/feature-shape-growth.test.ts`(unit, merge 단계)가 매번 빌드해 이
값을 재고, 상한을 넘거나 기록과 다르면(합계 256 B 초과, 파일 수 불일치, 기능·
context 비용 10% 초과) 실패한다. 실패 메시지에 잰 값이 나온다.
- 기록을 고칠 때는 `node scripts/scale/measure-feature-shape-growth.ts
--initial-baseline --write`를 돌리고 같은 변경에 넣는다.
- 합계의 허용 오차는 바이트로 둔다(1105/15-02). build id만 달라도 합계가
수십 B 움직이므로 0으로 둘 수 없다. 예전 1%(약 2 KB)는 남은 여유와 기능
하나보다 커서, 여유를 다 쓴 변경이 기록을 고치지 않고 지나갈 수 있었다.
- 기록을 고칠 때는
`node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`를
돌리고 같은 변경에 넣는다.
- 여유는 예산에서 `gzipBytes`를 뺀 값이다. 그것을 `perFeatureGzipBytes`로 나누면
더 넣을 수 있는 기능 수다. 새 context마다 `perContextGzipBytes`가 더 든다.
- 예산 값 `initialJsGzipBytes`는 206,848 B(202 KiB)다. 1105 수정 라운드에서
204,800 B를 올렸다(2026-11-06). 그 라운드의 검사·진단 코드(조립 때 code 검사
1105/03-01, 홈 시작 링크 08-03, scope closer 진단 02-01 등)가 초기 JS를
1,184 B 늘려, 생성 기능 둘을 더하는 FE-GATE-020 드릴이 예산을 663 B
넘었다(그 라운드를 합친 빌드에서 잼, 기록 커밋 `0fee3fe`). 버린 대안은 런타임
검사를 빌드 시점으로 옮겨 줄이기다.
라운드 중간의 설계 변경이라 다음 라운드 숫자를 흐린다. 다시 볼 때: 예산을 또
넘을 때, 또는 1103/13-03(zod 갱신, 약 7 KB)을 정할 때. 그때 03-01·02-01의
런타임 검사를 빌드 시점으로 옮기는 것부터 본다. 이 상향은 13-03을 정하지
않는다. 결정 기록은 `docs/reviews/2026-11-05-maturity-review/README.md` 16절이다.
- 기능 실행부(`feature-runtime.ts`)는 라우트에 들어갈 때 받는 lazy chunk다.
lazy chunk 예산은 파일마다 120 KiB(`lazyChunkGzipBytes`)다.
@@ -87,7 +102,31 @@ lab 측정(`scripts/test-performance.ts`, FE-GATE-026)은 local 프로필 build
대상 heading이 DOM에 들어온 시각까지다. Playwright 왕복 시간은 들어가지 않고,
lazy chunk 다운로드(200 KB/s 제한)는 들어간다. 클릭의 Event Timing entry
길이(INP의 입력값)는 `context.sampling.clickEventDurationMs`에 따로 남는다.
- 클릭으로 들어간 화면의 CLS는 대상 화면이 채워지며 내는 shift를 보지 못한다.
클릭 뒤 500 ms 안의 shift는 정의상 입력이 낸 것(`hadRecentInput`)이라 빠진다.
그래서 run마다 대상 라우트를 새 context에서 직접 열고, heading 뒤 network
idle까지의 CLS를 `metrics.targetDeepLinkCls`(중앙값)와
`context.sampling.targetDeepLink`에 남긴다. 예산은 `cls`와 같다(1105/15-01).
- 대상 화면(플랫폼 구성)은 기능 코드를 받지 않으므로 기능이 늘어도 수치가
거의 그대로다. 그래서 run마다 설치된 기능이 가진 첫 공개 내비게이션
라우트(`labFeatureRoute`, 템플릿에서는 `EXAMPLES_UI`)를 같은 시계로 따로 잰다
(`metrics.featureRouteInteractionMs`, `context.sampling.featureRoute`,
1105/15-04). 그런 라우트가 없으면 `measured: false`로 남기고 판정하지 않는다.
- 예산 `lab.featureRouteInteractionMs`는 500 ms다. 근거: `8a44226`에서 lab
조건으로 `EXAMPLES_UI`를 5회 재니 중앙값 406 ms(403~410)였다. 그 진입은 요청
두 묶음이다(context 라우트 모듈과 기능 실행부, 그다음 페이지 청크와 공유
청크). 둘째 묶음이 약 100 ms(클릭 뒤 98~204 ms)다. 500 ms는 지금 진입을
통과시키고, 같은 크기의 묶음이 하나 더 붙으면 넘는다.
- 두 묶음을 하나로 줄이지는 않았다. 페이지 청크의 이름은 context 라우트
모듈 안의 `lazy()`에만 있어서, 첫 묶음에 같이 받으려면 라우트 선언(초기
청크)이 페이지 로더를 가져야 한다. 선언 모양과 초기 JS를 바꾸는 일이라 따로
정한다.
- CPU 모델, 논리 CPU 수, 측정 전후 loadavg를 `context.runner`에 남긴다.
- Chromium은 스크롤바를 보이게 띄운다(`--hide-scrollbars` 제외, 1105/15-05).
Playwright 기본값은 스크롤바를 숨겨서, 첫 화면에 세로 스크롤바가 생기며
header가 밀리는 shift를 lab이 보지 못했다. 화면 쪽은 `:root`의
`scrollbar-gutter: stable`이 그 자리를 처음부터 잡는다. 다른 Playwright 게이트
(시각 골든 포함)는 여전히 스크롤바를 숨긴다.
- preview 서버는 자기 프로세스 그룹으로 띄우고 끝날 때 그룹 전체를 멈춘다.
`corepack`에만 신호를 보내던 때는 vite가 포트를 계속 잡고 있었다.
@@ -78,6 +78,12 @@ release has under `assets/` (`.css`, `.js`, `.woff2` and the rest of
exactly that type (`hashedAsset.css` and so on). The worker's install refuses
the whole release when one precached asset has another type, while a page
still uses a font served as `application/octet-stream` (review 1103/06-03).
The install fetch also refuses any redirect, so an asset the host answers only
after a redirect fails even when the final answer is a correct 200 (review
1105/06-02). This asset check runs for a build without a worker too: under
`nosniff` a script or style of another type breaks the page anyway, and a later
release that turns the worker on then needs no new hosting check. A font or
image of another type fails it although a worker-free page still loads it.
The served `release-manifest.json` must name the `buildId` and `releaseId` of
the release being checked: correct headers on an earlier release are not
@@ -505,3 +505,192 @@ CLAUDE.md 목록, local env(CI 값 없음):
| [15-03](15-performance.md) | Low·P3 | 구조적 위험 | 측정용 빌드 입력 목록이 두 파일에 같은 내용으로 있다 | 9, 23, 3, 10 | `scripts/scale/measure-feature-shape-growth.ts:40-49`, `tests/unit/product-feature-selection-build.test.ts:22-31` | |
| [15-05](15-performance.md) | Low·P3 | 확인된 결함 | 홈 첫 렌더가 세로 스크롤바를 만들어 header를 15 px 민다(CLS 0.0002). 게이트는 스크롤바를 숨긴 Chromium이라 못 본다 | 14, 10, 21 | `src/presentation/styles/theme/base.css:1-71`, `scripts/test-performance.ts:186` | |
| [16-02](16-structure-patterns.md) | Low·P3 | 구조적 위험 | 쓰기 slice가 백엔드 생성기 템플릿의 사실 넷을 손으로 옮겼고, pin·drift 검사는 `http-contract.md`만 본다 | 17, 9, 21, 23 | `scripts/create-feature-write-slice.ts:58-59, 83-84`, `config/contracts/backend-contract-pin.json:6-7`, `scripts/check-backend-contract-drift.ts:60` | |
## 16. 조치 (2026-11-05~06)
메인 세션이 지시한 수정 라운드다. 이 세션이 수정·통합·문서를 맡았고, push·PR·Slack은 메인 세션이 맡았다. 12-03은 매뉴얼 세션이 맡았다.
### 16.1 방법
- PR A(`fix/maturity-review-2026-11-05`, 기준 main `409d72e`): 이 리뷰 기록과 P1 셋(09-01, 12-01, 13-01). 끝 `a793b83`, PR #5.
- PR B(`fix/maturity-review-2026-11-05-b`, PR A 끝 `a793b83` 위): 나머지 새 발견 45건과 1103 이월 22건(13절의 "일부"). 영역별 수정 에이전트 10개가 각자 worktree의 `fix/r1105-<영역>` 브랜치에서 고쳤다. 오케스트레이터가 그 브랜치를 `--no-ff`로 합쳤다.
- 공통 지시:
- RED 먼저, 발견 하나에 커밋 하나.
- 커밋 규칙(`design-docs/conventions/commit-and-pr.md`)을 따르고 AI 꼬리말을 넣지 않는다.
- 검사를 약하게 하지 않는다. 백엔드 repo는 읽기만 한다.
- 실행 방법:
- desktop 한 checkout에서 공유 잠금(`/tmp/claude-gates/heavy.lock`)을 잡고 항목을 하나씩 돌렸다.
- 항목마다 그 ref를 detached로 checkout하고, 끝나면 원래 브랜치로 되돌렸다.
- RED는 그 커밋의 테스트 파일을 부모의 비테스트 파일 위에 올려 돌린 것이다. 변이는 항목마다 patch·script로 적용했다.
- 결과:
- 커밋 단위 항목 133개(실패 기대 71, 통과 기대 62)가 요청 파일의 기대와 모두 맞았다.
- 실패는 요청이 이름 댄 테스트에서, 요청이 말한 이유로 났다.
- 02-04의 `INTEGRITY_FAILED` 제거 변이는 동등 변이라 살아남는 것이 기대였다.
### 16.2 결정
7절의 D1~D6과 이 라운드에서 새로 생긴 D7이다.
| 번호 | 고른 것 | 이유 | 버린 대안 | 재검토 조건 |
|---|---|---|---|---|
| D1~D3 | 결정 대기로 남긴다(1103/13-03, 09-04, 03-07) | 메인 세션 지시 | — | 각 발견의 남은 것(16.5절) |
| D4 | (가) 러너 요구에 비특권 user namespace를 적고, 사전 점검이 `bwrap --unshare-net`을 실제로 돌린다(PR A `9655958`, 기준선 `67082cc`) | 메인 세션 지시. 러너 요구는 요구 목록·gate 정의·workflow 주석 셋에 적는다 | (나) 샌드박스 방식 변경 | 러너가 namespace를 허용하지 않게 바뀔 때 |
| D5 | 제품 gate를 release `needs`에 묶는다(`92d5019`) | 제품 merge 검사가 실패한 run에서 release를 멈춘다 | 문서로 제한 명시 | — |
| D6 | 실행별 출력 디렉터리 + 빈 포트(`ddbda4d`, `f4d5761`, `0e72c0c`, `510e2bb`) | 메인 세션 지시와 완료 기준(한 checkout 두 e2e 동시 실행) | "한 checkout 한 실행"을 문서로 명시 | 게이트·증거 검사도 run ID를 읽게 할 때 |
| D7 | 초기 JS 예산 `initialJsGzipBytes`를 204,800 → 206,848 B(202 KiB)로 올린다(`287dc6f`). 메인 세션 결정, 2026-11-06 | 아래 「D7 근거」 | 줄이기. 리뷰 라운드 중간의 설계 변경이라 다음 라운드 숫자를 흐린다. 청크를 합치는 것만으로는 663 B를 채우지 못한다 | 예산을 다시 넘을 때, 또는 1103/13-03(zod 갱신, 약 7 KB)을 정할 때. 그때 03-01·02-01의 런타임 검사를 빌드 시점으로 옮기는 것부터 본다. 이 상향은 13-03을 정하지 않는다 |
D7 근거:
- 확인한 사실:
- PR B를 합친 빌드의 초기 JS는 204,111 B, 초기 파일은 27개다. PR A 끝은 202,927 B, 26개였다.
- FE-GATE-020의 생성 기능 드릴은 기능 둘을 더한다. 그 상태에서 205,463 B가 되어 check:bundle이 663 B 넘었다(`0fee3fe`).
- 측정은 desktop에서 2026-11-06에 했다. 커밋과 합친 커밋마다 `--initial-baseline`으로 쟀다.
- 늘어난 곳(합 1,184 B):
- 03-01 `5c0b37e` +327 B: 조립 때 `refusedBeforeWrite` code 검사.
- 08-03 `f849d78` +293 B, 초기 파일 +1: `navigation-policy` 공유 청크.
- 02-01 `f738348` +251 B: scope closer 진단.
- 계약·앱 코어 브랜치를 합칠 때 +148 B.
- 나머지 +165 B.
- 추론(재지 않음): 08-03 청크를 기존 청크 그룹에 넣으면 약 240 B가 돌아온다.
- 올린 뒤 여유:
- 템플릿 그대로일 때 2,737 B. 기능 하나가 768 B라 기능 셋이 들어간다.
- 드릴이 기능 둘을 더한 뒤 1,385 B.
- 기록 대조 허용치 256 B(15-02)는 두 여유보다 작다.
### 16.3 통합에서 생긴 것
브랜치마다 따로는 통과했지만, 합친 트리에서만 실패한 것이다.
- 브랜치 안의 결함은 해당 발견의 커밋에 접어 넣었다(fixup).
- 합칠 때만 생기는 어긋남은 합친 커밋 안에서 고치고, 그 본문에 적었다.
| 위치 | 내용 |
|---|---|
| `45c9c4d`(합친 커밋) | 03-02는 503 `RATE_LIMIT_*` 둘을 답 표에 옮겼다. 07-01은 같은 code를 pin의 `notCopied`에 두었다. `notCopied`를 비우고, 계약 문서 4.1절 두 문장을 고쳤다 |
| `b8d53c9`(합친 커밋) | 12-04는 `vite.config.ts`에 `scripts/lib/run-isolation.ts` import를 더했다. 15-03은 임시 루트 빌드의 입력 목록을 `scripts/lib/vite-build-inputs.ts`로 모았다. 모은 목록에 그 파일을 더했다 |
| `f4d5761`(12-04에 접음) | 같은 import 때문에 실행 격리 브랜치만으로도 임시 루트 빌드 두 곳이 실패했다. 두 목록에 그 파일을 더했다 |
| `dc7c95b`(05-01에 접음) | 레시피가 `AUTH_REDIRECT_TRANSACTION`의 유일한 사용처다. 그래서 `src`만 복사해 check:registries를 돌리는 테스트가 orphan으로 실패했다. 레시피는 제품이 지울 수 있다(test:optional-recipe-removal). 그래서 consumer 폴더를 넓히지 않고, 이 행을 `AUTH_TOKEN`처럼 FE-REG-STORAGE의 `orphanExemptRows`에 넣었다 |
| `5c0b37e`(03-01), `6d084cf`(16-01)에 접음 | 새 테스트 둘이 계약 문서와 매뉴얼을 읽는다. 문서를 복사하지 않는 기능 제거 드릴 셋(FE-GATE-020의 optional-recipe·browser-file-storage·realtime)이 ENOENT로 실패했다. `scripts/lib/removal-fixture.ts`의 문서 테스트 목록에 두 파일을 더했다. `b8d53c9`과 문서 브랜치는 같은 목록에 한 줄씩 더한 것을 모두 둔다 |
| `f4d5761`, `0e72c0c`(12-04에 접음) | `playwright-run-isolation.test.ts`가 capability 설정을 import했다. 그 설정은 test:browser-file-storage-removal이 지운다. 그래서 타입 검사와 테스트, 그 사본을 타입 검사하는 `product-extension-typecheck.test.ts`가 실패했다. 그 설정은 파일이 있을 때만 읽고, 경로를 변수로 둔다 |
| `e025529`(1105/11-01에 접음) | 새 fixture 콜백 이름 `use`가 `react-hooks/rules-of-hooks` lint에 걸렸다. 다른 spec처럼 `provide`로 바꿨다 |
| `e02f252`(15-05에 접음) | `scrollbar-gutter: stable`은 `--hide-scrollbars` Chromium에서도 자리를 잡는다. 그래서 시각 골든 5장이 모두 바뀌었다(내용 폭 1040 → 1025 px, compact는 줄바꿈이 늘어 1297 → 1377 px). desktop에서 다시 찍었다. compact 골든은 overlay 스크롤바를 쓰는 실제 휴대폰보다 15 px 좁다 |
| `c9aa73f`(15-03에 접음) | 참조 기능을 지운 사본(FE-GATE-020)에서는 측정 스크립트가 없다. 그래서 `vite-build-inputs.test.ts`가 ENOENT로 실패했다. 이제 있는 소비자만 본다. 템플릿에서 그 파일이 없어지면 `feature-shape-growth.test.ts`가 import에서 실패한다 |
| `0fee3fe` | 합친 빌드의 초기 JS가 기록과 1,184 B, 파일 하나 달랐다. 브랜치마다는 허용치 안이었다. 측정 스크립트 `--initial-baseline --write`로 다시 적었다 |
| `287dc6f` | D7. 예산을 올렸다 |
### 16.4 새 발견 상태 (48건)
- 고침: 완료 기준까지 확인했다.
- 일부: 남은 부분을 적었다.
- 결정 대기·백엔드로 넘김: 이 repo 안에서 정할 수 없다. 고르는 사람이나 백엔드에 할 요청을 적었다.
- 해시는 PR B 끝에서 닿는 커밋이다.
| ID | 상태 | 커밋 | 남은 것 |
|---|---|---|---|
| 09-01 | 고침(PR A) | `397664e` | — |
| 12-01 | 고침(PR A) | `9655958`, 기준선 `67082cc` | gate 모양 digest가 FE-GATE-013의 `hostRequirements`도 본다(기준선을 한 번 다시 기록) |
| 13-01 | 고침(PR A) | `629c713` | — |
| 01-01 | 고침 | `6608fef` | 실제 백엔드 업로드는 돌리지 않았다 |
| 01-02 | 고침 · 백엔드로 넘김 | `471b001` | 504 `TRANSFER_TIMEOUT`은 작업이 시작된 뒤에도 retryable로 온다. 백엔드가 `ambiguous` 표시를 주거나, 504가 "READY 없음"을 보장해야 한다. `POST /v1/files`는 `Idempotency-Key`를 읽지 않는다 |
| 01-03 | 고침 | `8b92f45` | — |
| 01-04 | 고침 | `f2f7dc4` | — |
| 02-01 | 고침 | `f738348` | — |
| 02-02 | 고침 | `8e9fb1f` | — |
| 02-03 | 고침 | `d31c7d6` | — |
| 02-04 | 고침 | `56c0bd0` | `INTEGRITY_FAILED` 제거는 동등 변이다(커밋 본문) |
| 03-01 | 고침 | `5c0b37e` | BREAKING |
| 03-02 | 고침 · 백엔드로 넘김 | `c6c37f3` | `RateLimitInterceptor`가 비동기 재디스패치에서도 평가되면, 503이 쓰기 뒤에도 나올 수 있다. `DispatcherType.REQUEST`에서만 평가하도록 요청한다 |
| 04-01 | 고침 | `bde7fa4` | — |
| 04-02 | 고침 | `05330e3`, `1e576ef` | BREAKING |
| 04-03 | 고침 | `05880d1` | — |
| 05-01 | 고침 | `dc7c95b` | — |
| 06-01 | 고침 | `1c7c614` | — |
| 06-02 | 일부 | `4d6f254` | 결정 대기: 워커 없는 빌드에서 probe를 script·style만 보게 좁힐지. 지금은 글꼴·이미지도 FAIL이다 |
| 06-03 | 고침 | `aaa782b` | — |
| 07-01 | 고침 | `daf3474` | 사본이 백엔드 문서와 같은지는 게이트 밖의 `check:backend-contract-drift`만 본다 |
| 07-02 | 고침 | `3b62ccd` | — |
| 08-01 | 고침 | `4f3c10b` | — |
| 08-02 | 고침 | `90c489c` | — |
| 08-03 | 고침 | `f849d78` | 초기 파일이 하나 늘었다(16.2절 D7) |
| 08-04 | 고침 | `f2b8ba7` | — |
| 09-02 | 고침 | `0007699` | 쿠키 handler를 잇지 않은 제품을 막는 검사는 없다. 실제 Keycloak·Redis에 붙여 보지 않았다 |
| 09-03 | 고침 | `bfd9d50` | — |
| 10-01 | 고침 | `00b12b3` | — |
| 10-02 | 고침 | `dae44f5` | — |
| 10-03 | 제안으로 남김 | — | 변이 도구(Stryker) 도입은 제안이다 |
| 11-01 | 고침 | `e025529` | — |
| 12-02 | 고침 | `fc95672` | — |
| 12-03 | 매뉴얼 PR에 포함 | `e9d9c36`(`claude/mystifying-carson-f61c35`) | PR B에는 없다 |
| 12-04 | 고침 | `ddbda4d`, `f4d5761`, `0e72c0c`, `510e2bb` | 완료 기준을 확인했다. 한 checkout에서 e2e 두 실행을 함께 돌려 둘 다 통과했다(부분 spec 10건, 전체 202건씩). 포트와 출력 폴더는 실행마다 달랐다. 남은 한계는 아래 셋이다. 게이트와 증거 검사는 기본 경로만 읽는다. 선택이 다른 두 실행은 `src/.generated`를 서로 바꾼다. Storybook 캐시는 공유한다 |
| 13-02 | 고침 | `92d5019` | — |
| 14-01 | 일부 | `50b631e`, `332bfee` | 문서 검사는 고쳤다. 예제 기능 제거 드릴을 돌리는 게이트는 없다. 문서 쪽은 `test:unit` 사본 테스트가 본다 |
| 14-02 | 고침 | `e6b2a4f` | — |
| 14-03 | 고침 | `50b631e`, `1dda18d` | — |
| 15-01 | 고침 | `138c195` | — |
| 15-02 | 고침 | `46359a1` | 합친 뒤 기록을 다시 적고(`0fee3fe`) 예산을 올렸다(`287dc6f`, D7) |
| 15-03 | 고침 | `c9aa73f` | — |
| 15-04 | 일부 | `81701ad` | lab이 기능 라우트를 500 ms 예산으로 잰다. 결정 대기: 진입 요청 두 묶음을 하나로 줄이려면, 초기 청크의 라우트 선언이 페이지 로더를 가져야 한다 |
| 15-05 | 고침 | `e02f252` | 골든을 다시 찍었다(16.3절) |
| 16-01 | 일부 | `6d084cf` | 충돌 처리 명령을 매뉴얼에 적었다. 결정 대기: dev manifest를 생성 파일로 둘지, 초기 JS 기록에서 제품 기능을 뺄지 |
| 16-02 | 고침 | `f600e6b` | drift 검사는 게이트 밖이다 |
| 16-03 | 결정 대기 | — | FE-GATE-009 job에 생성 기능을 설치한 상태의 브라우저 검사를 더할지 정해야 한다. 더하려면 gates.json과 CI 기준선을 다시 기록하고, fixture 포트를 설계해야 한다. 고르는 사람: 템플릿 담당 |
| 16-04 | 고침 | `b45d6a0` | — |
### 16.5 1103 이월 상태 (22건, 13절의 "일부")
| ID | 상태 | 커밋 | 남은 것 |
|---|---|---|---|
| 1103/01-01 | 일부 · 백엔드로 넘김 | `6608fef` | 백엔드 매뉴얼의 짝 경로 안내, `docs/fileserver/http-contract.md`의 202 state 목록. 실제 업로드는 돌리지 않았다 |
| 1103/03-01 | 일부 | `12d97d7` | 결정 대기: KEYED 결과 불명의 같은 키 재전송이 500 `IDEMPOTENCY_RECOVERY_REQUIRED`를 받아도 재전송 버튼이 남는다. 고르는 사람: 프론트 템플릿 담당 |
| 1103/03-02 | 결정 대기 | — | bulk `results`를 지원할지 |
| 1103/03-07 | 결정 대기 | — | 백엔드 생성기의 목록 GET(지시대로 남김) |
| 1103/05-01 | 고침 | `23662fb` | — |
| 1103/07-04 | 고침 | `2e1acb1` | — |
| 1103/09-03 | 백엔드로 넘김 | — | 실제 Keycloak·Redis 연동은 확인하지 못했다. 백엔드 realm에 public client가 없다. 쿠키 recipe의 401 연결은 1105/09-02가 고쳤다 |
| 1103/09-04 | 결정 대기 | — | `EXAMPLES_PLATFORM` 처리(지시대로 남김) |
| 1103/09-05 | 일부 | `fdc1db9` | SW 활성화 화면(`onUpdateWaiting`·`requestActivation()`)과 reload 안내를 이을 제품 소유 자리가 없다 |
| 1103/11-01 | 고침 | `757d1c7` | BREAKING(`a11y.json` schema 2) |
| 1103/11-02 | 실행 환경 대기 | — | 코드 빈틈은 없다. 글꼴이 없는 깨끗한 러너에서 FE-GATE-008 완료 기준을 돌려야 한다 |
| 1103/11-03 | 실행 환경 대기 | — | user namespace를 허용하는 호스트에서 `test:system` 완료 기준을 돌려야 한다(12-01) |
| 1103/11-04 | 실행 환경 대기 | — | 11-03과 같다 |
| 1103/12-05 | 일부 | `e72fb6e` | 결정 대기: 1절 밖 문서(목표 설계)의 경로 검사. 문서별 예외 방식부터 정해야 한다 |
| 1103/13-03 | 결정 대기 | — | 운영 high advisory 2건(7절 D1, 지시대로 남김). D7은 이 결정을 하지 않는다 |
| 1103/14-01 | 고침 | `832774f` | — |
| 1103/14-02 | 일부 | `f4be426` | "옮기기 전" 목록은 문서만 고쳤다. 결정 대기: 제품 소유 자리가 없는 템플릿 파일을 템플릿에 들일지 |
| 1103/15-02 | 고침 | `832774f` | — |
| 1103/16-01 | 고침 | `56272e8` | BREAKING(`responseEnvelope` 필수) |
| 1103/16-05 | 고침 | `48c1ab7` | BREAKING |
| 1103/16-06 | 결정 대기 | — | 라우트 계약 `title`·`navigationLabel`을 지울지, catalog와 같게 강제할지. 둘 다 기준선과 승인 digest를 다시 적어야 한다 |
| 0929/03-03 | 고침 | `683ccfb` | — |
### 16.6 그 밖의 이월 (영역 문서 2절 "남음")
- 고침: 1101/02-04 `11a0fd0`, 0929/10-04 `c842bac`, 0929/10-05 `7ead8d3`, 1101/10-07 `ce191be`, 0929/12-03 `a37ebba`, 1101/14-02 `b834b8d`, 0929/14-05 `1c4e57c`.
- 일부:
- 1103/04-01 `27e3dec`: 조합 코드가 다른 descriptor를 넘기면 attempt마다 요청이 최대 3번이다.
- 0929/02-02 `f2a4f32`: inspect의 `signal`·판정 불가 칸은 결정 대기다.
- 0929/14-01 `1ac336a`, 0929/14-02 `57e3586`, 0929/14-03 `f4be426`: 문서만 고쳤고 명령은 실행하지 않았다.
- 결정 대기:
- 1101/02-02, 0929/02-06, 0929/04-02, 0929/04-03, 0929/14-06, 1101/14-07.
- 1101/10-05·10-06: 파일 51개를 옮기고 gates.json과 드릴 구조를 바꿔야 한다.
- 1101/10-08: 여러 integration 테스트에 걸친 정리라, 통합 뒤 따로 한다.
- 0929/12-07: owner 값을 `frontend-platform`과 `DongHyeonka` 중 무엇으로 할지.
- 남김(작지 않음):
- 0929/12-01: fanout 휴리스틱을 다시 설계해야 한다.
- 0929/12-04: 기준선 schema에 칸을 더하고, 다운스트림이 기준선을 다시 기록해야 한다.
- 0929/12-05: `pnpm remove`, lockfile, 의존성 기준선을 다시 승인해야 한다.
- 0929/12-06: Vitest와 Playwright를 구분하는 API가 필요하다. 지금 해당 사례는 0건이다.
- 1101/12-03: 디자인 규칙 범위를 넓히면 오탐 위험이 크다.
- 1101/15-01·15-03·15-04, 0929/11-04, 1101/16-05·16-06: 예산과 구조를 먼저 결정해야 한다.
### 16.7 확인
- 커밋 단위: 16.1절의 133개 항목.
- PR B 끝에서 돌린 것:
- FE-GATE-020과 FE-GATE-012(CI env).
- 빠른 검사 10개: check:types, lint, check:architecture, check:ci, check:registries, check:diagnostics, check:adapter-inventory, check:design-system, check:i18n, check:test-evidence.
- test:unit·component·integration·contract·runtime-schema, test:visual.
- 옆 백엔드 checkout 없는 verify:documentation, CHANGELOG 테스트 셋.
- 돌리지 않은 것:
- merge 단계 14개 전부(`ci:gate`). 메인 세션이 PR B 끝에서 돌린다.
- CI 러너에서는 아무것도 돌리지 않았다.
@@ -149,7 +149,9 @@ page error, 실패한 request, 끝까지 실행되지 않은 preload를 test 실
WebKit의 "preload했지만 몇 초 안에 쓰지 않았다" 경고는 load 3초 뒤 한 번 하는
추정이라 그 문구만 무시하고, 대신 preload된 build script가 실제로 실행됐는지를
세 엔진에서 같은 방법으로 검사한다(`tests/support/browser/preload-use.ts`,
1103/11-09). 시간은 각 test가
1103/11-09). 이 검사와 fixture가 그 기록으로 test를 실패시키는지는
`tests/e2e/preload-use.spec.ts`가 증명한다. fixture의 마지막 판정
(`browserFailureVerdict`)을 바꾸는 곳은 그 spec 하나다(1105/11-01). 시간은 각 test가
`vi.useFakeTimers()`로 통제하고, 전역 `afterEach`가 실제 timer로 되돌린다
(`tests/setup.ts`). 공용 clock/random/scheduler helper는 두지 않는다.
@@ -766,8 +768,10 @@ tests/factories/
| `server-terminal-503` | 503. 조회는 retry 2회 뒤 소진, 명령은 retry 없이 결과 불명(`MAYBE_APPLIED`) |
이 표는 `tests/mocks/scenarios/catalog.ts`의 `HTTP_SCENARIO_IDS`와 같은 순서다.
401 뒤 인증 복구 흐름은 catalog가 아니라 `tests/integration/auth-recovery.test.ts`가
다룬다.
401 뒤 세션을 복구하고 다시 보내는 흐름은 없다. V3 실행기는 401을 `UNAUTHENTICATED`로
끝내고 재전송하지 않는다(`src/adapters/http/http-execution-v3.ts`). 그 판정은
`tests/unit/http-execution-v3.test.ts`가 검사한다. 복구 흐름을 검사하던 V2의
auth-recovery 통합 테스트는 V2 클라이언트와 함께 지웠다.
### 11.3 Catalog 규칙
@@ -862,7 +866,9 @@ Storybook static artifact를 production application artifact와 합치지 않는
- Vite dev server
- 빠른 Chromium 중심 smoke
- 로컬 `reuseExistingServer`
- 떠 있는 dev server를 재사용하지 않는다. 빈 포트에 자기 dev server를 띄운다
(1105/12-04, 13.6절). 예전에는 5173에 다른 checkout의 서버가 떠 있으면
그 서버를 말없이 검사했다
- 개발 중 route와 form 확인
#### Release 검증
@@ -873,7 +879,7 @@ pnpm build
-> Playwright release config
```
- CI에서 기존 server 재사용 금지
- 로컬과 CI 모두 기존 server 재사용 금지
- production `dist`
- 실제 runtime config/release manifest
- base path와 hashed chunks
@@ -987,6 +993,72 @@ Chromatic 같은 cloud visual service는 선택이다. 저장소 내부 Playwrig
CI retry를 허용하는 경우 첫 실패 trace도 폐기하지 않는다. retry 후 통과한 test는
flaky signal로 집계한다.
### 13.6 한 checkout에서 두 실행 (1105/12-04)
핵심: Playwright 실행마다 `TEST_RUN_ID`를 다르게 주면, 한 checkout에서 두
실행이 동시에 돈다. 서버 포트는 run ID가 없어도 늘 빈 포트를 고른다.
예전에는 두 번째 실행이 둘 중 하나로 깨졌다.
- 고정 포트(e2e 4173 등) 때문에 `http://127.0.0.1:4173 is already used`로
시작하지 못했다.
- 시작하더라도 빌드가 첫 실행이 서빙 중인 `dist`를 비우고, Playwright가
첫 실행의 결과 폴더를 비웠다.
```text
TEST_RUN_ID=a playwright test
-> config: 빈 포트 P를 고른다. TEST_E2E_PORT=P를 runner 환경에 쓴다
-> web server: RUN_OUTPUT_ROOT=.tmp/runs/a 로 build
-> .tmp/runs/a/dist, .tmp/runs/a/.generated/..., .tmp/runs/a/artifacts/release/...
-> vite preview --port P --strictPort --outDir .tmp/runs/a/dist
-> worker: 설정을 다시 읽고 TEST_E2E_PORT=P를 물려받아 baseURL이 같다
-> 결과·report·JUnit: .tmp/runs/a/artifacts/tests/e2e/...
```
- `.tmp/runs/<id>/` 아래 경로는 checkout 안 경로와 같다. `dist`는
`.tmp/runs/<id>/dist`, `artifacts/tests/e2e/results`는
`.tmp/runs/<id>/artifacts/tests/e2e/results`가 된다.
- run ID가 없으면 지금까지와 같은 `dist`와 `artifacts/`에 쓴다. 게이트, CI
upload, 증거 검사가 읽는 곳이다.
- `.tmp/`는 git, Tailwind 소스 스캔, Vite watcher, vitest가 모두 건너뛴다.
그래서 출력 루트는 `.` 또는 `.tmp/` 아래만 받는다.
| 변수 | 누가 읽나 | 없을 때 |
|---|---|---|
| `TEST_RUN_ID` | 다섯 Playwright 설정, `tests/e2e/preload-use.spec.ts` | `dist`, `artifacts/tests/<이름>/` |
| `RUN_OUTPUT_ROOT` | 빌드 단계 전부(`scripts/build-frontend.ts`가 부르는 것), `vite.config.ts`. 설정이 web server에만 넘긴다 | `.` |
| `TEST_E2E_PORT`, `TEST_VISUAL_PORT`, `TEST_CAPABILITIES_PORT`, `TEST_STORYBOOK_PORT`, `TEST_DEV_PORT` | 각 설정 | 빈 포트 |
- run ID는 글자·숫자·`.`·`_`·`-` 64자 이하이고 글자나 숫자로 시작한다.
- 포트 변수를 주면 그 포트를 쓴다. 디버깅할 때 고정하는 용도다.
예: `TEST_E2E_PORT=4173`.
- `RUN_OUTPUT_ROOT`는 직접 export하지 않는다. 설정이 run ID에서 만든다. 빌드
코드는 `TEST_RUN_ID`를 읽지 않는다. e2e가 저장소 복사본을 빌드할 때 그
빌드는 복사본 자기 `dist`에 써야 하기 때문이다.
- 규칙은 `scripts/lib/run-isolation.ts` 한 곳에 있다.
두 e2e 실행을 동시에 돌리는 예:
```bash
TEST_RUN_ID=a corepack pnpm exec playwright test &
TEST_RUN_ID=b corepack pnpm exec playwright test &
wait
```
한계:
- 게이트(`ci:gate`)와 증거 검사(`check:test-evidence`,
`verify:browser-capability-evidence`)는 기본 경로만 읽는다. 게이트는 run ID
없이 한 checkout에서 하나씩 돌린다. run ID를 준 채 게이트를 돌리면 증거가
기본 경로에 새로 생기지 않아 "not freshly produced"로 실패한다.
- 동시에 도는 두 실행이 같은 run ID를 쓰면 다시 부딪힌다.
- `src/.generated`는 실행마다 따로 두지 않는다. 생성기는 내용이 같으면 쓰지
않고, 다르면 rename으로 바꾼다. 그래서 같은 선택으로 도는 실행끼리는
안전하다. `PRODUCT_APP_ID`나 `VITE_PRODUCT_FEATURES`가 서로 다른 두 실행은
서로의 인덱스를 바꾼다.
- Storybook 내부 캐시(`node_modules/.cache`)는 공유한다.
- `.tmp/runs/<id>/`는 자동으로 지우지 않는다. 다 보면 직접 지운다.
## 14. Coverage 정책
Coverage 목표는 “99% 완성도”와 같은 표현을 숫자로 대신하기 위한 것이 아니다.
+6 -2
View File
@@ -18,9 +18,13 @@ Each gate is blocking in its declared scope. Failures are not downgraded with
`test:all` is the normal product-development loop. It runs, in order,
`test:runtime-schema`, `test:unit`, `test:contract`, `test:component`,
`test:integration`, test:reference-feature (removed with the reference sample), `test:platform` (`tests/platform`
`test:integration`, the rest of what `test:coverage` runs (`tests/features`,
the reference sample's tests among them, `tests/scripts` and
`tests/scale/browser-soak.contract.test.ts`), `test:platform` (`tests/platform`
and `tests/architecture`), `check:release-coherence` and `test:recipes`
(`package.json` `test:all`). It does not include `test:system`. CI-runner and
(`package.json` `test:all`). So every Vitest path the merge gate's coverage
run covers also runs here (`tests/unit/test-all-paths.test.ts`, 0929/10-05).
It does not include `test:system`. CI-runner and
supply-chain assurance has different host prerequisites and is invoked
explicitly in the assurance path.
+1 -1
View File
@@ -82,7 +82,7 @@
"check:v8-coverage-counter-semantics": "node scripts/check-v8-coverage-counter-semantics.ts",
"test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features tests/platform tests/architecture tests/release tests/scripts tests/scale/browser-soak.contract.test.ts --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts",
"check:coverage:fixture": "node scripts/check-risk-coverage.ts --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json",
"test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:contract && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature && corepack pnpm test:platform && corepack pnpm check:release-coherence && corepack pnpm test:recipes",
"test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:contract && corepack pnpm test:component && corepack pnpm test:integration && node scripts/run-vitest.ts run tests/features tests/scripts tests/scale/browser-soak.contract.test.ts --reporter=default && corepack pnpm test:platform && corepack pnpm check:release-coherence && corepack pnpm test:recipes",
"verify:lockfile": "corepack pnpm install --frozen-lockfile --ignore-scripts",
"check:frozen-lockfile:fixture": "node scripts/check-frozen-lockfile-fixture.ts",
"generate:artifact-schemas": "node scripts/generate-product-feature-index.ts && node scripts/generate-artifact-schemas.ts",
+21 -8
View File
@@ -1,29 +1,43 @@
import { defineConfig, devices } from "@playwright/test";
import { LOCAL_BUILD_IDENTITY } from "./scripts/lib/build-environment.ts";
import {
reservePort,
RUN_OUTPUT_ROOT_VARIABLE,
TEST_PORT_VARIABLES,
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
// 1105/12-04. Under TEST_RUN_ID the results and report are the run's own
// (.tmp/runs/<id>/), and so is the dev server's Vite cache. The dev server
// listens on a free port (TEST_CAPABILITIES_PORT pins one); it shared 4174
// with the visual preview. Specs read the origin from `use.baseURL`.
const port = await reservePort(TEST_PORT_VARIABLES.capabilities);
const origin = `http://127.0.0.1:${port}`;
export default defineConfig({
testDir: "./tests/browser-capabilities",
forbidOnly: true,
outputDir: "./artifacts/tests/browser-capabilities/results",
outputDir: testRunPath("artifacts/tests/browser-capabilities/results"),
reporter: [
["list"],
[
"html",
{
outputFolder: "./artifacts/tests/browser-capabilities/report",
outputFolder: testRunPath("artifacts/tests/browser-capabilities/report"),
open: "never",
},
],
[
"junit",
{
outputFile: "./artifacts/tests/browser-capabilities/results.xml",
outputFile: testRunPath("artifacts/tests/browser-capabilities/results.xml"),
},
],
],
use: {
baseURL: "http://127.0.0.1:4174",
baseURL: origin,
trace: "retain-on-failure",
screenshot: "only-on-failure",
},
@@ -32,10 +46,9 @@ export default defineConfig({
// BUILD_ID is local-build. CI sets VITE_BUILD_ID for the whole workflow;
// built into the dev bundle it makes every page a rolling-release mismatch
// that reloads once and then fails closed (CONFIG_BUILD_MISMATCH).
env: { ...LOCAL_BUILD_IDENTITY },
command:
"corepack pnpm dev --host 127.0.0.1 --port 4174",
url: "http://127.0.0.1:4174",
env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command: `corepack pnpm dev --host 127.0.0.1 --port ${port} --strictPort`,
url: origin,
reuseExistingServer: false,
},
projects: [
+26 -6
View File
@@ -1,23 +1,43 @@
import { defineConfig, devices } from "@playwright/test";
import {
reservePort,
RUN_OUTPUT_ROOT_VARIABLE,
TEST_PORT_VARIABLES,
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
// 1105/12-04. With TEST_RUN_ID set, this run's results, report and the build
// its preview serves are under .tmp/runs/<id>/ (scripts/lib/run-isolation.ts),
// so a second run in the same checkout neither empties this run's dist nor
// deletes its results. Unset, the paths are artifacts/tests/e2e/* and dist,
// which FE-GATE-008 and the CI upload read. The preview listens on a free
// port (TEST_E2E_PORT pins one); a fixed 4173 made the second run fail with
// "is already used".
const dist = testRunPath("dist");
const port = await reservePort(TEST_PORT_VARIABLES.e2e);
const origin = `http://127.0.0.1:${port}`;
export default defineConfig({
testDir: "./tests/e2e",
forbidOnly: true,
outputDir: "./artifacts/tests/e2e/results",
outputDir: testRunPath("artifacts/tests/e2e/results"),
reporter: [
["list"],
["html", { outputFolder: "./artifacts/tests/e2e/report", open: "never" }],
["junit", { outputFile: "./artifacts/tests/e2e/results.xml" }],
["html", { outputFolder: testRunPath("artifacts/tests/e2e/report"), open: "never" }],
["junit", { outputFile: testRunPath("artifacts/tests/e2e/results.xml") }],
],
use: {
baseURL: "http://127.0.0.1:4173",
baseURL: origin,
trace: "retain-on-failure",
screenshot: "only-on-failure",
},
webServer: {
env: { [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command:
"corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port 4173",
url: "http://127.0.0.1:4173",
`corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`,
url: origin,
reuseExistingServer: false,
},
projects: [
+19 -5
View File
@@ -2,21 +2,35 @@ import { defineConfig } from "@playwright/test";
import releaseConfig from "./playwright.config.ts";
import { LOCAL_BUILD_IDENTITY } from "./scripts/lib/build-environment.ts";
import {
reservePort,
RUN_OUTPUT_ROOT_VARIABLE,
TEST_PORT_VARIABLES,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
// 1105/12-04. The dev server used to reuse whatever already answered on 5173,
// so the specs could run against another checkout's or another branch's dev
// server without saying so. It now starts its own on a free port
// (TEST_DEV_PORT pins one) and never reuses a server.
const port = await reservePort(TEST_PORT_VARIABLES.dev);
const origin = `http://127.0.0.1:${port}`;
export default defineConfig({
...releaseConfig,
use: {
...releaseConfig.use,
baseURL: "http://127.0.0.1:5173",
baseURL: origin,
},
webServer: {
// The dev server serves public/config.json, the local profile, whose
// BUILD_ID is local-build. CI sets VITE_BUILD_ID for the whole workflow;
// built into the dev bundle it makes every page a rolling-release mismatch
// that reloads once and then fails closed (CONFIG_BUILD_MISMATCH).
env: { ...LOCAL_BUILD_IDENTITY },
command: "corepack pnpm dev --host 127.0.0.1",
url: "http://127.0.0.1:5173",
reuseExistingServer: true,
// 1105/12-04. Under TEST_RUN_ID, Vite's cache is the run's own.
env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command: `corepack pnpm dev --host 127.0.0.1 --port ${port} --strictPort`,
url: origin,
reuseExistingServer: false,
},
});
+27 -6
View File
@@ -1,32 +1,53 @@
import { defineConfig, devices } from "@playwright/test";
import {
reservePort,
TEST_PORT_VARIABLES,
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
// 1105/12-04. Under TEST_RUN_ID the workshop is built into the run's own
// folder (.tmp/runs/<id>/artifacts/storybook/static) with build:storybook's
// two steps and another output folder, and the results and report are the
// run's own. Unset, the gate's build:storybook writes artifacts/storybook/static.
// The static server listens on a free port (TEST_STORYBOOK_PORT pins one).
const staticDirectory = testRunPath("artifacts/storybook/static");
const port = await reservePort(TEST_PORT_VARIABLES.storybook);
const origin = `http://127.0.0.1:${port}`;
const buildWorkshop =
testRunRoot() === "."
? "corepack pnpm build:storybook"
: "node scripts/generate-product-feature-index.ts && " +
`corepack pnpm exec storybook build -o ${staticDirectory}`;
export default defineConfig({
testDir: "./tests/storybook",
forbidOnly: true,
outputDir: "./artifacts/tests/storybook/results",
outputDir: testRunPath("artifacts/tests/storybook/results"),
reporter: [
["list"],
[
"html",
{
outputFolder: "./artifacts/tests/storybook/report",
outputFolder: testRunPath("artifacts/tests/storybook/report"),
open: "never",
},
],
[
"junit",
{ outputFile: "./artifacts/tests/storybook/results.xml" },
{ outputFile: testRunPath("artifacts/tests/storybook/results.xml") },
],
],
use: {
baseURL: "http://127.0.0.1:6006",
baseURL: origin,
trace: "retain-on-failure",
screenshot: "only-on-failure",
},
webServer: {
command:
"corepack pnpm build:storybook && node scripts/serve-static.ts artifacts/storybook/static 6006",
url: "http://127.0.0.1:6006",
`${buildWorkshop} && node scripts/serve-static.ts ${staticDirectory} ${port}`,
url: origin,
reuseExistingServer: false,
},
projects: [
+22 -7
View File
@@ -3,19 +3,34 @@ import { fileURLToPath } from "node:url";
import { defineConfig, devices } from "@playwright/test";
import { LOCAL_BUILD_IDENTITY } from "./scripts/lib/build-environment.ts";
import {
reservePort,
RUN_OUTPUT_ROOT_VARIABLE,
TEST_PORT_VARIABLES,
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
// 1105/12-04. Under TEST_RUN_ID the results, report and build are the run's
// own (.tmp/runs/<id>/); the goldens in snapshotDir are shared and only read.
// The preview listens on a free port (TEST_VISUAL_PORT pins one); it shared
// 4174 with the capability dev server.
const dist = testRunPath("dist");
const port = await reservePort(TEST_PORT_VARIABLES.visual);
const origin = `http://127.0.0.1:${port}`;
export default defineConfig({
testDir: "./tests/visual",
forbidOnly: true,
snapshotDir: "./tests/visual/__snapshots__",
outputDir: "./artifacts/tests/visual/results",
outputDir: testRunPath("artifacts/tests/visual/results"),
reporter: [
["list"],
[
"html",
{ outputFolder: "./artifacts/tests/visual/report", open: "never" },
{ outputFolder: testRunPath("artifacts/tests/visual/report"), open: "never" },
],
["junit", { outputFile: "./artifacts/tests/visual/results.xml" }],
["junit", { outputFile: testRunPath("artifacts/tests/visual/results.xml") }],
],
expect: {
toHaveScreenshot: {
@@ -31,7 +46,7 @@ export default defineConfig({
},
use: {
...devices["Desktop Chrome"],
baseURL: "http://127.0.0.1:4174",
baseURL: origin,
colorScheme: "light",
locale: "en-US",
trace: "retain-on-failure",
@@ -54,10 +69,10 @@ export default defineConfig({
// CI run failed here. The goldens are the template's shape, captured with
// the local identity.
// 1103/11-08: CI too, or the build is checked as a release build.
env: { ...LOCAL_BUILD_IDENTITY },
env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command:
"corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port 4174",
url: "http://127.0.0.1:4174",
`corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`,
url: origin,
reuseExistingServer: false,
},
projects: [
@@ -20,8 +20,17 @@ export type SessionBrowserFiles = Readonly<{
*
* file-transfer is an opt-in recipe (`productionComposition: false`), so the
* template does not build this. A product that installs a feature using it
* augments `FeaturePlatformCapabilities` with `files: SessionBrowserFiles` and
* returns both halves from `src/bootstrap/product-composition.ts`:
* types the capability in `src/features/product-capabilities.ts`, as
* `docs/manual/03-outside-feature-folder.md` says:
*
* export interface ProductFeaturePlatformCapabilities {
* readonly files: SessionBrowserFiles;
* }
*
* not with a `declare module` augmentation of `FeaturePlatformCapabilities`,
* whose key `check:types:node` does not see (1105/02-03). The feature lists
* `files` in `needs`, and the product returns both halves from
* `src/bootstrap/product-composition.ts`:
*
* const browserFiles = createSessionBrowserFileCapability(() =>
* createBrowserFileRuntime({ input, policies, limits, download }),
@@ -1652,8 +1652,9 @@ type MemoryDurableObjectStoreOptions = Readonly<{
* a journal row, and a LOGOUT or ACCOUNT_DELETION the policy allows leaves the
* partition empty. `reconcile` rolls a row that stopped while PREPARING back
* and commits one that stopped after FILES_READY, like the runtime's
* roll-forward; such a purge also drops every stopped row and reports
* `partitionDeleted` (2026-11-03 05-01, 05-04).
* roll-forward; such a purge also drops every stopped row. Every purge
* reports `partitionDeleted`, never a chunk sweep (2026-11-03 05-01, 05-04,
* 1103/05-01 rest).
*
* It does not model the worker, Web Locks, the composition authority, chunk
* dedup, orphan GC or the other maintenance reasons (`UNSUPPORTED`). Its
@@ -1926,8 +1927,9 @@ export class MemoryDurableObjectStore
const removedObjects = this.#objects.size;
this.#objects.clear();
// 2026-11-03 05-01. A stopped put goes with the partition, as the
// runtime's partition delete takes its row and its files.
const partitionDeleted = this.#pending.size > 0;
// runtime's partition delete takes its row and its files. 1103/05-01
// rest: the runtime ends every purge that walked all objects in that
// delete, so this one always reports it.
this.#pending.clear();
return dataSuccess(
Object.freeze({
@@ -1936,9 +1938,7 @@ export class MemoryDurableObjectStore
releasedBytes,
moreObjectsAvailable: false,
deadlineReached: false,
...(partitionDeleted
? { partitionDeleted: true as const }
: { chunkSweep: "COMPLETED" as const }),
partitionDeleted: true as const,
}),
);
}
+29 -3
View File
@@ -2,6 +2,8 @@ import type { ExternalSessionOwner } from "../../src/adapters/auth/index.ts";
import type { CredentialPatchOutcome } from "../../src/adapters/http/index.ts";
import type { SessionState } from "../../src/application/ports/auth-session-port.ts";
import type {
ProductComposition,
ProductCompositionContext,
ProductCredentialProvider,
SessionOwnerFetch,
} from "../../src/bootstrap/product-composition-contract.ts";
@@ -31,10 +33,14 @@ import type { RestAuthProfile } from "../../src/contracts/rest-profiles.ts";
* State transitions follow `SessionState` in
* `src/application/ports/auth-session-port.ts`. The cookie is the credential
* and the server is the judge: a server 401 signs out, and nothing is
* refreshed here.
* refreshed here. That 401 reaches the session only through
* `createSessionCookieRejectionHandler` as the product's
* `onCredentialRejected` (1105/09-02): the template tells a product
* provider's 401 to the product, not to the session.
*
* Copy this file into `src/bootstrap/`, the profiles into
* `PRODUCT_REST_AUTH_PROFILES` and the providers into `credentialProviders`;
* `PRODUCT_REST_AUTH_PROFILES`, the providers into `credentialProviders` and
* the handler into `onCredentialRejected`;
* `docs/manual/04-paired-backend-session.md` shows the wiring.
*/
@@ -176,7 +182,8 @@ export function createCookieSessionOwner(
* The providers for `SESSION_COOKIE_AUTH_PROFILES`. They read the CSRF cookie
* when the request goes, since the backend may issue a new one at any answer.
* They do not ask the session state: the cookie is the proof and the server
* decides, and its 401 reaches the owner.
* decides. Its 401 reaches the owner through
* `createSessionCookieRejectionHandler`, not through these.
*/
export function createSessionCookieCredentialProviders(
options: Readonly<{
@@ -197,3 +204,22 @@ export function createSessionCookieCredentialProviders(
},
});
}
/**
* 1105/09-02. The `onCredentialRejected` that goes with these providers. The
* template tells a 401 to whoever supplied the rejected credential
* (1103/09-01), and for a SESSION_COOKIE_* request that is the product. The
* credential is still the session's own cookie, so a 401 means the server
* session ended (TTL, signed out in another tab or on the server): the
* template session hears it, signs out and fences server state. A 401 on any
* other product profile is left to that profile's provider.
*/
export function createSessionCookieRejectionHandler(
context: Pick<ProductCompositionContext, "notifySessionUnauthenticated">,
): NonNullable<ProductComposition["onCredentialRejected"]> {
return (binding) => {
if (Object.hasOwn(SESSION_COOKIE_AUTH_PROFILES, binding.authProfileId)) {
context.notifySessionUnauthenticated();
}
};
}
@@ -8,6 +8,7 @@ import type {
ProductSessionOwnerPage,
SessionOwnerFetch,
} from "../../src/bootstrap/product-composition-contract.ts";
import { STORAGE_REGISTRY } from "../../src/contracts/storage-keys.ts";
/**
* 1103/09-03. A session owner for the paired backend's JWT mode
@@ -40,8 +41,15 @@ import type {
* shows the realm client and the wiring.
*/
/** `buildPhysicalKey("auth", 1, "oidc-pkce-transaction")`; never a token. */
export const OIDC_PKCE_TRANSACTION_KEY = "ca-frontend:auth:v1:oidc-pkce-transaction";
/**
* The sessionStorage key of the sign-in transaction; never a token.
* 1105/05-01. It comes from the storage registry
* (`AUTH_REDIRECT_TRANSACTION`, `backend: "external"`), so it follows the
* app's `APP_NAMESPACE` like every other Web Storage key. It used to be a
* literal that kept `ca-frontend:` after a product renamed the namespace.
*/
export const OIDC_PKCE_TRANSACTION_KEY =
STORAGE_REGISTRY.AUTH_REDIRECT_TRANSACTION.physicalKey;
export type OidcPkceSessionOwnerOptions = Readonly<{
/** Exact issuer, e.g. `http://localhost:8081/realms/ca-skeleton`. HTTPS off this machine. */
+14 -5
View File
@@ -5,6 +5,7 @@ import process from "node:process";
import { SERVICE_WORKER_SCRIPT_PATH } from "../src/contracts/service-worker.ts";
import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtime-capabilities.ts";
import { makeDistFilesPublic } from "./lib/dist-permissions.ts";
import { runOutputPath } from "./lib/run-isolation.ts";
import { SELF_UNREGISTERING_SERVICE_WORKER } from "./lib/self-unregistering-service-worker.ts";
/**
@@ -36,10 +37,18 @@ import { SELF_UNREGISTERING_SERVICE_WORKER } from "./lib/self-unregistering-serv
* is not what keeps the profile out of the worker cache (13-15). Step 6 reads
* the release manifest URL from the `dist/config.json` step 4 wrote, and fails
* if its `APP_ENV` is not `APP_PROFILE` (06-10).
*
* 1105/12-04. With `RUN_OUTPUT_ROOT` set (a Playwright config sets it for its
* web server under `TEST_RUN_ID`), every path above — `dist`,
* `.generated/frontend-runtime` and the build's `artifacts/` evidence — is
* under that folder instead, so a second build in the same checkout does not
* empty the first one's `dist`. Every step reads the same variable
* (`scripts/lib/run-isolation.ts`). Unset, the paths are the ones above.
*/
const selection = INSTALLED_RUNTIME_CAPABILITIES.serviceWorker;
const buildsActiveWorker = selection?.mode === "ACTIVE";
const dist = runOutputPath("dist");
function run(command: string, args: readonly string[]): void {
const result = spawnSync(command, [...args], {
@@ -53,8 +62,8 @@ function run(command: string, args: readonly string[]): void {
}
// 1. clean
await rm("dist", { recursive: true, force: true });
await rm(".generated/frontend-runtime", { recursive: true, force: true });
await rm(dist, { recursive: true, force: true });
await rm(runOutputPath(".generated/frontend-runtime"), { recursive: true, force: true });
// 2. contract set + build info
run("node", ["scripts/generate-contract-set.ts"]);
@@ -67,13 +76,13 @@ run("node", ["scripts/generate-runtime-config.ts"]);
if (buildsActiveWorker) {
// 5. hashed asset inventory
run("node", ["scripts/generate-service-worker-assets.ts", "dist"]);
run("node", ["scripts/generate-service-worker-assets.ts", dist]);
// 6. service worker build
run("npx", ["vite", "build", "--config", "vite.service-worker.config.ts"]);
} else if (selection?.mode === "REMOVE_REGISTRATION") {
// 6. self-unregistering worker in place of the active one
await writeFile(
`dist/${SERVICE_WORKER_SCRIPT_PATH}`,
`${dist}/${SERVICE_WORKER_SCRIPT_PATH}`,
SELF_UNREGISTERING_SERVICE_WORKER,
);
} else {
@@ -86,4 +95,4 @@ if (buildsActiveWorker) {
run("node", ["scripts/generate-build-manifest.ts"]);
// 8. publishable permissions: the validated writer creates 0600 files
await makeDistFilesPublic("dist");
await makeDistFilesPublic(dist);
+18
View File
@@ -820,6 +820,24 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
target === "src/adapters/telemetry/index.ts",
),
},
// 0929/12-03. A feature folder that is not a layer (support/) had no rule,
// so presentation reached the http adapter barrel through it with the
// graph and ESLint both passing.
{
name: "feature non-layer folder re-export of a concrete adapter is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "feature-and-app-roots-do-not-reach-adapters" &&
source === "src/features/alpha/support/telemetry.ts" &&
target === "src/adapters/telemetry/index.ts",
),
},
{
name: "feature adapters folder import of a concrete adapter is accepted",
passed: !blockingViolations(crossBoundaryGraph).some(
({ source }) => source === "src/features/alpha/adapters/telemetry-sink.ts",
),
},
{
name: "context re-export of a concrete adapter is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
+157 -42
View File
@@ -1,82 +1,197 @@
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import {
answerTableProblems,
excerptAnswerRows,
excerptDifferences,
readExcerptSections,
type ExcerptSections,
type NotCopiedRow,
} from "./lib/backend-contract-excerpt.ts";
/**
* 1103/12-06. Local only, outside every gate: CI checks this repository out
* alone. Tells whether the paired backend checkout next to this one has moved
* past the commit `config/contracts/backend-contract-pin.json` pins, and
* whether the contract document changed since.
* 1103/12-06, 1105/07-01. Local only, outside every gate: CI checks this
* repository out alone. With the paired backend checkout it checks that
*
* corepack pnpm check:backend-contract-drift [--backend <dir>]
* 1. the table excerpt (`tables.backendExcerpt`) is word for word the
* backend document's tables at the pinned commit,
* 2. the answer table JSON matches that excerpt (test:unit checks this too),
* 3. the document has not changed between the pin and the backend's HEAD,
* 4. 1105/16-02: neither have the backend scaffold files
* (`backend.scaffoldSources`) that `create:feature --with-create` copies
* four facts from (path plural rule, name limit, error codes, check
* order). Each changed file names the frontend copy to recheck.
*
* Exit 0: no checkout to compare, the pinned commit itself, or a later commit
* whose contract document is unchanged. Exit 1: the document changed after
* the pin. Recheck the frontend contract 6.1 table, the copied answer table
* and the pin in one change. Exit 2: the checkout cannot be compared.
* corepack pnpm check:backend-contract-drift [--backend <dir>] [--write-excerpt]
*
* `--write-excerpt` copies the excerpt from the pinned commit first: run it
* after moving the pin, then fix the answer table until this passes.
*
* Exit 0: all four hold. Exit 1: one does not; the output names the rows or
* files. Recheck the frontend contract 6.1 table, the answer table, the
* excerpt, the generator copies and the pin in one change. Exit 2: nothing
* was compared (no checkout, or the pinned commit or document is missing),
* which is not a pass.
*
* Without `--backend` the checkout is looked for beside the main checkout of
* this repository, so a linked worktree (`.claude/worktrees/<name>`) finds
* the same one.
*/
type ScaffoldSource = Readonly<{
path: string;
fact: string;
copiedTo: Readonly<{ file: string; symbol: string }>;
}>;
type Pin = Readonly<{
backend: Readonly<{ repository: string; commit: string; document: string }>;
backend: Readonly<{
repository: string;
commit: string;
document: string;
scaffoldSources?: readonly ScaffoldSource[];
}>;
tables: Readonly<{ idempotencyAnswers: string; backendExcerpt: string }>;
notCopied: readonly NotCopiedRow[];
}>;
type Answers = Readonly<{
answers: readonly Readonly<{ section: string; code: string; status: number }>[];
}>;
type Excerpt = Readonly<{
schemaVersion: 1;
source: Readonly<{ repository: string; commit: string; document: string }>;
sections: ExcerptSections;
}>;
const PIN_PATH = "config/contracts/backend-contract-pin.json";
function backendDirectory(pin: Pin): string {
const flag = process.argv.indexOf("--backend");
const given = flag >= 0 ? process.argv[flag + 1] : undefined;
return given
? path.resolve(given)
: path.resolve("..", pin.backend.repository);
}
function git(directory: string, ...args: string[]) {
return spawnSync("git", ["-C", directory, ...args], { encoding: "utf8" });
}
function backendDirectory(pin: Pin): string {
const flag = process.argv.indexOf("--backend");
const given = flag >= 0 ? process.argv[flag + 1] : undefined;
if (given) return path.resolve(given);
const common = spawnSync(
"git",
["rev-parse", "--path-format=absolute", "--git-common-dir"],
{ encoding: "utf8" },
);
const mainCheckout =
common.status === 0 && common.stdout.trim() !== ""
? path.dirname(common.stdout.trim())
: process.cwd();
return path.resolve(mainCheckout, "..", pin.backend.repository);
}
function readJson<T>(file: string): T {
return JSON.parse(readFileSync(file, "utf8")) as T;
}
function cannotCompare(message: string): void {
console.error(`Backend contract drift: not compared. ${message}`);
process.exitCode = 2;
}
function main(): void {
const pin = JSON.parse(readFileSync(PIN_PATH, "utf8")) as Pin;
const pin = readJson<Pin>(PIN_PATH);
const directory = backendDirectory(pin);
const { commit, document } = pin.backend;
const scaffoldSources = pin.backend.scaffoldSources ?? [];
if (!existsSync(path.join(directory, ".git"))) {
console.log(
`Backend contract drift: skipped, no ${pin.backend.repository} checkout at ${directory} (pass --backend <dir>)`,
cannotCompare(
`No ${pin.backend.repository} checkout at ${directory}; pass --backend <dir>. test:unit holds the answer table to ${pin.tables.backendExcerpt}, and only this script holds that copy to the backend.`,
);
return;
}
const head = git(directory, "rev-parse", "HEAD");
if (head.status !== 0 || git(directory, "cat-file", "-e", `${commit}^{commit}`).status !== 0) {
console.error(
`Backend contract drift: cannot compare ${directory} with the pinned ${commit.slice(0, 12)}; fetch the backend history first`,
cannotCompare(
`${directory} does not have the pinned ${commit.slice(0, 12)}; fetch the backend history first.`,
);
process.exitCode = 2;
return;
}
const headCommit = head.stdout.trim();
if (headCommit === commit) {
console.log(`Backend contract drift: ${directory} is at the pinned ${commit.slice(0, 12)}`);
const pinned = git(directory, "show", `${commit}:${document}`);
if (pinned.status !== 0) {
cannotCompare(`${document} is not in the pinned ${commit.slice(0, 12)}.`);
return;
}
const changed = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", document);
const tableLines = changed.stdout
.split("\n")
.filter((line) => /^[+-]\|/u.test(line));
if (changed.stdout.trim() === "") {
const sectionNames = Object.keys(readJson<Excerpt>(pin.tables.backendExcerpt).sections);
const pinnedSections = readExcerptSections(pinned.stdout, sectionNames);
if (process.argv.includes("--write-excerpt")) {
const written: Excerpt = {
schemaVersion: 1,
source: { repository: pin.backend.repository, commit, document },
sections: pinnedSections,
};
writeFileSync(pin.tables.backendExcerpt, `${JSON.stringify(written, null, 2)}\n`);
console.log(
`Backend contract drift: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document} unchanged`,
`Backend contract drift: wrote ${pin.tables.backendExcerpt} from ${commit.slice(0, 12)} §${sectionNames.join(", §")}`,
);
}
const excerpt = readJson<Excerpt>(pin.tables.backendExcerpt);
const failures: string[] = [];
const source = excerpt.source;
if (source.repository !== pin.backend.repository || source.commit !== commit || source.document !== document) {
failures.push(`${pin.tables.backendExcerpt} names ${source.commit.slice(0, 12)}, the pin ${commit.slice(0, 12)}`);
}
for (const line of excerptDifferences(excerpt.sections, pinnedSections)) {
failures.push(`excerpt differs from the pinned document: ${line}`);
}
const answers = readJson<Answers>(pin.tables.idempotencyAnswers).answers;
for (const problem of answerTableProblems(answers, pin.notCopied, excerptAnswerRows(pinnedSections))) {
failures.push(`answer table: ${problem}`);
}
const headCommit = head.stdout.trim();
if (headCommit !== commit) {
const changed = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", document);
if (changed.stdout.trim() !== "") {
failures.push(
`${document} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}`,
);
const current = git(directory, "show", `HEAD:${document}`);
const tableChanges =
current.status === 0
? excerptDifferences(pinnedSections, readExcerptSections(current.stdout, sectionNames))
: [];
for (const line of tableChanges) failures.push(` copied table at HEAD: ${line}`);
if (tableChanges.length === 0) {
failures.push(" (no copied table row changed; read the other changes with git diff)");
}
}
// 1105/16-02. The generator's copies of backend scaffold facts.
for (const scaffold of scaffoldSources) {
const scaffoldDiff = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", scaffold.path);
if (scaffoldDiff.stdout.trim() === "") continue;
failures.push(
`scaffold source ${scaffold.path} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}`,
);
failures.push(
` the generator copies "${scaffold.fact}" from it: recheck ${scaffold.copiedTo.symbol} in ${scaffold.copiedTo.file}`,
);
}
}
if (failures.length === 0) {
console.log(
headCommit === commit
? `Backend contract drift: ${directory} is at the pinned ${commit.slice(0, 12)}; the excerpt and the answer table match it`
: `Backend contract drift: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document} and ${scaffoldSources.length} scaffold sources unchanged; the excerpt and the answer table match it`,
);
return;
}
console.error("Backend contract drift:");
for (const failure of failures) console.error(` ${failure}`);
console.error(
`Backend contract drift: ${document} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}.`,
`Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, ${pin.tables.idempotencyAnswers}, ${pin.tables.backendExcerpt}, the generator copies of changed scaffold sources and ${PIN_PATH} together.`,
);
console.error(
`Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, config/contracts/backend-idempotency-answers.json and ${PIN_PATH} together.`,
);
for (const line of tableLines) console.error(` ${line}`);
if (tableLines.length === 0) {
console.error(" (no table rows changed; read the prose changes with git diff)");
}
process.exitCode = 1;
}
+7 -3
View File
@@ -152,13 +152,17 @@ async function resolveRegistrySource(
}
/**
* 1103/14-06. A contract composition failure (`ContractContributionError`)
* says only "not composable"; its cause is the `reason` property.
* 1103/14-06. A load error's cause may be only in its `reason` property, so
* it is printed after the message. 1105/09-03. `ContractContributionError`
* already ends its message with the reason (1103/09-07); that cause is
* printed once.
*/
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
return typeof reason === "string" &&
reason.length > 0 &&
!message.includes(reason)
? `${message} (reason: ${reason})`
: message;
}
+7 -2
View File
@@ -295,8 +295,9 @@ const gateSchema = z
* 1105/12-01. What the runner host must provide for the gate to pass, one
* line each. The workflow shows them as comments beside the job's
* `runs-on`; a line cannot hold a line break, so it cannot leave the
* comment. They describe the runner, not the gate's commands or evidence,
* so the reviewed gate shape (canonicalGateShapeSha256) leaves them out.
* comment. They are part of the reviewed gate shape
* (canonicalGateShapeSha256): dropping or changing one needs a new
* contract baseline, like any other change to what a gate demands.
*/
hostRequirements: z.array(nonEmpty.max(512)).min(1).max(8).optional(),
})
@@ -504,6 +505,7 @@ function canonicalGateShapeSha256(gates: CiGateContract["gates"]): string {
evidenceArtifactIds,
retentionClassId,
requiresEnvironment,
hostRequirements,
}) => ({
id,
name,
@@ -512,6 +514,9 @@ function canonicalGateShapeSha256(gates: CiGateContract["gates"]): string {
evidenceArtifactIds,
retentionClassId,
requiresEnvironment: requiresEnvironment ?? [],
// Only gates that declare runner requirements carry the key, so the
// digest of every other gate stays what it was.
...(hostRequirements === undefined ? {} : { hostRequirements }),
}),
);
return createHash("sha256").update(JSON.stringify(normalized)).digest("hex");
+27 -5
View File
@@ -830,20 +830,41 @@ function addUniqueStringIssues(
}
}
/**
* 1103/11-01. `automatedStatus` speaks for `scope` only. A route axe saw only
* on its failure state (a detail page whose one-resource read has no generic
* answer, scripts/lib/a11y-data-state.ts) is in `notChecked` with its reason
* instead; its content is the manual review's. Together they are the
* installed route registry. Version 1 put every route in `scope`.
*/
export const automatedA11yArtifactSchema = z
.object({
schemaVersion: z.literal(1),
schemaVersion: z.literal(2),
generatedAt: timestamp,
scope: z.array(nonEmptyString).min(1).max(128),
notChecked: z
.array(z.object({ routeId: nonEmptyString, reason: nonEmptyString }).strict())
.max(128),
threshold: z.object({ critical: z.literal(0), serious: z.literal(0) }).strict(),
automatedStatus: z.literal("passed"),
manualReview: z.literal("see artifacts/tests/a11y-manual/report.json"),
})
.strict()
.superRefine((artifact, context) => {
const installed: readonly string[] = MANUAL_A11Y_ROUTE_IDS;
const notCheckedIds = artifact.notChecked.map(({ routeId }) => routeId);
addUniqueStringIssues(artifact.scope, ["scope"], context);
if (JSON.stringify(artifact.scope) !== JSON.stringify(MANUAL_A11Y_ROUTE_IDS)) {
context.addIssue({ code: "custom", path: ["scope"], message: "must match the installed route registry" });
addUniqueStringIssues(notCheckedIds, ["notChecked"], context);
if (notCheckedIds.some((routeId) => !installed.includes(routeId))) {
context.addIssue({ code: "custom", path: ["notChecked"], message: "must name installed routes" });
}
const checked = installed.filter((routeId) => !notCheckedIds.includes(routeId));
if (JSON.stringify(artifact.scope) !== JSON.stringify(checked)) {
context.addIssue({
code: "custom",
path: ["scope"],
message: "must be the installed route registry less the notChecked routes",
});
}
});
@@ -1442,8 +1463,9 @@ export const documentationReviewArtifactSchema = z
.object({
path: nonEmptyString,
missingPaths: z.array(nonEmptyString),
// 1103/12-05. References into a paired repository that is not
// checked out beside this one. Reported, not failed.
// 1103/12-05, 1105/12-02. References into a paired repository
// whose pinned commit cannot be read beside this checkout (no
// checkout, or one without that commit). Reported, not failed.
unverifiedLinks: z.array(nonEmptyString),
missingScripts: z.array(nonEmptyString),
unknownGateIds: z.array(nonEmptyString),
+50 -3
View File
@@ -14,6 +14,12 @@
* `--keyed` is for a backend create made KEYED with its IdempotencyExecutor
* (its docs/manual/05-idempotency.md). Like the rest of the command, nothing
* here imports a sample feature.
*
* 1105/16-02. The backend scaffold facts copied here (name limit, error
* codes, 201 and the endpoints, the check order behind refusedBeforeWrite)
* and the path rule in create-feature.ts are listed with their backend
* files in config/contracts/backend-contract-pin.json `scaffoldSources`;
* `check:backend-contract-drift` says when one of those files changes.
*/
export type WriteSemantics = "NEVER" | "KEYED";
@@ -617,7 +623,8 @@ import { use${pascal}Create } from "./use-${base}-create.ts";
* of the name (400 ${write.invalidCode}, refused before the write) shows on
* the field and the form saves again. A save whose result is unknown (the
* response was lost) keeps the form: the user checks, or, for a KEYED
* command, resends the same request with the same key.
* command, resends the same request with the same key. Confirming it was
* applied opens the list, which shows whether the item is there.
*/
export default function ${pascal}CreatePage() {
const navigate = useNavigate();
@@ -656,6 +663,10 @@ export default function ${pascal}CreatePage() {
});
const effectUnknown = mutation.state.indicator === "mutation-effect-unknown";
const blocked = effectUnknown || mutation.state.indicator === "mutation-pending";
// A save this form did not start holds the coordinator (one left running
// when the user came back, or the check behind "confirm applied"): the save
// is off and the feedback says a save is running (1105/08-04).
const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending;
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
return (
@@ -694,7 +705,7 @@ export default function ${pascal}CreatePage() {
type="submit"
pending={form.pending}
pendingLabel={message("${camel}.form.saving")}
disabled={effectUnknown}
disabled={effectUnknown || otherSaveRunning}
>
{message("${camel}.form.save")}
</Button>
@@ -710,14 +721,21 @@ export default function ${pascal}CreatePage() {
<AsyncSurface
state={mutation.state}
supportReference={form.supportReference}
// The list shows whether the item is there; the form alone
// would show nothing but an emptied input (1105/08-02).
onReconcileUnknownEffect={(resolution) => {
void mutation.reconcileUnknownEffect(resolution).then(form.settleApplied);
void mutation.reconcileUnknownEffect(resolution).then(() => {
form.settleApplied();
void navigate(${camel}RouteUrl("${routeId}"));
});
}}
// Drawn only for a request with a key (a KEYED command).
onResendUnknownEffect={() => {
void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect()));
}}
/>
) : otherSaveRunning && form.result !== "effect-unknown" ? (
<AsyncSurface state={mutation.state} />
) : null
}
guard={<DirtyNavigationDialog guard={guard} />}
@@ -836,6 +854,14 @@ function answerItem(body: JsonBodyType = { id: ITEM_ID, name: "First item" }) {
);
}
function answerList() {
api.use(
http.get(\`\${API}${apiPath}\`, () =>
HttpResponse.json({ success: true, data: [{ id: ITEM_ID, name: "First item" }], meta: META }),
),
);
}
async function openForm() {
const user = await openSignedIn(${camel}RouteUrl("${write.create.routeId}"));
expect(
@@ -884,6 +910,27 @@ describe("${names.id} create form on the paired backend", () => {
});
${unknownTest}
// 1105/08-02. Confirming an unknown create opens the list, which shows
// whether the item was saved; the form alone showed nothing.
it("opens the list after the user confirms a create whose response was lost", async () => {
const posts = answerCreate(() => HttpResponse.error());
answerList();
const user = await openForm();
await user.type(await nameField(), "First item");
await user.click(saveButton());
expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible();
await user.click(
screen.getByRole("button", { name: KO_MESSAGES["action.confirmMutationApplied"] }),
);
expect(
await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }),
).toBeVisible();
expect(await screen.findByText("First item")).toBeVisible();
expect(posts).toHaveLength(1);
});
});
`;
}
+26 -2
View File
@@ -794,8 +794,9 @@ export const ${operationId}_CONTRACT = Object.freeze({
responseBody: "REQUIRED_JSON" as const,
// The paired backend wraps every JSON body (http-contract.md §1). Every
// operation of this contribution says so (1103/16-01: composition refuses
// one that does not). Drop the line from all of them for a backend that
// sends the DTO and problem details bare.
// one that does not, and check:types one without the line). Write
// "NONE" on all of them for a backend that sends the DTO and problem
// details bare.
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
@@ -1691,6 +1692,27 @@ async function readInstalledFacts(root: string): Promise<InstalledFacts> {
});
}
/**
* 1105/16-01. Tracked template files that change with every added feature,
* and the command that writes each. A feature branch commits them with the
* feature; two feature branches change the same lines, and the merge takes
* the command again instead of a hand-merged value. docs/manual/03 (A) and
* the "Adding a feature" table in docs/architecture/starter-experience.md
* list them (tests/unit/feature-tracked-files.test.ts).
*/
export const FEATURE_TRACKED_FILE_REWRITES = Object.freeze([
Object.freeze({
path: "public/release-manifest.json",
command: "node scripts/write-dev-release-manifest.ts",
when: "create:feature runs it: the dev server's manifest names the installed contract packages",
}),
Object.freeze({
path: "config/scale/feature-shape-ceilings.json",
command: "node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write",
when: "by hand while the sample is installed (the file goes with it): test:unit compares it with a build",
}),
]);
const USAGE =
"Usage: pnpm create:feature <id> [--context <context id>] [--with-create [--keyed]] " +
"[--package @scope/name@x.y.z --digest sha256:<64 hex> --revision <hex>]";
@@ -1752,6 +1774,8 @@ function report(plan: FeaturePlan): string {
" A failing gate's log is artifacts/quality/gates/FE-GATE-<NNN>.txt. Locally FE-GATE-013 needs VITE_COMMIT_SHA=$(git rev-parse HEAD); to run them as CI does, set CI=true and the CI build identity (README).",
" 3. The initial JavaScript changes. While config/scale/feature-shape-ceilings.json exists (the sample is installed), rewrite it with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write and commit it with the feature; test:unit compares it with a build. corepack pnpm check:bundle checks the budget.",
" public/release-manifest.json (the dev server's manifest) now names the feature's contract package; commit it with the feature.",
" Two feature branches change the same lines of these files. On a merge conflict, take either side and run the command again:",
...FEATURE_TRACKED_FILE_REWRITES.map((file) => ` ${file.path}: ${file.command}`),
" The registry baseline does not change: new routes, operations, schemas and invalidation topics are additive.",
];
return `${lines.join("\n")}\n`;
+1
View File
@@ -287,6 +287,7 @@ async function physicalAttempts(
retrySemantics,
requestBody: read ? ("NONE" as const) : ("JSON" as const),
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "NONE" as const,
commandRecovery: null,
commandEffect: read
? null
+18 -12
View File
@@ -21,8 +21,14 @@ import {
} from "./lib/build-environment.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
import { CANONICAL_VITE_MANIFEST_PATH } from "./lib/build-manifest-outputs.ts";
import { runOutputPath } from "./lib/run-isolation.ts";
assertCiBuildEnvironment(process.env);
// 1105/12-04. With RUN_OUTPUT_ROOT set, this build's dist and artifacts are
// under that folder. The manifest still records `dist`, `artifacts/...`:
// its paths are relative to the folder the build wrote, which is the
// checkout when the variable is unset.
const at = (relativePath: string) => runOutputPath(relativePath);
type ViteManifestEntry = Readonly<{
file: string;
name?: string;
@@ -39,10 +45,10 @@ const releaseId = process.env.RELEASE_ID ?? "local-release";
const runnerImage = process.env.CI_RUNNER_IMAGE ?? `${process.platform}-${process.arch}`;
const buildTime = buildDate(process.env);
const builtAt = buildTime.toISOString();
const viteManifest = await readFile(CANONICAL_VITE_MANIFEST_PATH, "utf8");
const viteManifest = await readFile(at(CANONICAL_VITE_MANIFEST_PATH), "utf8");
const viteManifestObject = parseViteManifest(JSON.parse(viteManifest));
const moduleInventory = await readFile(
"dist/.vite/module-inventory.json",
at("dist/.vite/module-inventory.json"),
"utf8",
);
const moduleInventoryDocument = moduleInventoryArtifactSchema.parse(
@@ -56,7 +62,7 @@ const moduleInventoryHash = createHash("sha256")
.update(moduleInventoryBytes)
.digest("hex");
const runtimeConfig = runtimeConfigV2ArtifactSchema.parse(
JSON.parse(await readFile("dist/config.json", "utf8")),
JSON.parse(await readFile(at("dist/config.json"), "utf8")),
);
const routeChunks: Record<string, string> = {};
const runtimeContracts: Readonly<Record<string, { moduleId: string }>> =
@@ -113,36 +119,36 @@ const releaseManifest = releaseManifestV2ArtifactSchema.parse({
contractSet: buildContractSet(),
});
await mkdir("artifacts/release", { recursive: true });
await mkdir("artifacts/quality", { recursive: true });
await mkdir(at("artifacts/release"), { recursive: true });
await mkdir(at("artifacts/quality"), { recursive: true });
await writeValidatedJsonArtifact({
path: "artifacts/quality/vite-module-inventory.json",
path: at("artifacts/quality/vite-module-inventory.json"),
schema: moduleInventoryArtifactSchema,
value: moduleInventoryDocument,
});
await rm("dist/.vite/module-inventory.json");
await rm(at("dist/.vite/module-inventory.json"));
await writeValidatedJsonArtifact({
path: "dist/config.json",
path: at("dist/config.json"),
schema: runtimeConfigV2ArtifactSchema,
value: runtimeConfig,
});
await writeValidatedJsonArtifact({
path: "dist/release-manifest.json",
path: at("dist/release-manifest.json"),
schema: releaseManifestV2ArtifactSchema,
value: releaseManifest,
});
await writeValidatedJsonArtifact({
path: "dist/runtime-config.schema.json",
path: at("dist/runtime-config.schema.json"),
schema: jsonSchemaDocumentArtifactSchema,
value: runtimeConfigJsonSchema,
});
await writeValidatedJsonArtifact({
path: "artifacts/release/runtime-config.schema.json",
path: at("artifacts/release/runtime-config.schema.json"),
schema: jsonSchemaDocumentArtifactSchema,
value: runtimeConfigJsonSchema,
});
await writeValidatedJsonArtifact({
path: "artifacts/release/build-manifest.json",
path: at("artifacts/release/build-manifest.json"),
schema: buildManifestArtifactSchema,
value: manifest,
});
+35 -8
View File
@@ -65,6 +65,18 @@ const defaultFileSystem: CiWorkflowFileSystem = Object.freeze({
rm: async (target) => rm(target, { force: true }),
});
const PRODUCT_GATE_JOB = "product_merge_gate";
/**
* 1105/13-02. The job that waits for the product gates. A failing product
* gate stopped nothing but a PR merge: the same run went on to release, build,
* promote and deploy, and the fixed job graph left a product no way to link
* them. release_gate is the first release-stage job, and every later one
* depends on it as it depends on merge_gate. The link is rendered from the
* overlay, so the template contract's job graph (and its check) stays the
* template's, and without product gates the workflow bytes do not change.
*/
const PRODUCT_GATES_HOLD = "release_gate";
export function renderCiWorkflow(
contract: CiGateContract,
productGates: readonly ProductGate[] = [],
@@ -76,6 +88,8 @@ export function renderCiWorkflow(
if (step.kind === "upload") transfers.set(step.transferId, { name: step.name });
}
}
// 1105/13-02. With product gates, the release stage waits for them too.
const productNeeds = productGates.length > 0 ? [PRODUCT_GATE_JOB] : [];
const lines = [
"# GENERATED FILE — edit config/ci/gates.json and run `corepack pnpm generate:ci-workflow`.",
"name: frontend-quality-gates",
@@ -113,7 +127,7 @@ export function renderCiWorkflow(
];
for (const [jobIndex, job] of contract.jobs.entries()) {
if (jobIndex > 0) lines.push("");
lines.push(...renderJob(job, index, transfers));
lines.push(...renderJob(job, index, transfers, job.id === PRODUCT_GATES_HOLD ? productNeeds : []));
}
if (productGates.length > 0) lines.push("", ...renderProductGateJob(productGates));
return `${lines.join("\n").replace(/\n+$/u, "")}\n`;
@@ -123,12 +137,13 @@ export function renderCiWorkflow(
* 1103/12-07. The product's merge gates (config/ci/product-gates.json) run in
* a job after every template job, on the same merge condition. A product gate
* is one package script; it has no log artifact or evidence of the template
* gate contract and is not part of its readiness formula, so the product makes
* this job a required check where it wants it to block a merge.
* gate contract and is not part of its readiness formula. The release stage
* waits for this job (1105/13-02); the product makes it a required check where
* it wants it to block a merge.
*/
function renderProductGateJob(productGates: readonly ProductGate[]): string[] {
return [
" product_merge_gate:",
` ${PRODUCT_GATE_JOB}:`,
` name: ${yamlScalar("${{ matrix.gate }} / ${{ matrix.name }}")}`,
` if: ${renderCondition("merge")}`,
" runs-on: ubuntu-latest",
@@ -161,10 +176,12 @@ function renderJob(
job: CiWorkflowJob,
index: ReturnType<typeof indexCiGateContract>,
transfers: ReadonlyMap<string, Readonly<{ name: string }>>,
productNeeds: readonly string[],
): string[] {
const lines = [` ${yamlKey(job.id)}:`, ` name: ${yamlScalar(job.displayName)}`];
if (job.needs.length === 1) lines.push(` needs: ${yamlKey(job.needs[0]!)}`);
if (job.needs.length > 1) lines.push(` needs: [${job.needs.map(yamlKey).join(", ")}]`);
const needs = [...job.needs, ...productNeeds];
if (needs.length === 1) lines.push(` needs: ${yamlKey(needs[0]!)}`);
if (needs.length > 1) lines.push(` needs: [${needs.map(yamlKey).join(", ")}]`);
const condition = renderCondition(job.condition);
if (condition) lines.push(` if: ${condition}`);
lines.push(
@@ -480,7 +497,7 @@ export function workflowGateExecutionFailures(
): string[] {
const executed = new Set<string>();
const jobs = workflow.split(/^(?= {2}[a-z_]+:$)/mu);
const productJob = jobs.find((job) => job.startsWith(" product_merge_gate:\n")) ?? "";
const productJob = jobs.find((job) => job.startsWith(` ${PRODUCT_GATE_JOB}:\n`)) ?? "";
const productRuns = /^ {8}run: corepack pnpm \$\{\{ matrix\.script \}\}$/mu.test(productJob);
const productFailures = productGates
.filter(
@@ -490,7 +507,17 @@ export function workflowGateExecutionFailures(
` - { gate: ${gate.id}, name: ${gate.name}, script: ${yamlScalar(gate.script)} }\n`,
),
)
.map(({ id }) => `product gate is not executed by the product_merge_gate job: ${id}`);
.map(({ id }) => `product gate is not executed by the ${PRODUCT_GATE_JOB} job: ${id}`);
// 1105/13-02. Run is not enough: a failing product gate must also hold the
// release stage.
const holdingJob = jobs.find((job) => job.startsWith(` ${PRODUCT_GATES_HOLD}:\n`)) ?? "";
const heldBy = /^ {4}needs: (?:\[([^\]\n]*)\]|(\S+))$/mu.exec(holdingJob);
if (
productGates.length > 0 &&
!(heldBy?.[1] ?? heldBy?.[2] ?? "").split(", ").includes(PRODUCT_GATE_JOB)
) {
productFailures.push(`product gates do not hold the release stage: ${PRODUCT_GATES_HOLD} does not need ${PRODUCT_GATE_JOB}`);
}
for (const job of jobs) {
for (const match of job.matchAll(/^ +run: corepack pnpm ci:gate -- (FE-GATE-\d{3})$/gmu)) {
executed.add(match[1]!);
+6 -3
View File
@@ -8,6 +8,7 @@ import {
type ContractSetPackage,
} from "../src/contracts/contract-set-canonical.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contract-contributions.ts";
import { moduleSpecifier, runOutputPath } from "./lib/run-isolation.ts";
/**
* §5.4 / §17.2.2 step 2. Derives the build-time expected contract set from the
@@ -16,6 +17,7 @@ import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contra
* cannot influence the release digest.
*/
/** Under `RUN_OUTPUT_ROOT` when a run sets one (1105/12-04). */
const OUTPUT = ".generated/frontend-runtime/contract-set.ts";
function sha256(bytes: Uint8Array): Uint8Array {
@@ -38,11 +40,12 @@ export function buildContractSet(
async function main(): Promise<void> {
const contractSet = buildContractSet();
const output = runOutputPath(OUTPUT);
const source = [
"// Generated by scripts/generate-contract-set.ts. Do not edit.",
"// Regenerated from scratch on every build; never committed.",
"",
"import type { ContractSet } from \"../../src/contracts/contract-set.ts\";",
`import type { ContractSet } from "${moduleSpecifier(output, "src/contracts/contract-set.ts")}";`,
"",
`export const BUILD_CONTRACT_SET: ContractSet = ${JSON.stringify(
contractSet,
@@ -52,8 +55,8 @@ async function main(): Promise<void> {
"",
].join("\n");
await mkdir(dirname(OUTPUT), { recursive: true });
await writeFile(OUTPUT, source, "utf8");
await mkdir(dirname(output), { recursive: true });
await writeFile(output, source, "utf8");
process.stdout.write(
`contract set: ${contractSet.packages.length} package(s) ${contractSet.setDigest}\n`,
);
+24 -3
View File
@@ -1,5 +1,6 @@
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
import { dirname, relative, resolve } from "node:path";
import { randomUUID } from "node:crypto";
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { selectCompiledProductFeatures } from "../src/contracts/product-features.ts";
@@ -404,6 +405,26 @@ export async function generateAppIndexes(
);
}
/**
* 1105/12-04. Every build, dev server, type check and test run renders these
* files first, so two runs in one checkout render them at the same time while
* the other run's Vite or tsc reads them. `writeFile` truncated the file in
* place, and a reader could see it empty or half written. An index that has
* not changed is left alone; a changed one replaces the old file with one
* rename, so a reader sees the old file or the new one, never a part.
*/
export async function writeIndexIfChanged(file: string, content: string): Promise<void> {
if ((await readFile(file, "utf8").catch(() => null)) === content) return;
const temporary = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);
try {
await writeFile(temporary, content, { encoding: "utf8", flag: "wx" });
await rename(temporary, file);
} catch (error) {
await rm(temporary, { force: true });
throw error;
}
}
async function main(): Promise<void> {
const scriptDir = dirname(fileURLToPath(import.meta.url));
// `--root=` points the same production command at another checkout (used by
@@ -448,7 +469,7 @@ async function main(): Promise<void> {
await Promise.all(
(["feature", "context", "app"] as const).map((key) =>
writeFile(outputs[key], rendered[key], "utf8"),
writeIndexIfChanged(outputs[key], rendered[key]),
),
);
}
+5 -2
View File
@@ -9,6 +9,7 @@ import {
type DeploymentTarget,
} from "../src/contracts/deployment-admission.ts";
import { runtimeConfigV2ArtifactSchema } from "../src/contracts/release-artifacts.ts";
import { runOutputPath } from "./lib/run-isolation.ts";
/**
* §6.4. Materializes `dist/config.json` from the profile the build declares.
@@ -24,6 +25,7 @@ import { runtimeConfigV2ArtifactSchema } from "../src/contracts/release-artifact
*/
const PROFILE_DIRECTORY = "config/runtime";
/** Under `RUN_OUTPUT_ROOT` when a run sets one (1105/12-04). */
const OUTPUT_PATH = "dist/config.json";
/**
@@ -98,9 +100,10 @@ function resolveTarget(environment: NodeJS.ProcessEnv): DeploymentTarget {
async function main(): Promise<void> {
const target = resolveTarget(process.env);
const config = await generateRuntimeConfig(target);
await writeFile(OUTPUT_PATH, `${JSON.stringify(config, null, 2)}\n`, "utf8");
const output = runOutputPath(OUTPUT_PATH);
await writeFile(output, `${JSON.stringify(config, null, 2)}\n`, "utf8");
process.stdout.write(
`runtime config: ${target} profile written to ${OUTPUT_PATH} ` +
`runtime config: ${target} profile written to ${output} ` +
`(APP_ENV=${String(config["APP_ENV"])}, AUTH_MODE=${String(config["AUTH_MODE"])})\n`,
);
}
+23 -8
View File
@@ -11,21 +11,27 @@ import path from "node:path";
import { getBuildConfig } from "../src/contracts/env.ts";
import {
BUILD_ASSET_DIRECTORY,
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
type StaticAssetManifestV1,
} from "../src/contracts/service-worker.ts";
import { moduleSpecifier, runOutputPath } from "./lib/run-isolation.ts";
/**
* §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed
* asset list the Service Worker will verify at install time.
* asset list under `BUILD_ASSET_DIRECTORY` the Service Worker will verify at
* install time.
*
* `service-worker.js` itself and `index.html` are excluded (§17.2.2), as are
* the runtime config and release manifest, which are network-only (§18.4).
*/
/** Read back by tests/e2e/support/service-worker-builds.ts (0929/11-03). */
/**
* Read back by tests/e2e/support/service-worker-builds.ts (0929/11-03). A
* build with `RUN_OUTPUT_ROOT` writes it under that folder (1105/12-04).
*/
export const SERVICE_WORKER_ASSETS_OUTPUT =
".generated/frontend-runtime/service-worker-assets.ts";
@@ -41,7 +47,12 @@ const EXCLUDED_FILES: ReadonlySet<string> = new Set([
"runtime-config.schema.json",
]);
/** Vite emits content-hashed names; only those may be treated as immutable. */
/**
* Vite emits content-hashed names under its assets directory; only those may
* be treated as immutable. A `public/` file copied to the dist root keeps its
* own name even when it looks hashed (`android-chrome-192x192.png`), and a
* product may change its bytes under that name (1105/06-01).
*/
const HASHED_NAME = HASHED_STATIC_ASSET_NAME;
/**
@@ -59,7 +70,10 @@ export async function collectStaticAssets(
for (const relative of files.sort()) {
const base = path.basename(relative);
if (EXCLUDED_FILES.has(base) || relative.startsWith(".vite/")) continue;
if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) {
continue;
}
if (EXCLUDED_FILES.has(base)) continue;
const contentType = CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()];
if (!contentType || !HASHED_NAME.test(base)) continue;
@@ -134,7 +148,8 @@ async function walk(root: string, current: string): Promise<string[]> {
}
async function main(): Promise<void> {
const distDirectory = process.argv[2] ?? "dist";
const distDirectory = process.argv[2] ?? runOutputPath("dist");
const output = runOutputPath(SERVICE_WORKER_ASSETS_OUTPUT);
const buildId = process.env.VITE_BUILD_ID ?? "local-build";
const releaseId = process.env.RELEASE_ID ?? "local-release";
const manifest = await collectStaticAssets(
@@ -146,7 +161,7 @@ async function main(): Promise<void> {
const source = [
"// Generated by scripts/generate-service-worker-assets.ts. Do not edit.",
"",
'import type { StaticAssetManifestV1 } from "../../src/contracts/service-worker.ts";',
`import type { StaticAssetManifestV1 } from "${moduleSpecifier(output, "src/contracts/service-worker.ts")}";`,
"",
`export const SERVICE_WORKER_ASSETS: StaticAssetManifestV1 = ${JSON.stringify(
manifest,
@@ -155,8 +170,8 @@ async function main(): Promise<void> {
)} as const;`,
"",
].join("\n");
await mkdir(path.dirname(SERVICE_WORKER_ASSETS_OUTPUT), { recursive: true });
await writeFile(SERVICE_WORKER_ASSETS_OUTPUT, source, "utf8");
await mkdir(path.dirname(output), { recursive: true });
await writeFile(output, source, "utf8");
process.stdout.write(
`service worker assets: ${manifest.assets.length} file(s) ${manifest.setDigest}\n`,
);
+98
View File
@@ -0,0 +1,98 @@
import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
/**
* 1103/11-01. Which routes `tests/e2e/accessibility.spec.ts` could scan only
* on their failure state. The spec answers a protected page's list reads with
* an empty list; a read of one resource (a detail page) has no generic answer,
* so that page is scanned on its error screen. Passing axe there says nothing
* about the page's own content, and `artifacts/tests/a11y.json` used to list
* it as passed anyway.
*
* Each route's test leaves its answer in this directory: a record when it saw
* only the failure state, no record otherwise. A route's latest run therefore
* decides. `scripts/write-a11y-report.ts` reads the records and reports those
* routes under `notChecked` instead of in the passed `scope`.
*/
export const A11Y_DATA_STATE_DIRECTORY = "artifacts/tests/a11y-data-state";
export type A11yNotCheckedRoute = Readonly<{ routeId: string; reason: string }>;
const ROUTE_ID = /^[A-Z][A-Z0-9_]*$/u;
function recordPath(directory: string, routeId: string): string {
if (!ROUTE_ID.test(routeId)) {
throw new TypeError(`not a route id: ${routeId}`);
}
return path.join(directory, `${routeId}.json`);
}
/** `reason` is null when the route was scanned in its own state. */
export async function recordA11yDataState(
routeId: string,
reason: string | null,
directory: string = A11Y_DATA_STATE_DIRECTORY,
): Promise<void> {
const file = recordPath(directory, routeId);
if (reason === null) {
await rm(file, { force: true });
return;
}
if (reason.length === 0) throw new TypeError("a not-checked route needs a reason");
await mkdir(directory, { recursive: true });
// Every engine records the same route at once: write whole, then rename.
const pending = `${file}.${randomUUID()}.tmp`;
await writeFile(pending, `${JSON.stringify({ routeId, reason })}\n`, "utf8");
await rename(pending, file);
}
/** The records for `routeIds`, in their order. A route with none was checked. */
export async function readA11yNotCheckedRoutes(
routeIds: readonly string[],
directory: string = A11Y_DATA_STATE_DIRECTORY,
): Promise<readonly A11yNotCheckedRoute[]> {
const notChecked: A11yNotCheckedRoute[] = [];
for (const routeId of routeIds) {
let text: string;
try {
text = await readFile(recordPath(directory, routeId), "utf8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
throw error;
}
const record = JSON.parse(text) as Partial<Record<"routeId" | "reason", unknown>>;
if (
record.routeId !== routeId ||
typeof record.reason !== "string" ||
record.reason.length === 0
) {
throw new TypeError(`malformed a11y data-state record for ${routeId}`);
}
notChecked.push(Object.freeze({ routeId, reason: record.reason }));
}
return Object.freeze(notChecked);
}
/**
* The `artifacts/tests/a11y.json` value. `automatedStatus: "passed"` speaks
* for `scope` only: the installed routes axe scanned in their own state.
*/
export function automatedA11yReport(
input: Readonly<{
routeIds: readonly string[];
notChecked: readonly A11yNotCheckedRoute[];
generatedAt: string;
}>,
) {
const notCheckedIds = new Set(input.notChecked.map(({ routeId }) => routeId));
return {
schemaVersion: 2 as const,
generatedAt: input.generatedAt,
scope: input.routeIds.filter((routeId) => !notCheckedIds.has(routeId)),
notChecked: input.notChecked.map(({ routeId, reason }) => ({ routeId, reason })),
threshold: { critical: 0 as const, serious: 0 as const },
automatedStatus: "passed" as const,
manualReview: "see artifacts/tests/a11y-manual/report.json" as const,
};
}
+187
View File
@@ -0,0 +1,187 @@
/**
* 1105/07-01. The paired backend's `http-contract.md` tables the frontend
* copies at the pinned commit (`config/contracts/backend-http-contract-excerpt.json`),
* read the same way from the backend document and from the copy.
*
* - `tests/unit/backend-contract-pin.test.ts` (test:unit) holds the answer
* table JSON to the copy. It needs no backend checkout.
* - `scripts/check-backend-contract-drift.ts` (local, outside the gates) holds
* the copy to the backend document at the pin and reports what changed at
* the backend's HEAD.
*/
/** Section number (`"2"` for `## 2. ...`) → its tables, each the `|` lines in order. */
export type ExcerptSections = Readonly<Record<string, readonly (readonly string[])[]>>;
export type ContractAnswerRow = Readonly<{
section: string;
code: string;
status: number;
}>;
export type NotCopiedRow = Readonly<{
section: string;
code: string;
reason: string;
}>;
const SECTION_HEADING = /^## (\d+)\.\s/u;
const ANY_SECTION_HEADING = /^## /u;
const CODE_HEADERS = new Set(["error.code", "코드"]);
const STATUS_HEADER = "status";
const CODE_CELL = /^`([A-Z][A-Z0-9_]*)`/u;
const STATUS_CELL = /^\d{3}$/u;
const SEPARATOR_ROW = /^\|(?:\s*:?-+:?\s*\|)+\s*$/u;
/**
* The tables of the `## N.` sections named: every run of lines that start
* with `|`, kept as written. A `###` heading stays inside its section.
*/
export function readExcerptSections(
markdown: string,
sections: readonly string[],
): ExcerptSections {
const tables: Record<string, string[][]> = {};
let section: string | undefined;
let table: string[] | undefined;
for (const line of markdown.split(/\r?\n/u)) {
if (ANY_SECTION_HEADING.test(line)) {
section = SECTION_HEADING.exec(line)?.[1];
table = undefined;
continue;
}
if (section === undefined || !sections.includes(section) || !line.startsWith("|")) {
table = undefined;
continue;
}
if (table === undefined) {
table = [];
(tables[section] ??= []).push(table);
}
table.push(line);
}
return Object.freeze(
Object.fromEntries(
sections.map((name) => [
name,
Object.freeze((tables[name] ?? []).map((rows) => Object.freeze([...rows]))),
]),
),
);
}
function cells(line: string): string[] {
return line
.replace(/^\|/u, "")
.replace(/\|\s*$/u, "")
.split("|")
.map((cell) => cell.trim());
}
/**
* The rows that answer with one error code and one status: the code column
* is headed `error.code` or `코드`, the status column `status`. A row without
* a code (§2's replay) or without one three-digit status is not an answer.
*/
export function excerptAnswerRows(sections: ExcerptSections): readonly ContractAnswerRow[] {
const rows: ContractAnswerRow[] = [];
for (const [section, tables] of Object.entries(sections)) {
for (const table of tables) {
const [header = "", ...body] = table;
const headings = cells(header).map((cell) => cell.replaceAll("`", ""));
const codeColumn = headings.findIndex((cell) => CODE_HEADERS.has(cell));
const statusColumn = headings.indexOf(STATUS_HEADER);
if (codeColumn < 0 || statusColumn < 0) continue;
for (const line of body) {
if (SEPARATOR_ROW.test(line)) continue;
const row = cells(line);
const code = CODE_CELL.exec(row[codeColumn] ?? "")?.[1];
const status = row[statusColumn] ?? "";
if (code !== undefined && STATUS_CELL.test(status)) {
rows.push(Object.freeze({ section, code, status: Number(status) }));
}
}
}
}
return Object.freeze(rows);
}
/**
* What the copied answer table gets wrong against the excerpt: an answer the
* named section does not have, an excerpt row neither copied nor listed as
* not copied, and a not-copied entry the excerpt does not have. An answer
* covers an excerpt row of any section with the same code and status (§4
* repeats §2's `IDEMPOTENCY_KEY_INVALID`).
*/
export function answerTableProblems(
answers: readonly ContractAnswerRow[],
notCopied: readonly NotCopiedRow[],
excerpt: readonly ContractAnswerRow[],
): readonly string[] {
const problems: string[] = [];
for (const answer of answers) {
const inSection = excerpt.some(
(row) =>
row.section === answer.section &&
row.code === answer.code &&
row.status === answer.status,
);
if (!inSection) {
problems.push(
`answer ${answer.status} ${answer.code} is not a row of the pinned document's §${answer.section}`,
);
}
}
for (const row of excerpt) {
const copied = answers.some(
(answer) => answer.code === row.code && answer.status === row.status,
);
const skipped = notCopied.some(
(entry) => entry.section === row.section && entry.code === row.code,
);
if (copied && skipped) {
problems.push(
`§${row.section} ${row.status} ${row.code} is both copied and listed in notCopied`,
);
} else if (!copied && !skipped) {
problems.push(
`§${row.section} ${row.status} ${row.code} is neither in the answer table nor in the pin's notCopied`,
);
}
}
for (const entry of notCopied) {
if (!excerpt.some((row) => row.section === entry.section && row.code === entry.code)) {
problems.push(
`notCopied ${entry.code} is not a row of the pinned document's §${entry.section}`,
);
}
}
return Object.freeze(problems);
}
/**
* The lines one excerpt has and the other does not, per section: `-` only
* in `expected`, `+` only in `actual`. Empty when they are the same.
*/
export function excerptDifferences(
expected: ExcerptSections,
actual: ExcerptSections,
): readonly string[] {
const differences: string[] = [];
const names = [...new Set([...Object.keys(expected), ...Object.keys(actual)])].sort();
for (const name of names) {
const before = (expected[name] ?? []).flat();
const after = (actual[name] ?? []).flat();
const sameTables =
JSON.stringify(expected[name] ?? []) === JSON.stringify(actual[name] ?? []);
if (sameTables) continue;
const removed = before.filter((line) => !after.includes(line));
const added = after.filter((line) => !before.includes(line));
for (const line of removed) differences.push(`§${name} -${line}`);
for (const line of added) differences.push(`§${name} +${line}`);
if (removed.length === 0 && added.length === 0) {
differences.push(`§${name} the same rows, split into tables or ordered differently`);
}
}
return Object.freeze(differences);
}
+62
View File
@@ -0,0 +1,62 @@
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
/**
* 1105/16-04. What a product feature leaves behind after
* `test:sample-removal -- --feature=<id>` deleted its folders, in the copy the
* drill made.
*
* - `src/`: any file whose path or text still names the feature ID or its
* folder. Platform source never names a product feature, so a name left
* there is a reference the type checker cannot see (a catalog key, a
* runtime override, a link).
* - `tests/`: a file named after the feature, or one that imports from the
* feature's `src/features/<dir>/` or `tests/features/<dir>/`. The test
* text is not searched for the bare name: the template's own tests use
* example IDs as data (`tests/unit/create-feature.test.ts` writes
* `invoice-feature`, the manual's example, 51 times), and the drill flagged
* them as residue of a product feature that took that name. A test that
* still depends on the removed feature fails `test:all`, which the drill
* runs.
*
* The reference sample keeps its own, wider pattern in
* scripts/test-sample-removal.ts: the template owns all of its files.
*/
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
}
async function filesUnder(directory: string): Promise<string[]> {
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
const nested = await Promise.all(
entries.map((entry) => {
const target = path.join(directory, entry.name);
return entry.isDirectory() ? filesUnder(target) : Promise.resolve([target]);
}),
);
return nested.flat();
}
export async function productFeatureResidue(
root: string,
featureId: string,
directory: string,
): Promise<string[]> {
const names = [...new Set([featureId, directory])].map(escapeRegExp).join("|");
const named = new RegExp(names, "iu");
const imported = new RegExp(
String.raw`(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\bmock\s*\(\s*)["'][^"'\n]*/features/(?:${names})/`,
"u",
);
const residue: string[] = [];
const relative = (file: string) => path.relative(root, file).split(path.sep).join("/");
for (const file of await filesUnder(path.join(root, "src"))) {
const name = relative(file);
if (named.test(`${name}\n${await readFile(file, "utf8")}`)) residue.push(name);
}
for (const file of await filesUnder(path.join(root, "tests"))) {
const name = relative(file);
if (named.test(name) || imported.test(await readFile(file, "utf8"))) residue.push(name);
}
return residue.sort();
}
+48 -6
View File
@@ -2,7 +2,10 @@ import { isIP } from "node:net";
import path from "node:path";
import { connect } from "node:tls";
import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts";
import {
BUILD_ASSET_DIRECTORY,
type InstalledServiceWorkerSelection,
} from "../../src/contracts/service-worker.ts";
import { CACHEABLE_ASSET_CONTENT_TYPES } from "../../src/contracts/service-worker-static-manifest.ts";
import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.ts";
@@ -272,17 +275,26 @@ export function acceptedAssetContentTypes(extension: string): readonly string[]
* mismatch, while a page still uses, say, a font served as octet-stream. The
* entry script alone does not show that, so the live probe requests the first
* built `assets/` file of each cacheable extension.
*
* 1105/06-02. The install fetch also refuses any redirect (`redirect:
* "error"`), so an asset answered only after one fails here too, whichever
* redirect mode the fetcher uses.
*
* It runs for a build without a worker as well, on purpose: under `nosniff`
* a script or style of another type breaks the page anyway, and a later
* release that turns the worker on needs no new hosting check. A font or
* image of another type fails this probe although such a page still loads it.
*/
export async function probeAssetContentTypes(
base: URL,
distFiles: readonly string[],
fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }),
fetcher: HostingFetcher = (url) => fetch(url, { redirect: "manual" }),
): Promise<ProbeResult[]> {
const samples = new Map<string, string>();
for (const file of distFiles.map((entry) => entry.split(path.sep).join("/")).sort()) {
const extension = path.posix.extname(file).toLowerCase();
if (
file.startsWith("assets/") &&
file.startsWith(BUILD_ASSET_DIRECTORY) &&
acceptedAssetContentTypes(extension).length > 0 &&
!samples.has(extension)
) {
@@ -293,11 +305,14 @@ export async function probeAssetContentTypes(
for (const [extension, file] of [...samples].sort(([left], [right]) => left.localeCompare(right))) {
const expected = acceptedAssetContentTypes(extension);
let observed: string;
let redirected = false;
try {
const response = await fetcher(new URL(file, base));
await response.body?.cancel().catch(() => undefined);
observed =
response.status === 200
redirected = response.redirected || response.type === "opaqueredirect";
observed = redirected
? "redirected"
: response.status === 200
? (response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "")
: `HTTP ${response.status}`;
} catch (error: unknown) {
@@ -308,12 +323,39 @@ export async function probeAssetContentTypes(
header: "content-type",
expected,
observed,
passed: expected.includes(observed),
...(redirected
? { reason: "the worker's install fetch refuses a redirected asset" }
: {}),
passed: !redirected && expected.includes(observed),
});
}
return results;
}
/**
* 1105/06-02. Everything live mode of `verify:hosting-headers` asks the
* deployed host: the release surfaces (`probeLiveRelease`) and one built asset
* per cacheable type (`probeAssetContentTypes`). Live mode refuses loopback
* and plain http, so tests reach it only through this function and a fetcher
* double; a check dropped from here fails a test.
*/
export async function probeLiveHosting(
base: URL,
paths: Readonly<Record<string, string>>,
candidate: CandidateRelease,
distFiles: readonly string[],
transport: ProbeTransport = {},
): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> {
const probed = await probeLiveRelease(base, paths, candidate, transport);
return {
responses: probed.responses,
results: [
...probed.results,
...(await probeAssetContentTypes(base, distFiles, transport.fetcher)),
],
};
}
/** A build ships a worker script for these selections (06-03: REMOVE_REGISTRATION ships the self-unregistering one). */
export function shipsServiceWorker(selection: InstalledServiceWorkerSelection | null): boolean {
return selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION";
+44
View File
@@ -23,6 +23,50 @@ export function previewArguments(port: number): readonly string[] {
];
}
/**
* 1105/15-05. Playwright starts Chromium with `--hide-scrollbars`, so the lab
* measured layout shift in a browser without the classic scrollbar most
* Windows and Linux desktops draw. A first render that made one appear
* moved the header 15 px and the lab reported CLS 0. The lab runs with
* scrollbars, as those users see the page.
*/
export function labBrowserLaunchOptions(): { ignoreDefaultArgs: string[] } {
return { ignoreDefaultArgs: ["--hide-scrollbars"] };
}
export type LabRoute = Readonly<{
routeId: string;
path: string;
access: "public" | "session-required";
title: string;
navigationLabel: string | null;
navigationOrder: number | null;
}>;
/**
* 1105/15-04. The feature route the lab times next to its platform target:
* the first one in the navigation that an installed feature owns and a
* visitor without a session can open. The platform target loads no feature
* code, so its number stayed flat while a feature route's first entry (the
* context route module, then the page chunk) took 2.7 times as long and no
* gate measured it. `null` when no installed feature has such a route; the
* lab then records that it measured none.
*/
export function labFeatureRoute(
routes: readonly LabRoute[],
owners: Readonly<Record<string, string>>,
): LabRoute | null {
const candidates = routes.filter(
(route) =>
owners[route.routeId] !== undefined &&
route.access === "public" &&
route.navigationLabel !== null &&
route.navigationOrder !== null,
);
candidates.sort((left, right) => left.navigationOrder! - right.navigationOrder!);
return candidates[0] ?? null;
}
export type SampleSummary = Readonly<{
median: number;
min: number;
+25 -1
View File
@@ -62,10 +62,30 @@ export function describeBundleBudgetFailures(
return lines;
}
/**
* 1105/15-01. `targetDeepLinkCls` is the CLS of a direct visit to the lab's
* target route, judged against the same `cls` threshold. The click run
* cannot see a shift the target makes while it fills in: one within 500 ms
* of the click is input-driven by definition.
*/
export type LabMetrics = Readonly<{
lcpMs: number;
cls: number;
namedInteractionMs: number;
targetDeepLinkCls: number;
/**
* 1105/15-04. Click to heading on the first public navigation route an
* installed feature owns (`labFeatureRoute`). `null` when there is none:
* nothing to judge.
*/
featureRouteInteractionMs: number | null;
}>;
export type LabThresholds = Readonly<{
lcpMs: number;
cls: number;
namedInteractionMs: number;
featureRouteInteractionMs: number;
}>;
export function evaluateLabBudget(
@@ -73,7 +93,7 @@ export function evaluateLabBudget(
context?: Readonly<Record<string, unknown>>;
metrics: LabMetrics;
}>,
thresholds: LabMetrics,
thresholds: LabThresholds,
) {
const requiredContext = [
"runner",
@@ -92,6 +112,10 @@ export function evaluateLabBudget(
cls: report.metrics.cls <= thresholds.cls,
namedInteraction:
report.metrics.namedInteractionMs <= thresholds.namedInteractionMs,
targetDeepLinkCls: report.metrics.targetDeepLinkCls <= thresholds.cls,
featureRouteInteraction:
report.metrics.featureRouteInteractionMs === null ||
report.metrics.featureRouteInteractionMs <= thresholds.featureRouteInteractionMs,
};
return Object.freeze({
missingContext: Object.freeze(missingContext),
+25
View File
@@ -138,6 +138,28 @@ function onlyExtendsAllowedValues(before: unknown, after: unknown): boolean {
});
}
/**
* 1105/07-02. A response schema row that starts rejecting unknown keys
* narrows what the frontend accepts, as removing an accepted status does in
* FE-REG-API: every response the backend extends with a field then fails with
* SCHEMA_MISMATCH. That one direction is breaking. REJECT -> STRIP widens the
* reader, and a REQUEST row's policy is checked against what the frontend
* itself sends; both stay behavior-change, as does any other policy change.
*/
function narrowsResponseReader(
field: string,
before: unknown,
after: unknown,
row: Readonly<Record<string, unknown>>,
): boolean {
return (
field === "unknownFieldPolicy" &&
before !== "REJECT_UNKNOWN" &&
after === "REJECT_UNKNOWN" &&
row.direction === "RESPONSE"
);
}
function changeId(
registryId: string,
rowName: string,
@@ -343,6 +365,9 @@ export function diffRegistrySnapshots(
} else if (keyedSetFields.has(field) && Array.isArray(afterValue)) {
kind = "set-items-added";
changeImpact = "additive";
} else if (narrowsResponseReader(field, beforeValue, afterValue, afterRow)) {
kind = "response-reader-narrowed";
changeImpact = "breaking";
} else {
kind = "field-changed";
changeImpact = breakingFields.has(field)
@@ -0,0 +1,63 @@
/**
* The features this template ships that a copied project may delete: the
* reference sample (README "Files you can delete after copying") and the
* example screens (docs/architecture/starter-experience.md, CHANGELOG "먼저
* 할 일" 6). Each owns its folder under `src/features/` and `tests/features/`
* and the context it is the only feature of. The reference sample also owns
* files outside them, which `scripts/test-sample-removal.ts` deletes with it.
*
* This is the one list. The removal drill reads the reference sample's paths
* and scripts from it, and the documentation check reads the whole of it: a
* feature counts as deleted once its `feature-module.ts` is gone.
*/
export type RemovableTemplateFeature = Readonly<{
/** Its FEATURE_MODULE_ID, also its folder under src/features and tests/features. */
featureId: string;
/** The bounded context it is the only feature of; it goes with the feature. */
contextDirectory: string;
/** Files outside those folders that only this feature uses. */
extraPaths: readonly string[];
/** Package scripts that only this feature uses. */
scripts: readonly string[];
}>;
export const REMOVABLE_TEMPLATE_FEATURES: readonly RemovableTemplateFeature[] = Object.freeze([
Object.freeze({
featureId: "reference-feature",
contextDirectory: "src/contexts/reference-context",
// 0929/10-02. The HTTP scenario catalog (tests/mocks) and the negative
// type fixtures of the feature APIs run on the test contracts, so they
// are platform checks and stay (commonTestPaths in the drill).
extraPaths: Object.freeze([
"tests/component/product-feature-switch.test.tsx",
"tests/e2e/reference-form.spec.ts",
"tests/e2e/reference-route.spec.ts",
"tests/e2e/reference-save.spec.ts",
// 11-04: the growth measurement copies this sample feature.
"tests/unit/feature-shape-growth.test.ts",
"scripts/scale/measure-feature-shape-growth.ts",
"config/scale/feature-shape-growth.json",
"config/scale/feature-shape-ceilings.json",
]),
scripts: Object.freeze(["test:reference-feature"]),
}),
// 1103/09-04. The example screens /examples/ui, /examples/states and
// /examples/auth. The platform overview (/examples/platform) is a platform
// route and is not part of it.
Object.freeze({
featureId: "platform-examples-feature",
contextDirectory: "src/contexts/platform-examples-context",
extraPaths: Object.freeze([]),
scripts: Object.freeze([]),
}),
]);
/** Every path removing `feature` deletes: its folders, its context and its extra files. */
export function removableTemplateFeaturePaths(feature: RemovableTemplateFeature): readonly string[] {
return Object.freeze([
`src/features/${feature.featureId}`,
`tests/features/${feature.featureId}`,
feature.contextDirectory,
...feature.extraPaths,
]);
}
+8
View File
@@ -70,6 +70,14 @@ export const REMOVAL_FIXTURE_DOCUMENT_TARGETS = Object.freeze([
export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([
"tests/unit/changelog-review-ids.test.ts",
"tests/unit/documentation-readiness.test.ts",
// 1105/03-01. Reads the 6.1 table of the frontend contract document.
"tests/unit/backend-contract-pin.test.ts",
// 1105/16-01. Reads the 03 manual and docs/architecture/starter-experience.md.
"tests/unit/feature-tracked-files.test.ts",
// 1105/14-01
"tests/unit/template-feature-removal-documents.test.ts",
// 1105/14-02. Reads a code block of docs/manual.
"tests/unit/manual-paired-backend-settings.test.ts",
] as const);
/** The tests a fixture copied from `copyTargets` cannot run. */
+155
View File
@@ -0,0 +1,155 @@
import { createServer } from "node:net";
import path from "node:path";
/**
* 1105/12-04. Where one run writes, so that two runs in one checkout do not
* overwrite each other's build, results and reports.
*
* Two variables, read by different code:
*
* - `TEST_RUN_ID` names a Playwright run. The Playwright configs put its
* results, HTML report, JUnit file and the build its web server serves under
* `.tmp/runs/<id>/`, at the paths they have in the checkout:
* `artifacts/tests/e2e/results` becomes
* `.tmp/runs/<id>/artifacts/tests/e2e/results`, `dist` becomes
* `.tmp/runs/<id>/dist`. Unset, a run writes where it always did, which is
* where the gates, the CI upload and the evidence checks read.
* - `RUN_OUTPUT_ROOT` is what a Playwright config hands its web server. The
* build (`scripts/build-frontend.ts` and every step it runs) writes `dist/`,
* `.generated/frontend-runtime/` and its `artifacts/` evidence under it, and
* Vite keeps its cache there. Build code reads only this variable, never
* `TEST_RUN_ID`: a test that builds a copy of the repository inherits the
* runner's environment and must still build into the copy's own `dist`.
*
* Both roots are `.` or a folder under `.tmp/`. Git ignores `.tmp/`, and so do
* Tailwind's source scan (a Playwright report there would add classes to the
* CSS), Vite's file watcher, Vitest and the e2e helpers that copy the
* repository.
*
* Ports are separate from the run ID: every config serves on a free port
* unless its `TEST_*_PORT` variable pins one (`TEST_PORT_VARIABLES`), so two
* checkouts on one machine do not collide either.
*/
export const TEST_RUN_ID_VARIABLE = "TEST_RUN_ID";
export const RUN_OUTPUT_ROOT_VARIABLE = "RUN_OUTPUT_ROOT";
export const TEST_RUN_DIRECTORY = ".tmp/runs";
type Environment = Readonly<Record<string, string | undefined>>;
const RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
/** `.` without a run ID, `.tmp/runs/<id>` with one. */
export function testRunRoot(environment: Environment = process.env): string {
const runId = environment[TEST_RUN_ID_VARIABLE];
if (runId === undefined || runId === "") return ".";
if (!RUN_ID.test(runId)) {
throw new TypeError(
`${TEST_RUN_ID_VARIABLE} must be 1 to 64 letters, digits, ".", "_" or "-", ` +
`starting with a letter or digit; received ${JSON.stringify(runId)}`,
);
}
return `${TEST_RUN_DIRECTORY}/${runId}`;
}
/** `relativePath` as this run writes it: unchanged without a run ID. */
export function testRunPath(
relativePath: string,
environment: Environment = process.env,
): string {
return path.posix.join(testRunRoot(environment), relativePath);
}
/** `.` when unset; otherwise a normalized folder under `.tmp/`. */
export function runOutputRoot(environment: Environment = process.env): string {
const declared = environment[RUN_OUTPUT_ROOT_VARIABLE];
if (declared === undefined || declared === "") return ".";
const root = path.posix.normalize(declared).replace(/\/+$/u, "");
if (root === ".") return ".";
if (declared.includes("\\") || !root.startsWith(".tmp/") || root.split("/").includes("..")) {
throw new TypeError(
`${RUN_OUTPUT_ROOT_VARIABLE} must be "." or a folder under .tmp/ in this checkout; ` +
`received ${JSON.stringify(declared)}`,
);
}
return root;
}
/** `relativePath` as the build writes it: unchanged without an output root. */
export function runOutputPath(
relativePath: string,
environment: Environment = process.env,
): string {
return path.posix.join(runOutputRoot(environment), relativePath);
}
/**
* The port variable of each Playwright config's web server. Unset, the config
* picks a free port; set, it uses that one (to pin a port while debugging).
*/
export const TEST_PORT_VARIABLES = Object.freeze({
e2e: "TEST_E2E_PORT",
visual: "TEST_VISUAL_PORT",
capabilities: "TEST_CAPABILITIES_PORT",
storybook: "TEST_STORYBOOK_PORT",
dev: "TEST_DEV_PORT",
} as const);
/**
* A port nothing listens on now: the one the kernel gives a socket bound to
* port 0, which is closed again. Another process can still take it before the
* web server binds it. The configs start their servers with `--strictPort`
* (vite) or a fixed `listen` (serve-static) and `reuseExistingServer: false`,
* so that case is a start failure, never a run against someone else's server.
*/
export async function findFreePort(host = "127.0.0.1"): Promise<number> {
return new Promise<number>((resolve, reject) => {
const server = createServer();
server.unref();
server.once("error", reject);
server.listen(0, host, () => {
const address = server.address();
server.close(() => {
if (address !== null && typeof address === "object") resolve(address.port);
else reject(new Error(`no port was bound on ${host}`));
});
});
});
}
/**
* The port one config's web server listens on, kept in `variable`.
*
* Playwright evaluates the config again in each worker process, and the
* workers inherit the runner's environment. The runner's evaluation writes
* the port it picked into `variable`; the workers' evaluations read it, so
* `baseURL` is the same everywhere. A value already set is used as given.
*/
export async function reservePort(
variable: string,
environment: Record<string, string | undefined> = process.env,
find: () => Promise<number> = findFreePort,
): Promise<number> {
const pinned = environment[variable];
if (pinned !== undefined && pinned !== "") {
const port = Number(pinned);
if (!/^\d+$/u.test(pinned) || port < 1 || port > 65_535) {
throw new TypeError(
`${variable} must be a port from 1 to 65535; received ${JSON.stringify(pinned)}`,
);
}
return port;
}
const port = await find();
environment[variable] = String(port);
return port;
}
/**
* The import specifier a generated module at `fromFile` uses for `toFile`,
* both relative to the checkout. A generated module under an output root sits
* deeper than `.generated/` and needs more `../`.
*/
export function moduleSpecifier(fromFile: string, toFile: string): string {
const specifier = path.posix.relative(path.posix.dirname(fromFile), toFile);
return specifier.startsWith(".") ? specifier : `./${specifier}`;
}
+21
View File
@@ -0,0 +1,21 @@
/**
* 1105/15-03. The files `vite build` reads from the repository root, for the
* measurements and tests that copy them into a temporary root and build
* there: scripts/scale/measure-feature-shape-growth.ts (initial JavaScript
* record) and tests/unit/product-feature-selection-build.test.ts
* (`VITE_PRODUCT_FEATURES=none`). Each used to keep its own copy of this list;
* a new local import in vite.config.ts broke both, and both had to be edited
* (7f9a515, 799ab7f). tests/unit/vite-build-inputs.test.ts fails, naming the
* file, when vite.config.ts imports a local file this list does not cover.
*/
export const VITE_BUILD_INPUTS = Object.freeze([
"src",
"public",
"index.html",
"package.json",
"vite.config.ts",
"tsconfig.base.json",
"tsconfig.app.json",
"scripts/lib/run-isolation.ts",
"scripts/lib/vite-module-inventory.ts",
] as const);
+23 -22
View File
@@ -7,6 +7,7 @@ import { gzipSync } from "node:zlib";
import { classifyViteJavascript } from "../lib/classify-vite-bundle.ts";
import { linkFixtureNodeModules } from "../lib/fixture-node-modules.ts";
import { VITE_BUILD_INPUTS } from "../lib/vite-build-inputs.ts";
import { parseTscExtendedDiagnostics, type TscDiagnostics } from "./collect-tsc-diagnostics.ts";
/**
@@ -37,16 +38,6 @@ export const FEATURE_SHAPE_CEILINGS_PATH = "config/scale/feature-shape-ceilings.
const SOURCE_FEATURE = "src/features/reference-feature";
const FEATURES_PER_CONTEXT = 200;
const BUILD_INPUTS = [
"src",
"public",
"index.html",
"package.json",
"vite.config.ts",
"tsconfig.base.json",
"tsconfig.app.json",
"scripts/lib/vite-module-inventory.ts",
] as const;
// Platform-owned names that only happen to contain "reference".
const PLATFORM_TOKENS = [
"REFERENCE_FEATURE_V1",
@@ -110,7 +101,7 @@ async function copyRenamed(from: string, to: string, rename: (text: string) => s
async function createFixture(features: number): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), `feature-shape-${features}-`));
for (const input of BUILD_INPUTS) {
for (const input of VITE_BUILD_INPUTS) {
await mkdir(path.dirname(path.join(root, input)), { recursive: true });
await cp(path.resolve(input), path.join(root, input), { recursive: true });
}
@@ -225,24 +216,34 @@ export async function measureInitialJavascriptCosts(): Promise<InitialJavascript
}
/**
* Fields of the record that no longer describe the build. The total moves
* by tens of bytes with the build id (CI and local builds differ), so it may
* be 1% off; the per-feature and per-context costs are differences of builds
* with the same id but only a few hundred bytes, so 10%; the file count is
* exact.
* 1105/15-02. How far the total may be from the record, in gzip bytes. The
* total moves by tens of bytes with the build id (CI and local builds
* differ: 6 B and 48 B between recorded runs), so it cannot be exact. It
* used to be 1% of the total, 2,029 B, which is more than the room left
* under the budget (1,873 B at 8a44226) and more than one feature (768 B):
* the record and the documents that cite it could claim room that was
* gone. 256 B is above the build id spread and below one feature.
*/
export const INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES = 256;
/**
* Fields of the record that no longer describe the build. The total may be
* INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES off; the per-feature and
* per-context costs are differences of builds with the same id but only a
* few hundred bytes, so 10%; the file count is exact.
*/
export function initialJavascriptRecordDrift(
measured: InitialJavascriptCosts,
record: InitialJavascriptCosts,
): string[] {
const tolerance: Readonly<Record<keyof InitialJavascriptCosts, number>> = {
gzipBytes: 0.01,
const allowed: Readonly<Record<keyof InitialJavascriptCosts, number>> = {
gzipBytes: INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES,
files: 0,
perFeatureGzipBytes: 0.1,
perContextGzipBytes: 0.1,
perFeatureGzipBytes: Math.abs(measured.perFeatureGzipBytes) * 0.1,
perContextGzipBytes: Math.abs(measured.perContextGzipBytes) * 0.1,
};
return (Object.keys(tolerance) as (keyof InitialJavascriptCosts)[])
.filter((field) => Math.abs(record[field] - measured[field]) > Math.abs(measured[field]) * tolerance[field])
return (Object.keys(allowed) as (keyof InitialJavascriptCosts)[])
.filter((field) => Math.abs(record[field] - measured[field]) > allowed[field])
.map((field) => `${field}: record ${record[field]}, build ${measured[field]}`);
}
+153 -15
View File
@@ -3,18 +3,23 @@ import { mkdir, readFile } from "node:fs/promises";
import { cpus, loadavg } from "node:os";
import process from "node:process";
import { chromium, type Browser } from "@playwright/test";
import { chromium, type Browser, type Page } from "@playwright/test";
import {
assertPortUnused,
assertServedRelease,
DEFAULT_LAB_PORT,
DEFAULT_LAB_RUNS,
labBrowserLaunchOptions,
labFeatureRoute,
previewArguments,
summarizeSamples,
} from "./lib/lab-performance.ts";
import { evaluateLabBudget } from "./lib/performance-budgets.ts";
import { ROUTE_REGISTRY } from "../src/features/installed-feature-contracts.ts";
import {
ROUTE_FEATURE_OWNER,
ROUTE_REGISTRY,
} from "../src/features/installed-feature-contracts.ts";
import { labPerformanceArtifactSchema } from "./contracts/release-artifacts.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
@@ -48,6 +53,8 @@ const targetLabel = target.navigationLabel;
if (!targetLabel) {
throw new Error("Performance route must be present in navigation.");
}
// 1105/15-04. A feature route's first entry, timed like the target.
const featureRoute = labFeatureRoute(Object.values(ROUTE_REGISTRY), ROUTE_FEATURE_OWNER);
// 11-07. A server already on the port used to be measured in place of this
// build: vite moved to another port and the gate never noticed.
@@ -77,10 +84,25 @@ async function waitForServer() {
throw new Error("Preview server did not become ready.");
}
type RunMetrics = { lcpMs: number; cls: number; namedInteractionMs: number; eventDurationMs: number | null };
type RunMetrics = {
lcpMs: number;
cls: number;
namedInteractionMs: number;
eventDurationMs: number | null;
/** 1105/15-01. CLS of a direct visit to the target route. */
targetDeepLinkCls: number;
/** 1105/15-04. Click to heading on `featureRoute`, null without one. */
featureRouteInteractionMs: number | null;
};
async function measureOnce(browser: Browser): Promise<RunMetrics> {
// Every run is a cold, isolated context.
type ClickMetrics = Omit<RunMetrics, "targetDeepLinkCls" | "featureRouteInteractionMs">;
/**
* A cold, isolated context with the lab's network and CPU throttling and the
* page-side evidence recorder. `title` is the heading whose arrival after a
* click ends the named interaction.
*/
async function openMeasuredPage(browser: Browser, title: string) {
const context = await browser.newContext({
viewport: { width: 1280, height: 720 },
});
@@ -96,7 +118,7 @@ async function measureOnce(browser: Browser): Promise<RunMetrics> {
connectionType: "cellular4g",
});
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
await page.addInitScript((title: string) => {
await page.addInitScript((headingTitle: string) => {
const evidence: ContractPerformanceEvidence = {
lcpMs: 0,
cls: 0,
@@ -137,20 +159,45 @@ async function measureOnce(browser: Browser): Promise<RunMetrics> {
new MutationObserver((_records, observer) => {
if (evidence.clickAt === null) return;
const found = [...document.querySelectorAll("h1, h2")].some(
(heading) => heading.textContent?.trim() === title,
(heading) => heading.textContent?.trim() === headingTitle,
);
if (found) {
evidence.headingAt = performance.now();
observer.disconnect();
}
}).observe(document, { childList: true, subtree: true, characterData: true });
}, target.title);
}, title);
return { context, page };
} catch (error) {
await context.close();
throw error;
}
}
/** The evidence once the layout-shift observer has delivered its entries. */
async function settledEvidence(page: Page) {
return page.evaluate(async () => {
// Observer callbacks run as tasks after the frame that recorded them.
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
await new Promise((resolve) => setTimeout(resolve, 0));
return (window as ContractPerformanceWindow).__contractPerformance;
});
}
/** From `/`, a click on `route`'s navigation link to its heading. */
async function measureClick(
browser: Browser,
route: Readonly<{ title: string; navigationLabel: string }>,
): Promise<ClickMetrics> {
// Every run is a cold, isolated context.
const { context, page } = await openMeasuredPage(browser, route.title);
try {
await page.goto(baseUrl, { waitUntil: "networkidle" });
// Playwright matches accessible names by substring, so the navigation entry
// "플랫폼 구성" also matched the home page's "플랫폼 구성 보기" call to
// action; `exact` keeps the locator on the navigation link.
await page.getByRole("link", { name: targetLabel, exact: true }).click();
await page.getByRole("heading", { name: target.title }).waitFor();
await page.getByRole("link", { name: route.navigationLabel, exact: true }).click();
await page.getByRole("heading", { name: route.title }).waitFor();
await page.waitForFunction(
() => (window as ContractPerformanceWindow).__contractPerformance?.headingAt !== null,
);
@@ -172,6 +219,28 @@ async function measureOnce(browser: Browser): Promise<RunMetrics> {
}
}
/**
* 1105/15-01. The click run cannot see a shift the target screen makes while
* it fills in: a shift within 500 ms of the click has `hadRecentInput` and
* is left out of CLS by definition, and the lab only opened `/`. The target
* screen used to push its content 21 px after its title (CLS 0.0046) and the
* lab reported 0. A direct visit has no input, so every shift until the
* network is idle after the heading counts.
*/
async function measureTargetDeepLink(browser: Browser): Promise<number> {
const { context, page } = await openMeasuredPage(browser, target.title);
try {
await page.goto(new URL(target.path, baseUrl).href, { waitUntil: "networkidle" });
await page.getByRole("heading", { name: target.title, exact: true }).waitFor();
await page.waitForLoadState("networkidle");
const evidence = await settledEvidence(page);
if (!evidence) throw new Error("Browser performance evidence was not initialized.");
return Number(evidence.cls.toFixed(4));
} finally {
await context.close();
}
}
const load = () => loadavg().map((value) => Math.round(value * 100) / 100);
try {
@@ -183,11 +252,26 @@ try {
const thresholds = JSON.parse(
await readFile("config/performance/budgets.json", "utf8"),
).lab;
const browser = await chromium.launch();
const browser = await chromium.launch(labBrowserLaunchOptions());
try {
const loadBefore = load();
const samples: RunMetrics[] = [];
for (let run = 0; run < runs; run += 1) samples.push(await measureOnce(browser));
for (let run = 0; run < runs; run += 1) {
const click = await measureClick(browser, { title: target.title, navigationLabel: targetLabel });
const targetDeepLinkCls = await measureTargetDeepLink(browser);
const featureClick =
featureRoute === null
? null
: await measureClick(browser, {
title: featureRoute.title,
navigationLabel: featureRoute.navigationLabel!,
});
samples.push({
...click,
targetDeepLinkCls,
featureRouteInteractionMs: featureClick?.namedInteractionMs ?? null,
});
}
const loadAfter = load();
// The served build must not have changed under the runs either.
await assertServedRelease(baseUrl, release);
@@ -196,6 +280,13 @@ try {
const interaction = summarizeSamples(
samples.map((sample) => sample.namedInteractionMs),
);
const deepLinkCls = summarizeSamples(
samples.map((sample) => sample.targetDeepLinkCls),
);
const featureSamples = samples.flatMap((sample) =>
sample.featureRouteInteractionMs === null ? [] : [sample.featureRouteInteractionMs],
);
const featureInteraction = featureSamples.length ? summarizeSamples(featureSamples) : null;
const eventDurations = samples.flatMap((sample) =>
sample.eventDurationMs === null ? [] : [sample.eventDurationMs],
);
@@ -208,7 +299,12 @@ try {
logicalCpus: cpus().length,
loadAverage: { before: loadBefore, after: loadAfter },
},
browser: { name: "chromium", version: await browser.version() },
// 1105/15-05. Classic scrollbars, not Playwright's hidden ones.
browser: {
name: "chromium",
version: await browser.version(),
scrollbars: "visible",
},
viewport: { width: 1280, height: 720 },
network: {
profile: "contract-fast-4g",
@@ -235,12 +331,32 @@ try {
clickEventDurationMs: eventDurations.length
? summarizeSamples(eventDurations)
: null,
// 1105/15-01. A cold direct visit to the target route in each run.
targetDeepLink: {
path: target.path,
clock: "navigation start to network idle after the target heading",
cls: deepLinkCls,
},
// 1105/15-04. The first public navigation route a feature owns, from
// `/` by its navigation link, with the same clock.
featureRoute:
featureRoute === null || featureInteraction === null
? { measured: false, reason: "no installed feature owns a public navigation route" }
: {
measured: true,
routeId: featureRoute.routeId,
path: featureRoute.path,
owner: ROUTE_FEATURE_OWNER[featureRoute.routeId] ?? null,
interactionMs: featureInteraction,
},
},
};
const metrics = {
lcpMs: lcp.median,
cls: cls.median,
namedInteractionMs: interaction.median,
targetDeepLinkCls: deepLinkCls.median,
featureRouteInteractionMs: featureInteraction?.median ?? null,
};
const result = evaluateLabBudget(
{ context: contextMetadata, metrics },
@@ -261,6 +377,20 @@ try {
thresholds,
).passed,
},
// 1105/15-04. The feature route budget can fail.
{
name: "feature-route-over-threshold",
passed: !evaluateLabBudget(
{
context: contextMetadata,
metrics: {
...metrics,
featureRouteInteractionMs: thresholds.featureRouteInteractionMs + 1,
},
},
thresholds,
).passed,
},
];
const passed = result.passed && fixtures.every((fixture) => fixture.passed);
await mkdir("artifacts/performance", { recursive: true });
@@ -280,12 +410,20 @@ try {
if (!passed) {
throw new Error(
`Lab performance failed (median of ${runs}): ${JSON.stringify(metrics)}; ` +
`interaction samples ${interaction.samples.join(",")}`,
`interaction samples ${interaction.samples.join(",")}` +
(featureInteraction === null
? ""
: `; feature route samples ${featureInteraction.samples.join(",")}`),
);
}
process.stdout.write(
`Lab performance: PASS, median of ${runs} (LCP ${metrics.lcpMs}ms, CLS ${metrics.cls}, interaction ${metrics.namedInteractionMs}ms ` +
`[${interaction.min}-${interaction.max}])\n`,
`[${interaction.min}-${interaction.max}], ${target.path} direct CLS ${metrics.targetDeepLinkCls} ` +
`[${deepLinkCls.min}-${deepLinkCls.max}], ` +
(featureRoute === null || featureInteraction === null
? "no feature route measured)\n"
: `feature route ${featureRoute.routeId} ${featureInteraction.median}ms ` +
`[${featureInteraction.min}-${featureInteraction.max}])\n`),
);
} finally {
await browser.close();
+29 -23
View File
@@ -11,6 +11,7 @@ import path from "node:path";
import { ROUTE_FEATURE_OWNER } from "../src/features/installed-feature-contracts.ts";
import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts";
import { productFeatureResidue } from "./lib/feature-residue.ts";
import { isProductionModulePath } from "./lib/risk-coverage.ts";
import {
createRemovalFixtureRoot,
@@ -28,6 +29,7 @@ import {
sealRemovalFixtureRepository,
type RemovalCheck,
} from "./lib/removal-fixture.ts";
import { REMOVABLE_TEMPLATE_FEATURES } from "./lib/removable-template-features.ts";
/**
* 09-07 (D-10). Removes one installed feature, `--feature=<id>` (default: the
@@ -48,25 +50,19 @@ type FeatureExtras = Readonly<{
residue: RegExp;
}>;
// The sample's own files and scripts outside its folders are declared with
// the other removable template features, which verify:documentation reads too.
const REFERENCE_SAMPLE = REMOVABLE_TEMPLATE_FEATURES.find(
(feature) => feature.featureId === "reference-feature",
);
if (REFERENCE_SAMPLE === undefined) {
throw new Error("scripts/lib/removable-template-features.ts does not declare reference-feature");
}
const SAMPLE_EXTRAS: Readonly<Record<string, FeatureExtras>> = Object.freeze({
"reference-feature": Object.freeze({
// 0929/10-02. The HTTP scenario catalog (tests/mocks) and the negative
// type fixtures of the feature APIs run on the test contracts, so they are
// platform checks and stay (commonTestPaths below).
paths: [
"tests/component/product-feature-switch.test.tsx",
"tests/e2e/reference-form.spec.ts",
"tests/e2e/reference-route.spec.ts",
"tests/e2e/reference-save.spec.ts",
// 11-04: the growth measurement copies this sample feature.
"tests/unit/feature-shape-growth.test.ts",
"scripts/scale/measure-feature-shape-growth.ts",
"config/scale/feature-shape-growth.json",
"config/scale/feature-shape-ceilings.json",
],
ciScripts: [
"test:reference-feature",
],
paths: REFERENCE_SAMPLE.extraPaths,
ciScripts: REFERENCE_SAMPLE.scripts,
evidencePathFragments: [
"reference-feature.xml",
],
@@ -137,7 +133,11 @@ const isSample = featureId in SAMPLE_EXTRAS;
const commonTestPaths = [
"tests/unit/external-contract-runtime.test.ts",
"tests/unit/http-execution-v3.test.ts",
// 1105/10-01. MAX_RETRY_ATTEMPTS and REQUEST_TIMEOUT_MS reach the executor
// (`createRuntimeContractHttpExecutor`), and a session being recovered waits
// on a session-required route. Before, only sample tests held these rules.
"tests/unit/runtime-adapters.test.ts",
"tests/unit/session-route-access.test.ts",
"tests/integration/http-execution-v3-observability.test.ts",
// 0929/10-02. HTTP scenario evidence (FE-GATE-007) and the feature API
// negative type fixtures (FE-GATE-003) run on the test contracts.
@@ -415,14 +415,20 @@ try {
await regenerateRemovalFixtureWorkflow(fixtureRoot);
const residue: string[] = [];
for (const root of ["src", "tests"]) {
for (const file of await filesBelow(path.join(fixtureRoot, root))) {
const relative = path.relative(fixtureRoot, file);
const content = await readFile(file, "utf8");
if (extras.residue.test(`${relative}\n${content}`)) {
residue.push(relative);
if (isSample) {
for (const root of ["src", "tests"]) {
for (const file of await filesBelow(path.join(fixtureRoot, root))) {
const relative = path.relative(fixtureRoot, file);
const content = await readFile(file, "utf8");
if (extras.residue.test(`${relative}\n${content}`)) {
residue.push(relative);
}
}
}
} else {
// 1105/16-04. Template tests use example feature IDs as data; only what
// still points at the removed feature counts (scripts/lib/feature-residue.ts).
residue.push(...(await productFeatureResidue(fixtureRoot, featureId, located.directory)));
}
const missingCommonTests: string[] = [];
+104 -21
View File
@@ -1,3 +1,4 @@
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdir, readdir, readFile } from "node:fs/promises";
import { dirname, join, matchesGlob, normalize, resolve } from "node:path/posix";
@@ -7,6 +8,10 @@ import { RETIRED_GATE_IDS } from "./contracts/ci-gates.ts";
import { documentationReviewArtifactSchema } from "./contracts/release-artifacts.ts";
import { RUNTIME_OVERRIDES } from "./generate-runtime-config.ts";
import { MANUAL_A11Y_ROUTE_IDS } from "./lib/manual-a11y-evidence.ts";
import {
REMOVABLE_TEMPLATE_FEATURES,
removableTemplateFeaturePaths,
} from "./lib/removable-template-features.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
/**
@@ -182,6 +187,25 @@ const gateIds = new Set([
).gates.map((gate) => gate.id),
...RETIRED_GATE_IDS,
]);
// 1105/14-01. A copy may delete the template features listed in
// scripts/lib/removable-template-features.ts, and the CHANGELOG tells
// tech-log to delete the example screens. The documents are the template's:
// a product that edited them to drop the feature's paths would conflict on
// every sync. While a feature is installed (its feature-module.ts exists),
// its paths and scripts are checked like any other; once it is not, they are
// not drift. tech-log keeps the reference sample's folder with its contracts
// but without its module, screens and tests (CHANGELOG "먼저 할 일" 1). A
// misspelt feature folder is not on the list and still fails.
const removedTemplateFeatures = REMOVABLE_TEMPLATE_FEATURES.filter(
(feature) => !exists(`src/features/${feature.featureId}/feature-module.ts`),
);
const removedTemplateFeaturePaths = removedTemplateFeatures.flatMap((feature) =>
removableTemplateFeaturePaths(feature),
);
const removedTemplateFeatureScripts = new Set(removedTemplateFeatures.flatMap((feature) => feature.scripts));
function missingScript(name: string): boolean {
return !scripts.has(name) && !removedTemplateFeatureScripts.has(name);
}
// Generated output is what git ignores, so a document may name it before a
// run has written it.
const ignorePatterns = (await readFile(join(rootDirectory, ".gitignore"), "utf8").catch(() => ""))
@@ -207,12 +231,58 @@ const deletedHistory = [
.flatMap(([, cell = ""]) => [...cell.matchAll(/`([^`]+)`/gu)].map(([, entry = ""]) => entry.replace(/\/$/u, "")))
.filter((entry) => !exists(entry));
// 1103/12-05. The paired templates a document may name (`<name>/docs/…`) or
// link (`../../../<name>/…`). They are looked up beside the checkout the
// documents are read from; where none is checked out (CI, a nested worktree)
// the reference is reported as not verified instead of passing silently.
const SIBLING_REPOSITORIES = new Set(["clean-architecture-backend-template"]);
// 1103/12-05, 1105/12-02. The paired templates a document may name
// (`<name>/docs/…`) or link (`../../../<name>/…`) are the ones
// config/contracts/backend-contract-pin.json pins. It is read with the
// documents, since it says which commit they describe. A reference is looked
// up in the tree of the pinned commit, read from the object store of the
// checkout beside the documents, never from that checkout's working tree or
// HEAD: those differ per machine, and the same commit failed on one whose
// sibling was months behind with uncommitted changes and passed elsewhere.
// Where the checkout or the pinned commit is missing (CI, a nested worktree, a
// stale clone) the reference is reported as not verified. A link that leaves
// the repository for anything else is broken (a misspelled repository too).
const PAIRED_PIN = "config/contracts/backend-contract-pin.json";
const pairedPins = new Map<string, string>();
const pairedPin = await readFile(PAIRED_PIN, "utf8").catch(() => null);
if (pairedPin !== null) {
const { backend } = JSON.parse(pairedPin) as { backend: { repository: string; commit: string } };
pairedPins.set(backend.repository, backend.commit);
}
const siblingsRoot = resolve(process.cwd(), "..");
type PairedTree = Readonly<{ paths: ReadonlySet<string> }> | Readonly<{ unverified: string }>;
const pairedTrees = new Map<string, PairedTree>();
function readPairedTree(repository: string, commit: string): PairedTree {
const checkout = resolve(siblingsRoot, repository);
if (!existsSync(join(checkout, ".git"))) return { unverified: `no checkout at ${checkout}` };
// The checkout's own repository only: a GIT_DIR set by a hook would point
// git at another one.
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_")));
const git = (...args: string[]) =>
spawnSync("git", ["-C", checkout, ...args], { encoding: "utf8", env, maxBuffer: 64 * 1024 * 1024 });
if (git("cat-file", "-e", `${commit}^{commit}`).status !== 0) {
const head = git("rev-parse", "--short=12", "HEAD");
return {
unverified: `${checkout} at HEAD ${head.status === 0 ? head.stdout.trim() : "(unreadable)"} does not have the pinned commit; fetch it to check these`,
};
}
const listing = git("ls-tree", "-r", "-t", "-z", "--name-only", commit);
if (listing.status !== 0) return { unverified: `git ls-tree failed in ${checkout}: ${listing.stderr.trim()}` };
return { paths: new Set(listing.stdout.split("\0").filter((entry) => entry !== "")) };
}
/** Whether `reference` (`../<name>/<path>`) is in the pinned tree, or null when it cannot be checked here. */
function pairedReferenceExists(reference: string): boolean | null {
const [, repository = "", ...inside] = reference.split("/");
const commit = pairedPins.get(repository);
if (commit === undefined) return false;
let tree = pairedTrees.get(repository);
if (tree === undefined) {
tree = readPairedTree(repository, commit);
pairedTrees.set(repository, tree);
}
if ("unverified" in tree) return null;
return inside.length === 0 || tree.paths.has(inside.join("/"));
}
// A backtick span is a path when it starts at a top-level entry, at an entry
// beside the document or at a paired repository; line numbers and anchors are
@@ -223,13 +293,13 @@ function namedPath(token: string, document: string): string | null {
if (!candidate.includes("/") || candidate.startsWith("/") || /[\s*<>{}$()|]|\.\.\./u.test(candidate)) return null;
const first = candidate.split("/")[0] ?? "";
if (topLevelEntries.has(first)) return candidate;
if (SIBLING_REPOSITORIES.has(first)) return `../${candidate}`;
if (pairedPins.has(first)) return `../${candidate}`;
return first !== "." && first !== ".." && exists(join(dirname(document), first))
? join(dirname(document), candidate)
: null;
}
// A link that leaves the repository is kept (`../…`); the caller looks it up
// beside the checkout.
// in the paired repositories.
function linkedPath(target: string, document: string): string | null {
if (/^(?:[a-z][a-z+.-]*:|#)/iu.test(target)) return null;
return normalize(join(dirname(document), target.replace(/#.*$/u, "")));
@@ -304,33 +374,28 @@ for (const document of contractDocuments) {
if (file === null) continue;
const trimmed = file.replace(/\/$/u, "");
if (trimmed.startsWith("../")) {
// Outside this repository: the first folder past the `..` steps is the
// paired checkout. Without it the reference cannot be checked here.
const segments = trimmed.split("/");
const checkout = segments.slice(0, segments.findIndex((segment) => segment !== "..") + 1).join("/");
const relativeToSiblings = trimmed.replace(/^\.\.\//u, "");
if (!existsSync(resolve(siblingsRoot, checkout.replace(/^\.\.\//u, "")))) {
unverifiedLinks.add(trimmed);
} else if (!existsSync(resolve(siblingsRoot, relativeToSiblings))) {
missingPaths.add(trimmed);
}
// Outside this repository: `../<paired repository>/<path at its pin>`.
const found = pairedReferenceExists(trimmed);
if (found === null) unverifiedLinks.add(trimmed);
else if (!found) missingPaths.add(trimmed);
continue;
}
if (
!exists(trimmed) &&
!NOT_CREATED.has(trimmed) &&
!generated(trimmed) &&
!deletedHistory.some((entry) => trimmed === entry || trimmed.startsWith(`${entry}/`))
!deletedHistory.some((entry) => trimmed === entry || trimmed.startsWith(`${entry}/`)) &&
!removedTemplateFeaturePaths.some((entry) => trimmed === entry || trimmed.startsWith(`${entry}/`))
) {
missingPaths.add(trimmed);
}
}
const missingScripts = new Set<string>();
for (const [, name = ""] of text.matchAll(/(?:corepack pnpm|`pnpm) (?:run )?([a-z](?:[\w:-]*\w)?)/gu)) {
if (!PNPM_COMMANDS.has(name) && !scripts.has(name)) missingScripts.add(name);
if (!PNPM_COMMANDS.has(name) && missingScript(name)) missingScripts.add(name);
}
for (const [, name = ""] of text.matchAll(/`([a-z][\w-]*:[\w:-]*\w)(?=[` ])/gu)) {
if (scriptPrefixes.has(name.split(":")[0]) && !scripts.has(name)) missingScripts.add(name);
if (scriptPrefixes.has(name.split(":")[0]) && missingScript(name)) missingScripts.add(name);
}
documentReferences.push({
path: document,
@@ -416,6 +481,15 @@ if (!passed) {
);
}
}
if (documentReferences.some((entry) => entry.missingPaths.some((file) => file.startsWith("../")))) {
const checked = [...pairedTrees]
.filter(([, tree]) => "paths" in tree)
.map(([repository]) => `${repository} ${pairedPins.get(repository)?.slice(0, 12)}`);
process.stderr.write(
`A path outside this repository must be in a repository ${PAIRED_PIN} pins, at the pinned commit` +
`${checked.length > 0 ? ` (looked up in ${checked.join(", ")})` : ""}\n`,
);
}
if (!reportDigestValid) {
process.stderr.write(
`${ledger.evidenceReport.repoPath} does not contain the ledger's canonicalSha256\n`,
@@ -436,11 +510,20 @@ if (!passed) {
);
process.exit(1);
}
if (removedTemplateFeatures.length > 0) {
process.stdout.write(
`Documentation readiness: paths and scripts of removed template features not required: ` +
`${removedTemplateFeatures.map((feature) => feature.featureId).join(", ")}\n`,
);
}
const unverified = documentReferences.flatMap((entry) => entry.unverifiedLinks);
if (unverified.length > 0) {
const reasons = [...pairedTrees].flatMap(([repository, tree]) =>
"unverified" in tree ? [`${repository} pinned at ${pairedPins.get(repository)?.slice(0, 12)}: ${tree.unverified}`] : [],
);
process.stdout.write(
`Documentation readiness: ${unverified.length} reference(s) into paired repositories not verified ` +
`(no checkout beside ${process.cwd()}): ${[...new Set(unverified)].join(", ")}\n`,
`(${reasons.join("; ")}): ${[...new Set(unverified)].join(", ")}\n`,
);
}
process.stdout.write("Documentation readiness: PASS_SCOPED\n");
+3 -5
View File
@@ -7,8 +7,7 @@ import {
checkPublicServiceWorkers,
classifyLiveHostingBaseUrl,
hostingVerdict,
probeAssetContentTypes,
probeLiveRelease,
probeLiveHosting,
releaseIdentity,
shipsServiceWorker,
type HostingMode,
@@ -111,13 +110,12 @@ if (liveTarget?.passed && !slotEmpty) {
runtimeConfig: await readFile(path.join(distRoot, "config.json"), "utf8"),
indexHtml: await readFile(path.join(distRoot, "index.html"), "utf8"),
};
const probed = await probeLiveRelease(liveTarget.url, paths, candidate, {
// 1103/06-03, 1105/06-02. Release surfaces and every precached asset type.
const probed = await probeLiveHosting(liveTarget.url, paths, candidate, distFiles, {
alpnProtocols: strings(recordValue(cachePolicy.transport).alpnProtocols),
});
responses = probed.responses;
probeResults.push(...probed.results);
// 1103/06-03. The worker needs every precached asset kind typed exactly.
probeResults.push(...(await probeAssetContentTypes(liveTarget.url, distFiles)));
} else if (liveTarget && !liveTarget.passed) {
mode = "invalid-live";
probeResults.push({
+14 -7
View File
@@ -1,19 +1,26 @@
import { mkdir } from "node:fs/promises";
import { automatedA11yArtifactSchema } from "./contracts/release-artifacts.ts";
import {
automatedA11yReport,
readA11yNotCheckedRoutes,
} from "./lib/a11y-data-state.ts";
import { MANUAL_A11Y_ROUTE_IDS } from "./lib/manual-a11y-evidence.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
await mkdir("artifacts/tests", { recursive: true });
// 1103/11-01. Routes the spec scanned only on their failure state are not
// reported as passed.
const notChecked = await readA11yNotCheckedRoutes(MANUAL_A11Y_ROUTE_IDS);
await writeValidatedJsonArtifact({
path: "artifacts/tests/a11y.json",
schema: automatedA11yArtifactSchema,
value: {
schemaVersion: 1,
value: automatedA11yReport({
routeIds: MANUAL_A11Y_ROUTE_IDS,
notChecked,
generatedAt: new Date().toISOString(),
scope: MANUAL_A11Y_ROUTE_IDS,
threshold: { critical: 0, serious: 0 },
automatedStatus: "passed",
manualReview: "see artifacts/tests/a11y-manual/report.json",
},
}),
});
for (const { routeId, reason } of notChecked) {
process.stdout.write(`a11y: ${routeId} not checked in its own state (${reason})\n`);
}
@@ -490,12 +490,20 @@ export function createPublicResponseCacheAdapter(
return browserDataSuccess(summaryFromMarker(marker.value));
}
if (verified.kind === "UNKNOWN") {
// Abort or an unreadable candidate is never stage success and
// never silently deletes an owned candidate. 2026-11-01
// 02-03: the verdict is shared with activation, so the
// failure is re-labelled as this stage call's own.
// Abort or a Cache Storage that cannot be asked is never
// stage success and never silently deletes an owned
// candidate. 2026-11-01 02-03: the verdict is shared with
// activation, so the failure is re-labelled as this stage
// call's own.
return rebaseFailure(verified.failure.error, "CACHE_STAGE");
}
// 1105/02-02. A damaged entry, and also one whose stored body
// cannot be read, is written again below. An entry that stays
// unreadable until it is rewritten had no other way back: the
// retry it was told to make met the same entry, and a rollback
// target that cleanup keeps could never be activated again.
// Writing digest-verified bytes over it deletes nothing, so a
// release that is serving traffic keeps serving.
}
}
@@ -684,6 +692,17 @@ export function createPublicResponseCacheAdapter(
"CACHE_ACTIVATE",
);
}
if (candidate.kind === "UNREADABLE") {
// 1105/02-02. Still not reported as damage, but the way out is
// to stage the same manifest again, which rewrites the entry.
return rebaseFailure(
Object.freeze({
...candidate.failure.error,
recovery: "REHYDRATE" as const,
}),
"CACHE_ACTIVATE",
);
}
if (candidate.kind === "REPAIRABLE") {
return browserDataFailure(
"INTEGRITY_FAILED",
@@ -1077,7 +1096,13 @@ type ReleaseCandidateVerdict =
| Readonly<{ kind: "VERIFIED" }>
/** An exact, owned entry is missing or no longer matches the manifest. */
| Readonly<{ kind: "REPAIRABLE" }>
/** Abort or an unreadable candidate: never success, never a silent delete. */
/**
* 1105/02-02. An entry is there but reading its stored body failed
* (UNAVAILABLE, NOT_READABLE, ...). That says nothing about the bytes, so
* it is no damage; staging the same manifest writes the entry again.
*/
| Readonly<{ kind: "UNREADABLE"; failure: BrowserFailureResult }>
/** Abort or a failed lookup: never success, never a silent delete. */
| Readonly<{ kind: "UNKNOWN"; failure: BrowserFailureResult }>;
const REPAIRABLE_READ_CODES: ReadonlySet<string> = new Set([
@@ -1134,14 +1159,15 @@ async function verifyReleaseCandidate(
);
if (!verified.ok) {
// 2026-11-03 02-02. Only a verdict about the stored bytes or headers is
// damage. A body read that failed (UNAVAILABLE, NOT_READABLE, ABORTED)
// says nothing about them, so it stays unknown and is retried.
return REPAIRABLE_READ_CODES.has(verified.error.code)
? Object.freeze({ kind: "REPAIRABLE" as const })
: Object.freeze({
kind: "UNKNOWN" as const,
failure: asFailure(verified),
});
// damage. A body read that failed (UNAVAILABLE, NOT_READABLE) says
// nothing about them (1105/02-02: UNREADABLE); an abort is unknown.
if (REPAIRABLE_READ_CODES.has(verified.error.code)) {
return Object.freeze({ kind: "REPAIRABLE" as const });
}
const failure = asFailure(verified);
return verified.error.code === "ABORTED" || signal?.aborted
? Object.freeze({ kind: "UNKNOWN" as const, failure })
: Object.freeze({ kind: "UNREADABLE" as const, failure });
}
}
return Object.freeze({ kind: "VERIFIED" as const });
+13 -1
View File
@@ -4,6 +4,7 @@ import {
type FailureKind,
type ValidationIssue,
} from "../../contracts/errors.ts";
import { PLATFORM_CODES_POSSIBLY_AFTER_WRITE } from "../../contracts/external-contract-runtime.ts";
import { z } from "../../contracts/zod.ts";
/**
@@ -144,6 +145,10 @@ export function readFailureEnvelope(
* answer table. Only the status and code together count. `reason` is the
* diagnostics name of an idempotency refusal, named for what is wrong on
* this side.
*
* 1105/03-02. And the edge rate limiter's two 503s (§4): its interceptor
* answers in `preHandle`, before the controller runs, so the command did not
* run whatever the operation's own classifier says.
*/
export type IdempotencyRefusalReason =
| "IDEMPOTENT_REQUEST_MISMATCH"
@@ -169,6 +174,11 @@ const REFUSED_BEFORE_WRITE: Readonly<
status: 422,
reason: "IDEMPOTENT_REQUEST_MISMATCH",
}),
// §4. The rate-limit store did not answer (retryable, with Retry-After),
// or the rate-limit provider does not match the contract. Both come from
// RateLimitInterceptor.preHandle, before any handler.
RATE_LIMIT_UNAVAILABLE: Object.freeze({ status: 503 }),
RATE_LIMIT_INCOMPATIBLE: Object.freeze({ status: 503 }),
});
/**
@@ -312,7 +322,8 @@ export function unknownEffectReason(
* (`commandEffect.refusedBeforeWrite`). Composition already refuses an
* idempotency code in that list; this is the runtime's own fail-close for an
* executor called without composition. The table's own codes keep its status
* rule.
* rule. 1105/03-01. So do the platform codes contract 6.1 reads as possibly
* raised after the write.
*/
function declaredBeforeWrite(
code: string,
@@ -322,6 +333,7 @@ function declaredBeforeWrite(
declared !== undefined &&
!Object.hasOwn(REFUSED_BEFORE_WRITE, code) &&
!/^IDEMPOTEN(?:T|CY)_/.test(code) &&
!PLATFORM_CODES_POSSIBLY_AFTER_WRITE.includes(code) &&
declared.includes(code)
);
}
+94 -27
View File
@@ -15,10 +15,13 @@ import {
} from "../platform/abortable-operation.ts";
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
import {
envelopeFailureEffect,
envelopeFailureReading,
gatewayFailureOr,
maybeAppliedAnswerRows,
readFailureEnvelope,
readSuccessEnvelope,
refusedBeforeWriteRows,
type EnvelopeError,
} from "./backend-envelope.ts";
import {
@@ -35,7 +38,8 @@ import type { AuthOperationContext } from "./http-execution-v3.ts";
/**
* 2026-11-03 01-01. A client for the paired backend Fileserver's multipart
* single upload, `POST /v1/files` (clean-architecture-backend-template
* `bbe944bd`, docs/fileserver/http-contract.md; Envelope and idempotency in
* `45d2a478`, the commit config/contracts/backend-contract-pin.json pins;
* docs/fileserver/http-contract.md and its code; Envelope and idempotency in
* docs/web/http-contract.md §1–§2).
*
* The paired backend removed presigned and direct multipart transfer on
@@ -48,7 +52,8 @@ import type { AuthOperationContext } from "./http-execution-v3.ts";
* gives (`FileserverByteSource` is its shape), so no `File` or `Blob` crosses
* into this adapter. Its bytes are read
* once into the multipart body, at most `maxFileBytes` of them; a file that
* declares a larger size is refused before reading.
* declares a larger size is refused before reading, and an empty file is
* never sent.
*
* One request per call. The client never resends: the body is the whole
* file, and only the caller knows whether to spend that again. It keeps the
@@ -59,6 +64,19 @@ import type { AuthOperationContext } from "./http-execution-v3.ts";
export type FileserverFileState = "READY" | "UPLOADED" | "VERIFYING" | "QUARANTINED";
/**
* 1105/01-01. The states the backend answers `POST /v1/files` with. It
* verifies synchronously and answers 202 for every state but `READY`
* (`FileUploadController#created`), so a file its verifiers refused, for a
* reason other than malware, comes back as 202 `REJECTED`. That one is not a
* stored file: the client returns it as a `FILE_REJECTED` failure.
*/
type FileserverAnswerState = FileserverFileState | "REJECTED";
type FileserverAnswer = Readonly<
Omit<FileserverUploadedFile, "state"> & { state: FileserverAnswerState }
>;
/**
* The bytes to send: structurally the browser-file-storage port's
* `FileByteSource`, which a product passes as it is. Written here instead of
@@ -75,7 +93,12 @@ export type FileserverByteSource = Readonly<{
/** The stored file, as the backend's `UploadedFileResponse` describes it. */
export type FileserverUploadedFile = Readonly<{
fileId: string;
/** `READY` with 201. Anything else came with 202: not readable yet. */
/**
* `READY` with 201: readable now. With 202 the file is not readable:
* `VERIFYING` means a verifier asked to check again later, and `QUARANTINED`
* means it is held until an operator decides, so a screen must not wait for
* it as for a check in progress.
*/
state: FileserverFileState;
filename: string;
mediaType: string;
@@ -92,7 +115,7 @@ export type FileserverUploadRequest = Readonly<{
mediaType?: string;
/**
* Sent as `Idempotency-Key`. After a `MAYBE_APPLIED` failure, resend with
* the same key and never a new one. At `bbe944bd` the backend runs
* the same key and never a new one. At `45d2a478` the backend runs
* `POST /v1/files` without its idempotency executor, so the key protects
* only a deployment that routes the upload through it.
*/
@@ -153,30 +176,49 @@ const MAX_FILENAME_LENGTH = 255;
/**
* Backend `UploadFileApplicationUseCase` cancels the upload on every failure
* except an ambiguous completion, and the Fileserver contract marks a failure
* that may already have taken effect with `details.ambiguous`. So a 4xx
* Envelope is NOT_APPLIED unless it says otherwise. A 5xx stays MAYBE_APPLIED
* except these codes, which the backend raises before the file is published
* (`FileserverErrorCode`; 503 IDEMPOTENCY_UNAVAILABLE is web contract §2).
* Recheck both lists when the backend SHA above moves.
* its worker raises except an ambiguous completion, and the Fileserver
* contract marks a failure that may already have taken effect with
* `details.ambiguous`. So a 4xx Envelope is NOT_APPLIED unless it says
* otherwise. A 5xx stays MAYBE_APPLIED except these codes, which the worker
* raises before the file is published (`FileserverErrorCode`,
* `AtomicMoveContentPublisher`). Recheck the list when the pinned backend
* commit moves; contract §6.1 says why the 4xx reading differs from its
* fileserver row.
*
* 1105/01-02. 504 TRANSFER_TIMEOUT is not here. The waiting servlet thread
* raises it when `await-seconds` runs out, whatever stage the worker is in
* (`BlockingTransferExecutor`), and the interrupt that follows does not stop a
* publish rename or the READY commit. The file may still become READY, so a
* resend can store it twice.
*/
const NOT_APPLIED_5XX_CODES: ReadonlySet<string> = new Set([
"PARTIAL_WRITE",
"ATOMIC_PUBLISH_UNSUPPORTED",
"STORAGE_UNAVAILABLE",
"TRANSFER_TIMEOUT",
"STORAGE_FULL",
"IDEMPOTENCY_UNAVAILABLE",
]);
/** Answers that may have taken effect whatever their status. */
const MAYBE_APPLIED_CODES: ReadonlySet<string> = new Set([
"AMBIGUOUS_COMPLETION",
// Web contract §2: resend with the same key, never a new one.
"IDEMPOTENT_IN_FLIGHT",
"IDEMPOTENCY_COMPLETION_UNKNOWN",
"IDEMPOTENCY_RECOVERY_REQUIRED",
]);
/**
* 1105/01-02. The web contract's own answers (idempotency §2, and the other
* codes the V3 table lists) read as the V3 executor reads them, so the same
* backend code has one verdict in this repository. The idempotency codes are
* taken by prefix: one the table does not list yet stays MAYBE_APPLIED.
*/
function sharedAnswerEffect(
status: number,
error: EnvelopeError,
): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined {
const listed = (rows: readonly Readonly<{ code: string; status: number }>[]) =>
rows.some((row) => row.code === error.code && row.status === status);
if (
!/^IDEMPOTEN(?:T|CY)_/u.test(error.code) &&
!listed(refusedBeforeWriteRows()) &&
!listed(maybeAppliedAnswerRows())
) {
return undefined;
}
return envelopeFailureEffect(status, error) ?? "MAYBE_APPLIED";
}
export function createFileserverUploadClient(
dependencies: FileserverUploadClientDependencies,
@@ -191,7 +233,7 @@ export function createFileserverUploadClient(
const uploadedFileSchema = z
.object({
fileId: z.string().regex(UUID),
state: z.enum(["READY", "UPLOADED", "VERIFYING", "QUARANTINED"]),
state: z.enum(["READY", "UPLOADED", "VERIFYING", "QUARANTINED", "REJECTED"]),
filename: z.string().min(1).max(1_024),
mediaType: z.string().min(1).max(255),
size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
@@ -426,6 +468,11 @@ async function readMultipartBody(
// The server's code for the same refusal, so a feature handles one code.
return failure("VALIDATION_REJECTED", "FILE_TOO_LARGE", notSent);
}
// 1105/01-01. The backend's default verifier chain rejects empty content
// first (`LengthVerifier`), and that answer is a 202 `REJECTED` with no
// reason. Refused here instead, under a code that says why.
const empty = () => failure("VALIDATION_REJECTED", "FILE_EMPTY", notSent);
if (declared === 0) return empty();
const random = new Uint8Array(16);
crypto.getRandomValues(random);
const boundary = `----FileserverUpload${[...random]
@@ -485,6 +532,7 @@ async function readMultipartBody(
return failure("REQUEST_ABORTED", "REQUEST_ABORTED", notSent);
}
if (declared !== null && fileBytes !== declared) return changed();
if (fileBytes === 0) return empty();
let bytes: Uint8Array<ArrayBuffer>;
if (sized) {
bytes = sized;
@@ -564,7 +612,7 @@ async function readAnswer(
response: Response,
attempt: AbortableOperation,
settings: Settings,
uploadedFileSchema: z.ZodType<FileserverUploadedFile>,
uploadedFileSchema: z.ZodType<FileserverAnswer>,
sentBytes: number,
): Promise<Result<FileserverUploadedFile, AppFailure>> {
const status = response.status;
@@ -629,23 +677,34 @@ async function readAnswer(
) {
return unreadable("SCHEMA_MISMATCH", "UPLOADED_FILE_INVALID");
}
const { state, ...file } = parsed.data;
if (state === "REJECTED") {
// 1105/01-01. The file is the user's to replace, as with a 413, 415 or
// 422 refusal. The backend keeps the record unpublished and schedules
// its bytes for removal, so nothing usable was stored.
return failure("VALIDATION_REJECTED", "FILE_REJECTED", {
httpStatus: status,
effect: "NOT_APPLIED",
});
}
return Object.freeze({
ok: true as const,
value: Object.freeze({ ...parsed.data }),
value: Object.freeze({ ...file, state }),
});
}
if (status < 400) return unreadable("ENVELOPE_MISMATCH", "STATUS_UNEXPECTED");
const envelope = readFailureEnvelope(json);
if (!envelope.ok) return unreadable("ENVELOPE_MISMATCH", "ENVELOPE_INVALID");
return envelopeFailure(status, envelope.value, response, settings);
return envelopeFailure(status, envelope, response, settings);
}
function envelopeFailure(
status: number,
error: EnvelopeError,
envelope: Readonly<{ value: EnvelopeError; traceId?: string }>,
response: Response,
settings: Settings,
): Result<never, AppFailure> {
const error = envelope.value;
const effect = fileserverFailureEffect(status, error);
const retryAfterMs = parseRetryAfterDelay(
response.headers.get("retry-after"),
@@ -673,6 +732,9 @@ function envelopeFailure(
...(reading.validationIssues === undefined
? {}
: { validationIssues: reading.validationIssues }),
// 1105/01-03. The backend's `meta.traceId`, as the V3 executor carries it
// (1103/03-06), so support can find this upload in the server logs.
...(envelope.traceId === undefined ? {} : { traceId: envelope.traceId }),
});
// `retryable` in the Envelope is the server's decision for this answer and
// can only narrow the client's.
@@ -687,7 +749,10 @@ function envelopeFailure(
});
}
/** See `NOT_APPLIED_5XX_CODES`. */
/**
* In this order: an ambiguous answer, then the web contract's own answers
* (`sharedAnswerEffect`), then the Fileserver reading (`NOT_APPLIED_5XX_CODES`).
*/
export function fileserverFailureEffect(
status: number,
error: EnvelopeError,
@@ -698,7 +763,9 @@ export function fileserverFailureEffect(
typeof details === "object" &&
!Array.isArray(details) &&
(details as Readonly<Record<string, unknown>>)["ambiguous"] === true;
if (ambiguous || MAYBE_APPLIED_CODES.has(error.code)) return "MAYBE_APPLIED";
if (ambiguous || error.code === "AMBIGUOUS_COMPLETION") return "MAYBE_APPLIED";
const shared = sharedAnswerEffect(status, error);
if (shared !== undefined) return shared;
if (status >= 400 && status < 500) return "NOT_APPLIED";
return NOT_APPLIED_5XX_CODES.has(error.code) ? "NOT_APPLIED" : "MAYBE_APPLIED";
}
@@ -1,5 +1,9 @@
import type { AuthSessionPort } from "../../application/ports/auth-session-port.ts";
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
import {
isScopeParticipantLabel,
safeErrorKind,
} from "../../contracts/diagnostics.ts";
import type { QueryInvalidationCoordinator } from "../../contracts/query-invalidation.ts";
import {
createRuntimeIdentityRegistry,
@@ -20,6 +24,11 @@ import type {
export type ScopeResetParticipant = Readonly<{
/** Lower runs earlier; the §10.6 step number is used as the rank. */
order: number;
/**
* 1105/02-01. Names the participant in the diagnostic a failed close
* records (`scope_participant`). Use a lowercase kebab-case token
* (`isScopeParticipantLabel`); any other is left out of that record.
*/
label: string;
close(): void | Promise<void>;
}>;
@@ -32,10 +41,20 @@ export type ServerStateScopeDependencies = Readonly<{
session: Pick<AuthSessionPort, "subscribe"> &
Partial<Pick<AuthSessionPort, "getState" | "getSubject">>;
queryInvalidation: Pick<QueryInvalidationCoordinator, "resetLocal">;
/** Hears about an authenticated session that could not name its subject. */
/**
* Hears about an authenticated session that could not name its subject, and
* about every step of a reset that failed (1105/02-01).
*/
diagnostics?: DiagnosticsPort;
tokenFactory?: () => string;
participants?: readonly ScopeResetParticipant[];
/**
* The closers, or a function read at each reset (1105/02-01): composition
* that learns some of them only after the runtime exists, such as the
* product's, passes the function instead of wrapping them in one closer.
*/
participants?:
| readonly ScopeResetParticipant[]
| (() => readonly ScopeResetParticipant[]);
activateNextGeneration?: () => void | Promise<void>;
}>;
@@ -46,9 +65,11 @@ export function createServerStateScopeRuntime(
const lifecycleListeners = new Set<
(event: ClientScopeLifecycleEvent) => void
>();
const participants = [...(dependencies.participants ?? [])].sort(
(left, right) => left.order - right.order,
);
const listParticipants = dependencies.participants;
const fixedParticipants =
typeof listParticipants === "function"
? undefined
: orderParticipants(listParticipants ?? []);
let generation = 1;
let identities = newIdentityRegistry(dependencies.tokenFactory);
@@ -132,18 +153,39 @@ export function createServerStateScopeRuntime(
.catch(() => {})
.then(async () => {
let failed = false;
// 1105/02-01. Each failed step is recorded once, with the label of
// the participant that threw. A FAILED scope fences every request, and
// without this nothing said which closer kept it there.
const report = (
reason: ScopeResetFailureReason,
error: unknown,
label?: string,
) => reportResetFailure(dependencies.diagnostics, reason, error, label);
let participants: readonly ScopeResetParticipant[] = [];
try {
participants =
fixedParticipants ??
orderParticipants(
(listParticipants as () => readonly ScopeResetParticipant[])(),
);
} catch (error) {
failed = true;
report("PARTICIPANTS_UNREADABLE", error);
}
// Steps 4-11: close admission, cancel and clear, release leases.
for (const participant of participants) {
try {
await participant.close();
} catch {
} catch (error) {
failed = true;
report("PARTICIPANT_FAILED", error, participant.label);
}
}
try {
await dependencies.queryInvalidation.resetLocal();
} catch {
} catch (error) {
failed = true;
report("CACHE_RESET_FAILED", error);
}
previousIdentities.close();
@@ -152,8 +194,9 @@ export function createServerStateScopeRuntime(
if (!failed) {
try {
await dependencies.activateNextGeneration?.();
} catch {
} catch (error) {
failed = true;
report("GENERATION_ACTIVATION_FAILED", error);
}
}
if (disposed || generation !== targetGeneration) return;
@@ -236,6 +279,40 @@ function readSessionIdentity(
}
}
function orderParticipants(
participants: readonly ScopeResetParticipant[],
): readonly ScopeResetParticipant[] {
return [...participants].sort((left, right) => left.order - right.order);
}
type ScopeResetFailureReason =
| "PARTICIPANTS_UNREADABLE"
| "PARTICIPANT_FAILED"
| "CACHE_RESET_FAILED"
| "GENERATION_ACTIVATION_FAILED";
function reportResetFailure(
diagnostics: DiagnosticsPort | undefined,
reason: ScopeResetFailureReason,
error: unknown,
label: string | undefined,
): void {
try {
diagnostics?.record({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation: "SCOPE_RESET",
reason,
error_kind: safeErrorKind(error),
...(isScopeParticipantLabel(label) ? { scope_participant: label } : {}),
},
});
} catch {
// The reset ends FAILED whether or not diagnostics works.
}
}
function reportSubjectMissing(diagnostics: DiagnosticsPort | undefined): void {
try {
diagnostics?.record({
@@ -98,11 +98,25 @@ export type BoundedPollCoordinatorDependencies<Value> = Readonly<{
policy: PollLeasePolicy;
/**
* The V3 descriptor `execute` runs (`BoundedPollOperation`). Creation
* refuses one whose `frontend.retryBudget` is not 0.
* refuses one whose `frontend.retryBudget` is not 0, and every `execute`
* call receives this same object as `input.operation`.
*/
operation: BoundedPollOperation;
/**
* Returns every outcome as a result, server and network failures included
* (the V3 executor returns a rejected fetch as NETWORK_FAILURE). A throw,
* like a result of the wrong shape, ends the lease with PROTOCOL_MISMATCH
* and is not retried: it is a composition defect, not a server outage.
*/
execute(input: Readonly<{
operationId: string;
/**
* 1103/04-01. The `operation` this coordinator was created with, the
* object creation checked. Run this one on the executor, not another row
* for the same path: a descriptor with `retryBudget: 2` sends up to three
* requests per attempt.
*/
operation: BoundedPollOperation;
attempt: number;
/**
* Hard response-body ceiling that must be enforced before decoding.
@@ -132,10 +146,11 @@ export function createBoundedPollCoordinator<Value>(
dependencies: BoundedPollCoordinatorDependencies<Value>,
): BoundedPollCoordinator<Value> {
const policy = definePollLeasePolicy(dependencies.policy);
assertBoundedPollOperation(policy, dependencies.operation);
const operation = dependencies.operation;
assertBoundedPollOperation(policy, operation);
const maxResponseBytes = Math.min(
policy.maxResponseBytes,
dependencies.operation.frontend.responseByteLimit,
operation.frontend.responseByteLimit,
);
const clock = dependencies.clock ?? systemClock;
const random = dependencies.random ?? Math.random;
@@ -300,12 +315,13 @@ export function createBoundedPollCoordinator<Value>(
}
attempts += 1;
let result: BoundedPollAttemptResult<Value>;
let result: BoundedPollAttemptResult<Value> | null;
const attemptOutcome = await awaitWithinLease(
() =>
trackWork(
dependencies.execute({
operationId: policy.operationId,
operation,
attempt: attempts,
maxResponseBytes,
signal: controller.signal,
@@ -320,12 +336,14 @@ export function createBoundedPollCoordinator<Value>(
if (attemptOutcome.kind === "VALUE") {
result = attemptOutcome.value;
} else if (attemptOutcome.kind === "REJECTED") {
// 1103/04-04. No server answered; OFFLINE is the environment's.
result = realtimeFailure(
controller.signal.aborted ? "ABORTED" : "PROVIDER_UNAVAILABLE",
"POLL",
!controller.signal.aborted,
);
// 1105/04-02. `execute` returns every failure as a result; the V3
// executor already returns a rejected fetch as NETWORK_FAILURE. A
// throw is a composition defect, read below like a malformed
// result, not retried as a server outage. One caused by this
// lease's abort ends with the abort's reason.
result = controller.signal.aborted
? realtimeFailure("ABORTED", "POLL", false)
: null;
} else {
if (attemptOutcome.kind === "CLOCK_FAILED") {
controller.abort();
@@ -374,7 +392,8 @@ export function createBoundedPollCoordinator<Value>(
return pollFailure("POLL_BUDGET_EXHAUSTED");
}
const parsedResult = parseAttemptResult<Value>(result);
const parsedResult =
result === null ? null : parseAttemptResult<Value>(result);
if (!parsedResult) {
return pollFailure("PROTOCOL_MISMATCH");
}
@@ -1,4 +1,5 @@
import {
BUILD_ASSET_DIRECTORY,
HASHED_STATIC_ASSET_NAME,
isOwnedStaticCacheName,
SERVICE_WORKER_BOUNDS,
@@ -59,12 +60,10 @@ export function classifyFetch(input: ClassificationInput): FetchClassification {
}
/**
* 06-08. Vite's default `build.assetsDir`, under the app base that is also the
* registration scope. A hashed-looking API or download name elsewhere is not an
* old build chunk and is left to the browser.
* 06-08. `BUILD_ASSET_DIRECTORY` is resolved under the app base that is also
* the registration scope. A hashed-looking API or download name elsewhere is
* not an old build chunk and is left to the browser.
*/
const BUILD_ASSET_DIRECTORY = "assets/";
function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean {
try {
const request = new URL(requestUrl);
@@ -805,8 +805,7 @@ export function createOpfsByteStoreAdapter(
const sweeping =
request.reason === "LOGOUT" || request.reason === "ACCOUNT_DELETION";
// [0929] 05-01. Rows the journal could not read and skipped, and damage
// met past the listing: a remove or the sweep failing on an unreadable
// row, or staging the sweep cannot read.
// met past the listing: a remove failing on an unreadable row.
let corruptObjects = 0;
let damaged = false;
@@ -888,14 +887,25 @@ export function createOpfsByteStoreAdapter(
}
afterObjectId = page.value.nextObjectId;
}
// 2026-11-03 05-01. A put or delete of this partition that has not
// finished holds bytes the object walk never sees and the sweep skips:
// one running in another tab, or a row a crash left (PREPARING, or
// FILES_READY, which the next reconcile would commit) or nothing can
// read. Any such row sends the purge to the partition delete below,
// which first waits for every live one.
// 1103/05-01 (rest). A walk that reached the last object no longer ends
// in a chunk sweep. The walk and a journal count each see one moment:
// another tab's put of a new object that committed after the listing
// and settled before the count was in neither, and a stopped put whose
// row lost its partition key is never counted. The sweep then skipped
// their chunks and staging and still reported COMPLETED, so the file
// stayed readable after the account deletion. Such a walk now always
// ends in the partition delete below, which waits for every put and
// delete of the partition and takes the whole directory, staging
// included, so nothing that began before it is left.
const walkFinished = !moreObjectsAvailable && !deadlineReached;
// 2026-11-03 05-01. A walk the budget or another tab's change stopped
// leaves the rest for the next call, unless a put or delete of this
// partition has not finished: one running in another tab, or a row a
// crash left (PREPARING, or FILES_READY, which the next reconcile would
// commit) or nothing can read. Any such row sends this call to the
// partition delete too.
let unfinished = 0;
if (sweeping && !request.signal?.aborted) {
if (sweeping && !walkFinished && !request.signal?.aborted) {
const counted = await dependencies.journal.countPartitionTransactions(
dependencies.scope,
);
@@ -904,40 +914,6 @@ export function createOpfsByteStoreAdapter(
}
unfinished = counted.value;
}
// 05-04. Removing an object leaves its chunks, and GC only takes a
// chunk 24 h after it was written, so a purged user's bytes stayed on
// the device. Once every object is gone the partition's chunks are swept
// without that grace. The sweep still skips any chunk the journal or a
// staged put references.
let chunkSweep: OpfsPolicyMaintenanceReport["chunkSweep"];
if (
sweeping &&
!unfinished &&
!corruptObjects &&
!damaged &&
!moreObjectsAvailable &&
!deadlineReached &&
!request.signal?.aborted
) {
const swept = await reconcileOrphanChunks(
deadline,
request.signal,
now(),
);
if (!swept.ok) {
if (swept.error.code !== "CORRUPT_DATA") {
return rebaseFailure(swept.error, "OBJECT_RECONCILE");
}
damaged = true;
} else {
chunkSweep = swept.value.status;
damaged = chunkSweep === "STAGING_STATE_UNREADABLE";
if (chunkSweep === "DEADLINE_REACHED") {
deadlineReached = true;
moreObjectsAvailable = true;
}
}
}
// [0929] 05-01. A row nothing can read never lets this purge finish, so
// the user's bytes would stay on the device for good. The authority
// approved this exact LOGOUT or ACCOUNT_DELETION (the same approval the
@@ -949,7 +925,7 @@ export function createOpfsByteStoreAdapter(
// wait for every put and delete of the partition in any tab.
const partitionDeleted =
sweeping &&
(corruptObjects > 0 || damaged || unfinished > 0) &&
(walkFinished || corruptObjects > 0 || damaged || unfinished > 0) &&
!request.signal?.aborted;
if (partitionDeleted) {
const removed = await withPartitionLock(
@@ -970,8 +946,12 @@ export function createOpfsByteStoreAdapter(
if (!removed.ok) {
return rebaseFailure(removed.error, "OBJECT_RECONCILE");
}
chunkSweep = undefined;
moreObjectsAvailable = false;
} else if (sweeping) {
// Only an abort between the walk and the delete gets here with the
// walk finished. Either way the partition still holds bytes, so a
// purge reports exactly one of `partitionDeleted` and more work.
moreObjectsAvailable = true;
}
const report: OpfsPolicyMaintenanceReport = Object.freeze({
inspectedObjects,
@@ -979,7 +959,6 @@ export function createOpfsByteStoreAdapter(
releasedBytes,
moreObjectsAvailable,
deadlineReached,
...(chunkSweep ? { chunkSweep } : {}),
...(corruptObjects ? { corruptObjects } : {}),
...(partitionDeleted ? { partitionDeleted } : {}),
});
@@ -1365,7 +1344,6 @@ export function createOpfsByteStoreAdapter(
async function reconcileOrphanChunks(
deadline: number,
signal: AbortSignal | undefined,
olderThanEpochMs = Math.max(0, now() - policy.orphanGracePeriodMs),
): Promise<
BrowserDataResult<
Readonly<{
@@ -1378,6 +1356,7 @@ export function createOpfsByteStoreAdapter(
}>
>
> {
const olderThanEpochMs = Math.max(0, now() - policy.orphanGracePeriodMs);
let inspected = 0;
let deleted = 0;
// R-5.1. Candidates include committed chunks, so a page can be all
+3 -2
View File
@@ -31,8 +31,9 @@ export type PollLeasePolicy = Readonly<{
/**
* 1103/04-01. A poll lease runs one installed V3 descriptor: the composed row
* (`composeContractContributions(...).httpByOperationId.get(id)`). Hand the
* same object to the executor (`createContractHttpExecutor().execute`). The
* (`composeContractContributions(...).httpByOperationId.get(id)`). The poll
* coordinator hands that same object back to `execute` as `input.operation`;
* pass it to the executor (`createContractHttpExecutor().execute`). The
* executor reads its retry ceiling from `frontend.retryBudget`, so a budget of
* 0 is what makes one poll attempt one physical request; the poll coordinator
* owns every retry between attempts.
@@ -52,8 +52,22 @@ export type PublicCacheInspection = Readonly<{
activeReleaseRegistryId: string | null;
ownedCacheCount: number;
unreadableOwnedCacheCount: number;
/**
* 0929/02-02. Every owned release cache with a readable marker. To fill
* `verified`, inspect reads back every entry of every candidate, so its cost
* grows with caches times entries. It has no cursor, deadline or signal
* (VD-15's target runtime adds a cursor and a deadline). Keep it off a boot
* path.
*/
releaseCandidates: readonly Readonly<{
releaseRegistryId: string;
/**
* `true` only when every entry was read back and matched the manifest.
* `false` when an entry is missing or no longer matches, and also when it
* could not be read at all (a failed body read or lookup): inspect does
* not tell those apart. Activating the candidate does, and staging the
* same manifest again rewrites either (1105/02-02).
*/
verified: boolean;
entryCount: number | null;
}>[];
@@ -152,12 +152,15 @@ export type OpfsPolicyMaintenanceReport = Readonly<{
moreObjectsAvailable: boolean;
deadlineReached: boolean;
/**
* 05-04. LOGOUT and ACCOUNT_DELETION only, once every object is removed and
* no put or delete of the partition is unfinished: how the sweep of the
* partition's now unreferenced chunks ended. For those two reasons the
* partition's bytes are gone exactly when this is `COMPLETED` or
* `partitionDeleted` is set; a put that begins after the purge reached its
* journal check is kept (2026-11-03 05-01).
* 05-04. How a LOGOUT or ACCOUNT_DELETION chunk sweep ended.
*
* @deprecated The reference runtime and the recipe fake no longer set it
* (1103/05-01 rest): a sweep after the object walk missed a new object
* another tab's put settled during the walk, and the staging of a stopped
* put whose journal row lost its partition key, and still said
* `COMPLETED`. Such a purge now ends in the partition delete, so
* `partitionDeleted` is the one completion signal. Kept so code that reads
* it still compiles; it is always absent.
*/
chunkSweep?: "COMPLETED" | "DEADLINE_REACHED" | "STAGING_STATE_UNREADABLE";
/**
@@ -166,12 +169,16 @@ export type OpfsPolicyMaintenanceReport = Readonly<{
*/
corruptObjects?: number;
/**
* [0929] 05-01. An approved LOGOUT or ACCOUNT_DELETION that damage kept
* from finishing, or that found an unfinished put or delete of the
* partition (2026-11-03 05-01), removed the whole partition directory and
* the partition's journal rows instead, after every put and delete of the
* partition then running in any tab had returned. Every byte of the
* partition is gone.
* [0929] 05-01. An approved LOGOUT or ACCOUNT_DELETION removed the whole
* partition directory and the partition's journal rows, after every put
* and delete of the partition then running in any tab had returned. Every
* byte of the partition is gone; a put that begins after that delete is
* kept. A purge that walked every object always ends this way (1103/05-01
* rest). One the budget or another tab's change stopped part-way ends this
* way only when damage or an unfinished put or delete of the partition
* (2026-11-03 05-01) was met; otherwise it reports `moreObjectsAvailable`
* and the caller runs it again. For these two reasons the partition's bytes
* are gone exactly when this is set.
*/
partitionDeleted?: true;
}>;
+3 -1
View File
@@ -86,7 +86,9 @@ export type AsyncState = Readonly<{
/**
* 0929/03-03. Only with `indicator: "mutation-effect-unknown"`, when the
* coordinator said: `false` means the request has no idempotency key, so
* sending it again is a second, unprotected request and no resend is drawn.
* sending it again is a second, unprotected request. A resend is drawn
* only for `true`; absent (a state built without the coordinator) draws
* none.
*/
unknownEffectResendable?: boolean;
}>;
@@ -7,7 +7,9 @@ import { loadRuntimeConfig } from "./load-runtime-config.ts";
import {
createOptionalRuntimeHost,
type OptionalRuntimeHost,
type OptionalRuntimeHostInput,
} from "./optional-runtime-host.ts";
import type { ProductServiceWorkerWiring } from "./product-composition-contract.ts";
import { createRuntimeAdapters } from "./runtime-adapters.ts";
export type RuntimeCompositionDependencies = Readonly<{
@@ -27,6 +29,9 @@ export async function createRuntimeComposition(
// 06-05. The optional host reports a Service Worker that did not start
// through the same telemetry port as the application.
let telemetry: TelemetryPort | undefined;
// 1103/09-05. `composeProduct` (product-owned) supplies the worker's
// blockers and observer; this template file only passes them on.
let productServiceWorker: ProductServiceWorkerWiring | null | undefined;
const root = await createCompositionRoot({
loadConfig: () => loadRuntimeConfig({ fetcher: dependencies.fetcher }),
loadRelease: (runtime) =>
@@ -39,6 +44,7 @@ export async function createRuntimeComposition(
host: dependencies.host,
});
telemetry = adapters.outputPorts.telemetry;
productServiceWorker = adapters.productServiceWorker;
return adapters;
},
});
@@ -52,6 +58,7 @@ export async function createRuntimeComposition(
routerBasePath: root.config.build.routerBasePath,
buildId: root.release.buildId,
...(telemetry ? { telemetry } : {}),
...serviceWorkerWiring(productServiceWorker),
...(dependencies.host
? {
host: dependencies.host as Parameters<
@@ -78,3 +85,31 @@ export async function createRuntimeComposition(
export type RuntimeComposition = Awaited<
ReturnType<typeof createRuntimeComposition>
>;
/**
* 1103/09-05. The product's wiring in the optional host's terms. The blocker
* list is copied once; the page controller already treats a throwing blocker
* as blocking. A throwing observer is product code and must not break the
* worker flow, so its throw is dropped here.
*/
function serviceWorkerWiring(
wiring: ProductServiceWorkerWiring | null | undefined,
): Pick<OptionalRuntimeHostInput, "blockers" | "observe"> {
if (!wiring) return {};
return {
...(wiring.blockers
? { blockers: Object.freeze([...wiring.blockers]) }
: {}),
...(wiring.observe
? {
observe: (observation: Readonly<{ event: string; outcome: string }>) => {
try {
wiring.observe?.(observation);
} catch {
// A failing product sink never changes the worker's outcome.
}
},
}
: {}),
};
}
+17 -3
View File
@@ -1,4 +1,8 @@
import { assertSafeConfigNames, getBuildConfig } from "../contracts/env.ts";
import {
assertSafeConfigNames,
getBuildConfig,
UnsafeConfigNameError,
} from "../contracts/env.ts";
import { checkReleaseCoherence } from "../platform/release/release-coherence.ts";
import {
BOOT_JSON_POLICIES,
@@ -21,7 +25,10 @@ export type BootConfigSafe = Readonly<{
buildId: string;
configSchemaVersion?: string;
releaseId?: string;
/** 09-04. Names of rejected keys (never their values), bounded. */
/**
* 09-04. Names of rejected keys (never their values), bounded: the keys the
* schema rejected, or (1103/07-04) the secret-looking key's dotted path.
*/
invalidKeys?: readonly string[];
supportReference: string;
}>;
@@ -117,9 +124,16 @@ export async function loadRuntimeConfig(
try {
assertSafeConfigNames(rawConfig);
} catch {
} catch (error) {
// 1103/07-04. The rejected key's name, never its value, tells an operator
// what to remove. It comes from the rejected document, so it is bounded
// like the schema failure's keys below.
const key = error instanceof UnsafeConfigNameError ? error.key : undefined;
throw new BootConfigError("CONFIG_SECRET_NAME_REJECTED", {
buildId: buildConfig.buildId,
...(key !== undefined && SAFE_KEY_PATTERN.test(key)
? { invalidKeys: Object.freeze([key]) }
: {}),
});
}
+42 -3
View File
@@ -88,6 +88,16 @@ export type ProductCompositionContext = Readonly<{
http: InstalledHttpOperationExecutor;
/** False while a session change fences server state; send nothing then. */
isScopeReady(): boolean;
/**
* 1105/09-02. Tells the template session that the server rejected the
* session's own credential, as a 401 to a request the session credentialed
* does: the session goes unauthenticated and server state is fenced. For
* `onCredentialRejected` when a provider sends the session's credential (a
* BFF cookie session: `createSessionCookieRejectionHandler` in
* recipes/session-owners/cookie-session-owner.ts). Not for a provider whose
* credential is not the session's, such as another API's token.
*/
notifySessionUnauthenticated(): void;
}>;
/**
@@ -98,10 +108,36 @@ export type ProductCompositionContext = Readonly<{
* or rejects keeps the scope from reaching READY, as the template's own do.
*/
export type ProductScopeParticipant = Readonly<{
/**
* 1105/02-01. A lowercase kebab-case token such as `browser-files`
* (`isScopeParticipantLabel` in `src/contracts/diagnostics.ts`). A close
* that throws or rejects records `cache.operation.failed` with
* `operation: "SCOPE_RESET"`, `reason: "PARTICIPANT_FAILED"` and this label
* as `scope_participant`, so the stuck scope names its cause. Composition
* throws a `TypeError` on any other label.
*/
label: string;
close(): void | Promise<void>;
}>;
/**
* 1103/09-05. The page side of the Service Worker the product selected in
* `src/features/product-capabilities.ts`. Unused when no worker is selected.
*/
export type ProductServiceWorkerWiring = Readonly<{
/**
* §17.10. Asked each time this tab is about to let a waiting worker take
* over (`requestActivation()`). One that returns true, or throws, refuses
* with `BLOCKED_DIRTY_CLIENT`: say, while a form has unsaved edits.
*/
blockers?: readonly (() => boolean)[];
/**
* The page controller's diagnostics (`register`, `activation`, `message`,
* `client_drain`, ...), each with its outcome. A throw is ignored.
*/
observe?(observation: Readonly<{ event: string; outcome: string }>): void;
}>;
export type ProductComposition = Readonly<{
capabilities: Readonly<
Partial<Omit<FeaturePlatformCapabilities, TemplatePlatformCapabilityId>>
@@ -111,9 +147,10 @@ export type ProductComposition = Readonly<{
/**
* 1103/09-01. Optional. Called when the server answers 401 to a request
* whose credential one of `credentialProviders` supplied. The template
* session is not told, because it did not supply that credential; a BFF
* product whose provider and session owner share one cookie session tells
* its owner here (`notifyUnauthenticated`). A throw is ignored.
* session is not told, because it did not supply that credential. A BFF
* product whose provider sends the session's own cookie tells the session
* here with `context.notifySessionUnauthenticated()` (1105/09-02); without
* it an ended server session leaves the page signed in. A throw is ignored.
*/
onCredentialRejected?(
binding: Readonly<{ operationId: string; authProfileId: string }>,
@@ -125,4 +162,6 @@ export type ProductComposition = Readonly<{
* does.
*/
scopeParticipants?: readonly ProductScopeParticipant[];
/** 1103/09-05. Optional. Read once, when the runtime is composed. */
serviceWorker?: ProductServiceWorkerWiring;
}>;
+80 -36
View File
@@ -7,12 +7,15 @@ import {
import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts";
import {
createContractHttpExecutor,
type ContractHttpExecutor,
type ContractHttpExecutorDependencies,
type HttpExecutionObservation,
type InstalledHttpOperationExecutor,
} from "../adapters/http/index.ts";
import {
attemptBucket,
durationBucket,
isScopeParticipantLabel,
statusGroup,
type DiagnosticRecordInput,
} from "../contracts/diagnostics.ts";
@@ -57,6 +60,7 @@ import {
type ReleaseManifest,
} from "./load-release-manifest.ts";
import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts";
import type { RuntimeConfig } from "./runtime-config-schema.ts";
import { createServerStateGenerationStore } from "./server-state-generation-store.ts";
import {
composeProduct,
@@ -278,6 +282,43 @@ function isTerminalNonAbortFailure(
);
}
/**
* 1105/10-01. Where Runtime Config's two HTTP dials reach the V3 executor:
* `MAX_RETRY_ATTEMPTS` caps every contract's retry budget and
* `REQUEST_TIMEOUT_MS` caps every contract's deadline. The composition root
* below builds its executor only through this function. It is a function of
* its own so a platform test can drive the dials without an installed
* feature: `createRuntimeAdapters` reaches the executor only through a
* feature's HTTP, and a product that removed the sample has none
* (tests/unit/runtime-adapters.test.ts).
*/
export function createRuntimeContractHttpExecutor(
config: Pick<
RuntimeConfig,
"API_BASE_URL" | "MAX_RETRY_ATTEMPTS" | "REQUEST_TIMEOUT_MS"
>,
collaborators: Pick<
ContractHttpExecutorDependencies,
"fetcher" | "attachCredentials" | "observe"
>,
): ContractHttpExecutor {
return createContractHttpExecutor({
baseUrl: config.API_BASE_URL,
maxRetryAttempts: config.MAX_RETRY_ATTEMPTS,
// §6.1. `REQUEST_TIMEOUT_MS` was declared, validated and then dropped on the
// floor here: every V3 operation ran on its contract's own 10s deadline and
// the deployment dial did nothing. It is a ceiling, so it can tighten an
// operation but never loosen one.
requestDeadlineCeilingMs: config.REQUEST_TIMEOUT_MS,
fetcher: collaborators.fetcher,
// §7.7. The installed registry owns Fetch credentials and the exact
// credential-header sets; `attachCredentials` only supplies proof headers.
authProfiles: INSTALLED_REST_AUTH_PROFILES,
attachCredentials: collaborators.attachCredentials,
observe: collaborators.observe,
});
}
export async function createRuntimeAdapters(
context: RuntimeAdaptersContext,
) {
@@ -390,37 +431,34 @@ export async function createRuntimeAdapters(
});
});
// 2026-11-03 02-01. The product's closers. `composeProduct` runs after the
// scope exists (its context needs the fence), so they join through this one
// slot, filled below. Each runs even when an earlier one fails, and any
// failure keeps the scope from READY, as for the template's own.
// scope exists (its context needs the fence), so they join through this
// list, filled below, which the scope reads at each reset. Each runs even
// when an earlier one fails, and any failure keeps the scope from READY, as
// for the template's own. 1105/02-01. Each is its own participant at the
// offline-lease step (10), so a failed close is recorded under its label.
const productScopeParticipants: ProductScopeParticipant[] = [];
const templateScopeParticipants = Object.freeze([
Object.freeze({
order: 4,
label: "conditional-validators",
close: () => conditionalValidators.clear(),
}),
]);
const serverStateScope = createServerStateScopeRuntime({
session: authSession,
diagnostics,
queryInvalidation: {
resetLocal: () => serverStateGeneration.resetCurrent(),
},
participants: [
{
order: 4,
label: "conditional-validators",
close: () => conditionalValidators.clear(),
},
{
order: 10,
label: "product",
async close() {
let failed = false;
for (const participant of productScopeParticipants) {
try {
await participant.close();
} catch {
failed = true;
}
}
if (failed) throw new Error("A product scope participant failed.");
},
},
participants: () => [
...templateScopeParticipants,
...productScopeParticipants.map((participant) =>
Object.freeze({
order: 10,
label: participant.label,
close: () => participant.close(),
}),
),
],
activateNextGeneration: () => serverStateGeneration.activateNext(),
});
@@ -497,18 +535,8 @@ export async function createRuntimeAdapters(
diagnostics,
telemetry,
});
const contractHttp = createContractHttpExecutor({
baseUrl: config.API_BASE_URL,
maxRetryAttempts: config.MAX_RETRY_ATTEMPTS,
// §6.1. `REQUEST_TIMEOUT_MS` was declared, validated and then dropped on the
// floor here: every V3 operation ran on its contract's own 10s deadline and
// the deployment dial did nothing. It is a ceiling, so it can tighten an
// operation but never loosen one.
requestDeadlineCeilingMs: config.REQUEST_TIMEOUT_MS,
const contractHttp = createRuntimeContractHttpExecutor(config, {
fetcher: context.fetcher,
// §7.7. The installed registry owns Fetch credentials and the exact
// credential-header sets; this collaborator only supplies proof headers.
authProfiles: INSTALLED_REST_AUTH_PROFILES,
async attachCredentials(operation, authContext) {
if (serverStateScope.getPhase() !== "READY") {
return Object.freeze({ kind: "SCOPE_FENCED" as const });
@@ -671,6 +699,10 @@ export async function createRuntimeAdapters(
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
http: contractOperations,
isScopeReady: () => serverStateScope.getPhase() === "READY",
// 1105/09-02. For a product provider that sends the session's own
// credential: the verdict reportServerUnauthenticated gives the session's
// own 401.
notifySessionUnauthenticated: () => authSession.onUnauthenticated(),
}) satisfies ProductComposition;
// Read through the contract type: the product's own return type omits the
// optional fields when the product does not use them, and `product` keeps
@@ -678,7 +710,16 @@ export async function createRuntimeAdapters(
const productContract: ProductComposition = product;
const productCredentialProviders = productContract.credentialProviders;
const onProductCredentialRejected = productContract.onCredentialRejected;
productScopeParticipants.push(...(productContract.scopeParticipants ?? []));
for (const participant of productContract.scopeParticipants ?? []) {
// 1105/02-01. The label names the participant in diagnostics, so it must
// be a token the diagnostic projection keeps.
if (!isScopeParticipantLabel(participant.label)) {
throw new TypeError(
"A product scope participant label must be a lowercase kebab-case token (isScopeParticipantLabel).",
);
}
productScopeParticipants.push(participant);
}
// Each installed contribution receives only the capabilities it declares.
// The template's own capabilities come last, so a product cannot replace
// them. 09-05. `indexedDb` is not built here: IndexedDB is an opt-in
@@ -733,5 +774,8 @@ export async function createRuntimeAdapters(
},
}),
featureLoaders,
// 1103/09-05. The optional host is built after this bundle, by
// create-runtime-composition.ts, and reads the product's wiring here.
productServiceWorker: productContract.serviceWorker ?? null,
});
}
+15
View File
@@ -44,6 +44,7 @@ export const DIAGNOSTIC_CONTEXT_ALLOWLIST = Object.freeze([
"queue_size_bucket",
"feature_override_key",
"effect_certainty",
"scope_participant",
] as const);
export type DiagnosticContextKey =
(typeof DIAGNOSTIC_CONTEXT_ALLOWLIST)[number];
@@ -90,6 +91,9 @@ export const DIAGNOSTIC_CONTEXT_CARDINALITY = Object.freeze({
feature_override_key: "deployment",
// 1103/03-05. The V3 effect certainty, five values.
effect_certainty: "bounded",
// 1105/02-01. The label of a scope reset participant, set in source by the
// template or the product composition, never by traffic.
scope_participant: "topology",
} satisfies Readonly<Record<DiagnosticContextKey, DiagnosticCardinalityClass>>);
export type DiagnosticContext = Readonly<
@@ -118,6 +122,7 @@ const BOUNDED_CONTEXT_VALUE_POLICIES: Readonly<
queue_size_bucket: (value) =>
typeof value === "string" && /^(?:0|1-10|11-50|51\+)$/.test(value),
effect_certainty: isEffectCertainty,
scope_participant: isScopeParticipantLabel,
});
/**
@@ -133,6 +138,16 @@ export function isEffectCertainty(value: unknown): value is string {
);
}
/**
* 1105/02-01. A scope reset participant's label: a lowercase kebab-case token
* of at most 48 characters that starts with a letter. A failed close is
* recorded under it (`scope_participant`), so the label must pass this
* projection; product composition refuses any other.
*/
export function isScopeParticipantLabel(value: unknown): value is string {
return typeof value === "string" && /^[a-z][a-z0-9-]{0,47}$/.test(value);
}
export type DiagnosticRecordInput = Readonly<{
level: DiagnosticLevel;
eventId: DiagnosticEventId;
+36 -5
View File
@@ -116,25 +116,56 @@ function runtime(
return Object.freeze({ phase: "runtime", classification, required, defaultValue });
}
/**
* 1103/07-04. What `assertSafeConfigNames` throws. `key` is the rejected
* key's dotted path from where the check started
* (`CAPABILITY_OVERRIDES.AUTH_TOKEN`), so the boot error can name it without
* its value. It is absent when the document nests too deep.
*/
export class UnsafeConfigNameError extends Error {
readonly key: string | undefined;
constructor(message: string, key?: string) {
super(message);
this.name = "UnsafeConfigNameError";
this.key = key;
}
}
export function assertSafeConfigNames(
config: Readonly<Record<string, unknown>>,
depth = 0,
): void {
assertSafeConfigNamesAt(config, depth, []);
}
function assertSafeConfigNamesAt(
config: Readonly<Record<string, unknown>>,
depth: number,
path: readonly string[],
): void {
if (depth > 4) {
throw new Error("Client configuration nesting exceeds its bound");
throw new UnsafeConfigNameError(
"Client configuration nesting exceeds its bound",
);
}
for (const [name, value] of Object.entries(config)) {
const allowlisted = depth === 0 && SEMANTIC_KEY_ALLOWLIST.has(name);
if (!allowlisted && isForbiddenConfigName(name)) {
throw new Error(`Forbidden client configuration key: ${name}`);
throw new UnsafeConfigNameError(
`Forbidden client configuration key: ${name}`,
[...path, name].join("."),
);
}
if (!isPlainNested(value)) continue;
if (depth === 0 && FEATURE_ID_KEYED_MAPS.has(name)) {
for (const entry of Object.values(value)) {
if (isPlainNested(entry)) assertSafeConfigNames(entry, depth + 2);
for (const [featureId, entry] of Object.entries(value)) {
if (isPlainNested(entry)) {
assertSafeConfigNamesAt(entry, depth + 2, [...path, name, featureId]);
}
}
} else {
assertSafeConfigNames(value, depth + 1);
assertSafeConfigNamesAt(value, depth + 1, [...path, name]);
}
}
}

Some files were not shown because too many files have changed in this diff Show More