diff --git a/config/contracts/backend-contract-pin.json b/config/contracts/backend-contract-pin.json index 8e715df2..85a8a661 100644 --- a/config/contracts/backend-contract-pin.json +++ b/config/contracts/backend-contract-pin.json @@ -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 _INVALID and _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 _INVALID and 404 _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 / answers 201, GET //{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", diff --git a/config/performance/budgets.json b/config/performance/budgets.json index 18d08dc8..26b5a1d5 100644 --- a/config/performance/budgets.json +++ b/config/performance/budgets.json @@ -8,7 +8,8 @@ "lab": { "lcpMs": 2500, "cls": 0.1, - "namedInteractionMs": 200 + "namedInteractionMs": 200, + "featureRouteInteractionMs": 500 }, "field": { "p75LcpMs": 2500, diff --git a/config/schemas/lab-performance.schema.json b/config/schemas/lab-performance.schema.json index 878b9f33..7d0297f0 100644 --- a/config/schemas/lab-performance.schema.json +++ b/config/schemas/lab-performance.schema.json @@ -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 }, diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index aa35c31e..f0526f2a 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -186,10 +186,16 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 비교하고, 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`). diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index 8c7967ad..fa66ffdf 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -215,6 +215,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-module.ts` | the feature needs a new context | `generate:feature-index`: `Feature belongs to undeclared context ` | | `src/contexts//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/.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 | diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 739176ca..5f5f3859 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -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 `: 0단계에서 기존 context를 골랐을 때만 준다. @@ -208,9 +211,10 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope - 성공: `{ "success": true, "data": ..., "meta": ... }` - 실패: `{ "success": false, "error": { "code", ... }, "meta": ... }` - 이 모양을 읽게 하는 것은 V3 descriptor(`-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 생성된 operation에는 모두 들어 있다. - - operation을 손으로 더할 때마다 이 줄을 적는다. 이 값은 operation마다 따로다. - - 한 계약 기여 안에서 이 값이 다른 operation이 있으면 계약 조립이 거부한다(`/: responseEnvelope NONE, but 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이 있으면 계약 조립이 거부한다(`/: responseEnvelope NONE, but in the same contribution reads ENVELOPE_V1; ...`). 기여 하나는 백엔드 하나의 패키지라서다. 그래서 값을 잘못 적으면 앱을 조립하는 테스트와 `check:registries`가 실패한다. + - **못 잡음**: 기여 안의 operation 모두에 같은 틀린 값을 적는 것(짝 백엔드인데 모두 `"NONE"`). 그때는 아래 MSW 줄의 손글씨 gateway 테스트만 잡는다. ```text 성공 status → Envelope 확인 → data를 outputValidator로 검증 → mapSuccess @@ -233,7 +237,7 @@ 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`이 모든 판정을 정한다. 실행기가 먼저 정하는 판정은 없다. @@ -639,7 +643,8 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature 기능 폴더를 가리키는 커버리지 정책 행, owner가 기능 ID인 증거 정책 행을 지움 → 레지스트리 기준선을 다시 찍음 (빼는 변경은 breaking이라서) → 타입·아키텍처·레지스트리·테스트·커버리지·CI 계약·빌드 게이트 - → src와 tests에 기능 ID나 폴더 이름이 남았는지 찾음 + → 지운 기능을 가리키는 파일이 남았는지 찾음 + (src: 기능 ID·폴더 이름을 담은 파일, tests: 이름에 기능 ID가 있거나 기능 폴더에서 import하는 파일) ``` ① **정할 것**: 없음. 확인 단계다. @@ -651,9 +656,10 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature ③ **잡는 검사 / 못 잡는 것** -- 남은 파일이 기능 ID나 폴더 이름을 담고 있으면 실패한다. +- 남은 파일이 지운 기능을 가리키면 실패한다. `src`는 기능 ID나 폴더 이름을 담은 파일, `tests`는 이름에 기능 ID가 있거나 기능 폴더에서 import하는 파일이다. - 메시지: ` removal failed:` 다음 줄 `fixture-id-residue: residue: ` -- **못 잡음**: 기능 ID를 담지 않은 폴더 밖 파일. 예: route ID만 적은 e2e spec, `artifacts/tests/a11y-manual/.md`. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다. + - 템플릿 테스트가 예시 ID(`invoice-feature` 등)를 데이터로 쓰는 것은 잔여로 세지 않는다(1105/16-04). 그래서 매뉴얼 예시 이름으로 만든 기능도 이 단계를 통과한다. +- **못 잡음**: 기능을 가리키지 않는 폴더 밖 파일. 예: route ID만 적은 e2e spec, `artifacts/tests/a11y-manual/.md`. `tests` 안에서 기능 ID를 글자로만 적은 테스트도 잔여로 세지 않는다. 그 테스트가 지운 기능에 기대면 같은 드릴의 `test:all`이 실패한다. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다. ④ **쓸 스킬**: `documentation-and-adrs`, `deprecation-and-migration` diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 8e11c49d..ed195250 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -19,7 +19,7 @@ ## A. 생성 명령이 만든다 -`corepack pnpm create:feature`가 쓰는 폴더 밖 파일은 둘이다. 있는 파일은 덮어쓰지 않는다. +`corepack pnpm create:feature`가 새로 만드는 폴더 밖 파일은 둘이다. 있는 파일은 덮어쓰지 않는다. 이미 있는 추적 파일 중 다시 쓰는 것은 아래 "기능마다 바뀌는 템플릿 추적 파일"에 있다. - `src/contexts//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. 사람이 꼭 해야 한다 @@ -199,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=" removed" corepack pnpm update:registry-baseline diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 3c2f83fe..8f4a9af9 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -105,7 +105,8 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `/: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` | | `/: refusedBeforeWrite cannot declare ; 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-결과-불명)) | | `/: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` | -| `/: responseEnvelope NONE, but in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `responseEnvelope` 줄을 빠뜨린 경우다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 | +| `/: responseEnvelope NONE, but 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` | | `: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `_CONTRACT_PACKAGE.version` | ### 라우트·context @@ -195,6 +196,6 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | 메시지 | 원인 | 고칠 곳 | |---|---|---| -| ` removal failed:` 다음 `fixture-id-residue: residue: ` (`test:sample-removal`) | 기능을 지운 뒤에도 `src`·`tests`에 기능 ID를 담은 파일이 남았다 | 그 파일을 기능 폴더 안으로 옮기거나, 기능 ID를 담지 않게 한다 | +| ` removal failed:` 다음 `fixture-id-residue: residue: ` (`test:sample-removal`) | 기능을 지운 뒤에도 그 기능을 가리키는 파일이 남았다. `src`는 기능 ID나 폴더 이름을 담은 파일, `tests`는 이름이 기능 ID를 담거나 기능 폴더(`src/features//`, `tests/features//`)에서 import하는 파일이다 | 그 파일을 기능 폴더 안으로 옮기거나, 기능을 가리키지 않게 한다. 목록에 템플릿 파일이 나오면 템플릿 결함이다. 그 파일을 고치지 말고 템플릿에 알린다 | | `No installed feature declares FEATURE_MODULE_ID ""` | `--feature=`에 없는 기능 ID | 명령 인자 | | `feature scaffold failed:` 다음 `: ` (`test:feature-scaffold`) | 생성한 기능이 게이트 하나를 통과하지 못했다 | `scripts/create-feature.ts`의 템플릿. 제품 팀이 아니라 템플릿을 고칠 일이다 | diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index 36608b1b..9e01948c 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -30,8 +30,11 @@ config/scale/feature-shape-ceilings.json의 `initialJavascript` 한 곳이다. | `perContextGzipBytes` | 새 context를 하나 더할 때 느는 초기 JS. 상한 512 B | - tests/unit/feature-shape-growth.test.ts(unit, merge 단계)가 매번 빌드해 이 - 값을 재고, 상한을 넘거나 기록과 다르면(합계 1% 초과, 파일 수 불일치, 기능· + 값을 재고, 상한을 넘거나 기록과 다르면(합계 256 B 초과, 파일 수 불일치, 기능· context 비용 10% 초과) 실패한다. 실패 메시지에 잰 값이 나온다. + - 합계의 허용 오차는 바이트로 둔다(1105/15-02). build id만 달라도 합계가 + 수십 B 움직이므로 0으로 둘 수 없다. 예전 1%(약 2 KB)는 남은 여유와 기능 + 하나보다 커서, 여유를 다 쓴 변경이 기록을 고치지 않고 지나갈 수 있었다. - 기록을 고칠 때는 `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`를 돌리고 같은 변경에 넣는다. - 여유는 예산에서 `gzipBytes`를 뺀 값이다. 그것을 `perFeatureGzipBytes`로 나누면 @@ -87,7 +90,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가 포트를 계속 잡고 있었다. diff --git a/scripts/check-backend-contract-drift.ts b/scripts/check-backend-contract-drift.ts index c5aa78af..59538215 100644 --- a/scripts/check-backend-contract-drift.ts +++ b/scripts/check-backend-contract-drift.ts @@ -18,25 +18,41 @@ import { * 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. + * 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. * * corepack pnpm check:backend-contract-drift [--backend ] [--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 three hold. Exit 1: one does not; the output names the rows. - * Recheck the frontend contract 6.1 table, the answer table, the excerpt 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. + * 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/`) 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[]; }>; @@ -86,6 +102,7 @@ function main(): void { const pin = readJson(PIN_PATH); const directory = backendDirectory(pin); const { commit, document } = pin.backend; + const scaffoldSources = pin.backend.scaffoldSources ?? []; if (!existsSync(path.join(directory, ".git"))) { cannotCompare( `No ${pin.backend.repository} checkout at ${directory}; pass --backend . test:unit holds the answer table to ${pin.tables.backendExcerpt}, and only this script holds that copy to the backend.`, @@ -149,20 +166,31 @@ function main(): void { 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} unchanged; 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( - `Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, ${pin.tables.idempotencyAnswers}, ${pin.tables.backendExcerpt} and ${PIN_PATH} together.`, + `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.`, ); process.exitCode = 1; } diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index 45f20b1d..9675ec77 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -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"; diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts index 15ed740b..9654aaa6 100644 --- a/scripts/create-feature.ts +++ b/scripts/create-feature.ts @@ -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 { }); } +/** + * 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 [--context ] [--with-create [--keyed]] " + "[--package @scope/name@x.y.z --digest sha256:<64 hex> --revision ]"; @@ -1752,6 +1774,8 @@ function report(plan: FeaturePlan): string { " A failing gate's log is artifacts/quality/gates/FE-GATE-.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`; diff --git a/scripts/drill-runbook.ts b/scripts/drill-runbook.ts index c1c8c987..1607a8fd 100644 --- a/scripts/drill-runbook.ts +++ b/scripts/drill-runbook.ts @@ -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 diff --git a/scripts/lib/feature-residue.ts b/scripts/lib/feature-residue.ts new file mode 100644 index 00000000..2bcfc934 --- /dev/null +++ b/scripts/lib/feature-residue.ts @@ -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=` 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//` or `tests/features//`. 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 { + 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 { + 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(); +} diff --git a/scripts/lib/lab-performance.ts b/scripts/lib/lab-performance.ts index 0c01699d..2db190c9 100644 --- a/scripts/lib/lab-performance.ts +++ b/scripts/lib/lab-performance.ts @@ -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>, +): 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; diff --git a/scripts/lib/performance-budgets.ts b/scripts/lib/performance-budgets.ts index b2bf26b1..57c95fd4 100644 --- a/scripts/lib/performance-budgets.ts +++ b/scripts/lib/performance-budgets.ts @@ -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>; 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), diff --git a/scripts/lib/removal-fixture.ts b/scripts/lib/removal-fixture.ts index 9aa9bc80..9222d777 100644 --- a/scripts/lib/removal-fixture.ts +++ b/scripts/lib/removal-fixture.ts @@ -72,6 +72,8 @@ export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([ "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", ] as const); /** The tests a fixture copied from `copyTargets` cannot run. */ diff --git a/scripts/lib/vite-build-inputs.ts b/scripts/lib/vite-build-inputs.ts new file mode 100644 index 00000000..cc94af25 --- /dev/null +++ b/scripts/lib/vite-build-inputs.ts @@ -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); diff --git a/scripts/scale/measure-feature-shape-growth.ts b/scripts/scale/measure-feature-shape-growth.ts index ff162959..0fb5b724 100644 --- a/scripts/scale/measure-feature-shape-growth.ts +++ b/scripts/scale/measure-feature-shape-growth.ts @@ -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,17 +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/run-isolation.ts", - "scripts/lib/vite-module-inventory.ts", -] as const; // Platform-owned names that only happen to contain "reference". const PLATFORM_TOKENS = [ "REFERENCE_FEATURE_V1", @@ -111,7 +101,7 @@ async function copyRenamed(from: string, to: string, rename: (text: string) => s async function createFixture(features: number): Promise { 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 }); } @@ -226,24 +216,34 @@ export async function measureInitialJavascriptCosts(): Promise> = { - gzipBytes: 0.01, + const allowed: Readonly> = { + 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]}`); } diff --git a/scripts/test-performance.ts b/scripts/test-performance.ts index 4c82ebdb..9c054a3a 100644 --- a/scripts/test-performance.ts +++ b/scripts/test-performance.ts @@ -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 { - // Every run is a cold, isolated context. +type ClickMetrics = Omit; + +/** + * 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 { 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 { 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 { + // 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 { } } +/** + * 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 { + 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(); diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 88173ba0..8d91f788 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -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, @@ -419,14 +420,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[] = []; diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 77327a9a..55bdd490 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -217,8 +217,8 @@ export interface InstalledHttpContract { requestBody: "NONE" | "JSON"; responseBody: "REQUIRED_JSON" | "OPTIONAL_JSON" | "NONE"; /** - * 1101 README 14.3. How the server frames a JSON body. Absent or `"NONE"`: - * the body is the DTO, and a failure body is the problem. `"ENVELOPE_V1"`: + * 1101 README 14.3. How the server frames a JSON body. `"NONE"`: the body + * is the DTO, and a failure body is the problem. `"ENVELOPE_V1"`: * the paired backend's `{ success, data | error, meta }` * (clean-architecture-backend-template docs/web/http-contract.md §1). * `outputValidator` then sees `data` (`null` when the key is absent) and @@ -227,8 +227,16 @@ export interface InstalledHttpContract { * (`src/adapters/http/backend-envelope.ts`, the frontend contract's 6.1), * not from `commandEffect.classifyProblem`, which decides every other * status. A body that is empty by `emptyBodyStatuses` has no Envelope. + * + * 1103/16-01. Required: an operation added by hand without the line read + * the real backend's Envelope as a DTO, and assembly cannot tell a + * forgotten line from a bare backend when every operation of a + * contribution forgot it (a read-only contribution, or a write without + * `refusedBeforeWrite`). `check:types` now fails on the descriptor. A + * descriptor typed outside TypeScript that leaves it out still composes + * and reads as `"NONE"`. */ - responseEnvelope?: ResponseEnvelope; + responseEnvelope: ResponseEnvelope; commandRecovery: CommandRecoveryDescriptor | null; commandEffect: CommandEffectDescriptor | null; /** diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index b01ee5ba..08ada1ca 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -88,6 +88,7 @@ export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({ retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "NONE" as const, commandRecovery: null, commandEffect: null, projectRequest(input: z.output) { @@ -142,6 +143,7 @@ export const GET_REFERENCE_RESOURCE_CONTRACT = Object.freeze({ retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "NONE" as const, commandRecovery: null, commandEffect: null, projectRequest(input: z.output) { @@ -192,6 +194,7 @@ export const CREATE_REFERENCE_RESOURCE_CONTRACT = Object.freeze({ retrySemantics: "KEYED" as const, requestBody: "JSON" as const, responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "NONE" as const, commandRecovery: Object.freeze({ mode: "IDEMPOTENCY_REPLAY" as const, operationIdentityField: "idempotencyKey", diff --git a/src/presentation/examples/platform-overview-page.tsx b/src/presentation/examples/platform-overview-page.tsx index 1cf80f90..329d6a54 100644 --- a/src/presentation/examples/platform-overview-page.tsx +++ b/src/presentation/examples/platform-overview-page.tsx @@ -60,6 +60,23 @@ function Metric({ ); } +/** + * 1105/15-01. The release metrics before the summary resolves, or after it + * failed: the resolved metrics' labels and hint lines, so the grid keeps its + * height. The status takes the first card's value and stays short enough for + * one line in the narrowest card (13rem), as a build id does. + */ +function ReleaseMetricsPlaceholder({ status }: Readonly<{ status: string }>) { + return ( + <> + + + + + + ); +} + type RouteRow = (typeof ROUTE_REGISTRY)[keyof typeof ROUTE_REGISTRY]; const ROUTE_COLUMNS: readonly DataTableColumn[] = Object.freeze([ @@ -419,10 +436,18 @@ export function PlatformOverviewPage({ 부팅 시 경계 검사를 통과한 런타임 설정과 릴리스 매니페스트에서 옵니다.

-
- {release === "failed" ? ( - - ) : release ? ( + {/* 1105/15-01. The same four metrics, with the same hint lines, in + every state: the grid used to grow from one card to four with + hints once the summary resolved, about 30-100 ms after the title, + and pushed everything below it 21 px (CLS 0.0046 on a direct + visit). Only the values change; `aria-busy` says when they are + not there yet (the visual test waits on it). */} +
+ {release !== null && release !== "failed" ? ( <> @@ -450,7 +475,11 @@ export function PlatformOverviewPage({ /> ) : ( - + )}
diff --git a/src/presentation/styles/theme/base.css b/src/presentation/styles/theme/base.css index b0ecc0e6..71ccec31 100644 --- a/src/presentation/styles/theme/base.css +++ b/src/presentation/styles/theme/base.css @@ -3,6 +3,12 @@ color: var(--color-content); background: var(--color-surface); font-family: var(--font-sans); + /* 1105/15-05. The route loading surface fits a 720 px window and the + home page does not, so the first render added a classic (non-overlay) + scrollbar and pushed the header's right side 15 px left (CLS 0.0002 at + 1280x720 and 1366x657). The gutter is reserved from the first frame; + overlay scrollbars take no space either way. */ + scrollbar-gutter: stable; } body { diff --git a/tests/component/starter-platform-overview-page.test.tsx b/tests/component/starter-platform-overview-page.test.tsx index 3484238c..60aecfe7 100644 --- a/tests/component/starter-platform-overview-page.test.tsx +++ b/tests/component/starter-platform-overview-page.test.tsx @@ -233,13 +233,66 @@ describe("platform overview page", () => { }, }), }); + const region = screen.getByRole("region", { name: "릴리스 신원" }); await waitFor(() => expect( - screen.getByText("런타임 정보를 확인하지 못했습니다."), + within(metricByLabel(region, "빌드")).getByText("확인하지 못했습니다."), ).toBeVisible(), ); - expect( - screen.queryByText("런타임 정보를 확인하고 있습니다."), - ).not.toBeInTheDocument(); + expect(within(region).queryByText("확인하고 있습니다.")).not.toBeInTheDocument(); + }); + + /** + * 1105/15-01. The release metrics drew one "상태" card until the summary + * resolved, then four cards with hint lines: the grid grew by a hint line + * about 30-100 ms after the title and pushed the rest of the page 21 px + * (CLS 0.0046 on a direct visit). The cards and their hint lines are the + * same in every state; only the values change. + */ + it("keeps the release metrics' cards and hint lines while the summary loads", async () => { + const summary = { + buildId: "test-build", + releaseId: "test-release", + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: "test-hash", + routeChunks: { "route-home": "assets/home.js" }, + }; + let resolve: (value: typeof summary) => void = () => {}; + const pending = new Promise((settle) => { + resolve = settle; + }); + await renderPage({ + application: createTestApplication({ + releaseInfo: { getCurrent: () => pending, refresh: () => pending }, + }), + }); + const region = screen.getByRole("region", { name: "릴리스 신원" }); + const shape = () => + [...region.querySelectorAll(".platform-metric")].map((card) => [ + card.querySelector("dt")?.textContent, + card.querySelector(".platform-metric__hint") !== null, + ]); + + const loading = shape(); + expect(within(metricByLabel(region, "빌드")).getByText("확인하고 있습니다.")).toBeVisible(); + expect(region.querySelector("dl")).toHaveAttribute("aria-busy", "true"); + + await act(async () => { + resolve(summary); + await pending; + }); + await waitFor(() => + expect(within(metricByLabel(region, "빌드")).getByText("test-build")).toBeVisible(), + ); + + expect(loading).toEqual([ + ["빌드", false], + ["릴리스", false], + ["설정 스키마", true], + ["계약 집합 다이제스트", true], + ]); + expect(shape()).toEqual(loading); + expect(region.querySelector("dl")).toHaveAttribute("aria-busy", "false"); }); }); diff --git a/tests/contract/reusable-capability/feature-http-binding.test.ts b/tests/contract/reusable-capability/feature-http-binding.test.ts index 22bbf86c..b96600b5 100644 --- a/tests/contract/reusable-capability/feature-http-binding.test.ts +++ b/tests/contract/reusable-capability/feature-http-binding.test.ts @@ -44,6 +44,7 @@ const LOAD_RESOURCE_CONTRACT = Object.freeze({ retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "NONE" as const, commandRecovery: null, commandEffect: null, projectRequest(input: ResourceInput) { diff --git a/tests/helpers/external-contract-fixture.ts b/tests/helpers/external-contract-fixture.ts index a65e5f74..dc67cd01 100644 --- a/tests/helpers/external-contract-fixture.ts +++ b/tests/helpers/external-contract-fixture.ts @@ -64,6 +64,7 @@ export const TEST_LIST_HTTP_CONTRACT: InstalledHttpContract< retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "NONE" as const, commandRecovery: null, commandEffect: null, projectRequest(input: Readonly<{ limit: number }>) { @@ -99,6 +100,7 @@ export const TEST_DETAIL_HTTP_CONTRACT: InstalledHttpContract< retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "NONE" as const, commandRecovery: null, commandEffect: null, projectRequest(input: Readonly<{ entityId: string }>) { @@ -145,6 +147,7 @@ export const TEST_CREATE_HTTP_CONTRACT: InstalledHttpContract< retrySemantics: "KEYED" as const, requestBody: "JSON" as const, responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "NONE" as const, commandRecovery: Object.freeze({ mode: "IDEMPOTENCY_REPLAY" as const, operationIdentityField: "idempotencyKey", diff --git a/tests/unit/backend-contract-drift.test.ts b/tests/unit/backend-contract-drift.test.ts index de2144d0..343276e1 100644 --- a/tests/unit/backend-contract-drift.test.ts +++ b/tests/unit/backend-contract-drift.test.ts @@ -98,9 +98,30 @@ function git(cwd: string, ...args: string[]): string { return result.stdout.trim(); } -async function commitDocument(backend: string, text: string, message: string): Promise { - await mkdir(path.join(backend, "docs/web"), { recursive: true }); - await writeFile(path.join(backend, "docs/web/http-contract.md"), text); +const DOCUMENT = "docs/web/http-contract.md"; +/** + * 1105/16-02. One of the backend scaffold files `create:feature + * --with-create` copies a fact from (the aggregate's name limit). + */ +const AGGREGATE = + "scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl"; +const SCAFFOLD_SOURCES = [ + { + path: AGGREGATE, + fact: "NAME_MAX_LENGTH 100", + copiedTo: { file: "scripts/create-feature-write-slice.ts", symbol: "BACKEND_NAME_MAX_LENGTH" }, + }, +]; + +async function commitFiles( + backend: string, + files: Readonly>, + message: string, +): Promise { + for (const [file, text] of Object.entries(files)) { + await mkdir(path.dirname(path.join(backend, file)), { recursive: true }); + await writeFile(path.join(backend, file), text); + } git(backend, "add", "--all"); git(backend, "commit", "--quiet", "--no-gpg-sign", "--no-verify", "-m", message); return git(backend, "rev-parse", "HEAD"); @@ -113,6 +134,10 @@ async function drift( notCopied?: typeof NOT_COPIED; /** The document of a backend commit after the pin. */ head?: string; + /** 1105/16-02. The scaffold aggregate template in that later commit. */ + scaffoldHead?: string; + /** 1105/16-02. A file the pin does not name, in that later commit. */ + otherHead?: string; /** Where the script looks for the backend instead of the fake one. */ backend?: string; flags?: readonly string[]; @@ -122,13 +147,26 @@ async function drift( const backend = await mkdtemp(path.join(tmpdir(), "drift-backend-")); directories.push(root, backend); git(backend, "init", "--quiet", "--initial-branch=fixture"); - const commit = await commitDocument(backend, contractDocument(SECTIONS), "pinned"); - if (options.head !== undefined) await commitDocument(backend, options.head, "after the pin"); + const commit = await commitFiles( + backend, + { + [DOCUMENT]: contractDocument(SECTIONS), + [AGGREGATE]: "public static final int NAME_MAX_LENGTH = 100;\n", + "README.md": "backend\n", + }, + "pinned", + ); + const later = { + ...(options.head === undefined ? {} : { [DOCUMENT]: options.head }), + ...(options.scaffoldHead === undefined ? {} : { [AGGREGATE]: options.scaffoldHead }), + ...(options.otherHead === undefined ? {} : { "README.md": options.otherHead }), + }; + if (Object.keys(later).length > 0) await commitFiles(backend, later, "after the pin"); const source = { repository: "clean-architecture-backend-template", commit, - document: "docs/web/http-contract.md", + document: DOCUMENT, }; const write = async (file: string, value: unknown) => { await mkdir(path.dirname(path.join(root, file)), { recursive: true }); @@ -136,7 +174,7 @@ async function drift( }; await write("config/contracts/backend-contract-pin.json", { schemaVersion: 1, - backend: { ...source, sectionsCompared: ["1", "2", "4"] }, + backend: { ...source, sectionsCompared: ["1", "2", "4"], scaffoldSources: SCAFFOLD_SOURCES }, frontend: { contractDocument: "docs/architecture/backend-api-and-server-state-contract.md", contractSections: ["4.1", "6", "6.1"], @@ -265,3 +303,30 @@ describe("check:backend-contract-drift (1105/07-01)", () => { expect((await result.readExcerpt()).sections).toEqual(SECTIONS); }); }); + +/** + * 1105/16-02. `create:feature --with-create` copies four facts from the + * paired backend's feature scaffold (path plural rule, name limit 100, error + * codes, check order). The pin and this script covered only + * `docs/web/http-contract.md`, so a backend that changed its scaffold left + * the frontend generator writing another path, limit or code with no signal. + */ +describe("check:backend-contract-drift scaffold sources (1105/16-02)", () => { + it("reports a scaffold source the generator copies from, with where the copy is", async () => { + const result = await drift({ scaffoldHead: "public static final int NAME_MAX_LENGTH = 120;\n" }); + + expect(result.status, result.stdout + result.stderr).toBe(1); + expect(result.stderr).toContain(`scaffold source ${AGGREGATE} changed`); + expect(result.stderr).toContain( + "recheck BACKEND_NAME_MAX_LENGTH in scripts/create-feature-write-slice.ts", + ); + }); + + it("passes a later backend commit that changed neither the document nor a scaffold source", async () => { + const result = await drift({ otherHead: "backend, later\n" }); + + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + expect(result.stdout).toContain("1 scaffold sources unchanged"); + }); +}); diff --git a/tests/unit/backend-contract-pin.test.ts b/tests/unit/backend-contract-pin.test.ts index ff5f334f..f219960c 100644 --- a/tests/unit/backend-contract-pin.test.ts +++ b/tests/unit/backend-contract-pin.test.ts @@ -39,6 +39,20 @@ const pinSchema = z commit: z.string().regex(COMMIT), document: z.string().min(1), sectionsCompared: z.array(z.string().min(1)).min(1), + // 1105/16-02. Backend scaffold files the generator copies facts from. + scaffoldSources: z + .array( + z + .object({ + path: z.string().min(1), + fact: z.string().min(1), + copiedTo: z + .object({ file: z.string().min(1), symbol: z.string().min(1) }) + .strict(), + }) + .strict(), + ) + .min(1), }) .strict(), frontend: z @@ -164,6 +178,36 @@ describe("paired backend contract pin", () => { expect(answerTableProblems(table.answers, pin.notCopied, rows)).toEqual([]); }); + /** + * 1105/16-02. The `--with-create` slice copies the backend scaffold's path + * rule, name limit, error codes and check order. Each copy names the + * backend file it came from, so check:backend-contract-drift can say which + * frontend line to recheck when that file changes. + */ + it("names the backend scaffold file behind each fact the generator copies", () => { + const paths = pin.backend.scaffoldSources.map((source) => source.path); + expect(new Set(paths).size).toBe(paths.length); + for (const source of pin.backend.scaffoldSources) { + expect(readFileSync(source.copiedTo.file, "utf8"), source.path).toContain( + source.copiedTo.symbol, + ); + } + const copiedFiles = new Set(pin.backend.scaffoldSources.map((source) => source.copiedTo.file)); + expect([...copiedFiles].sort()).toEqual([ + "scripts/create-feature-write-slice.ts", + "scripts/create-feature.ts", + ]); + expect(paths).toEqual( + expect.arrayContaining([ + "scripts/new-feature.sh", + expect.stringMatching(/\/__Feature__\.java\.tmpl$/u), + expect.stringMatching(/\/__Feature__ErrorCode\.java\.tmpl$/u), + expect.stringMatching(/\/__Feature__Controller\.java\.tmpl$/u), + expect.stringMatching(/\/Create__Feature__UseCase\.java\.tmpl$/u), + ]), + ); + }); + it("copies each backend answer once", () => { const keys = table.answers.map((answer) => `${answer.status} ${answer.code}`); expect(new Set(keys).size).toBe(keys.length); diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index cfcaf99d..6b4fe279 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -382,6 +382,26 @@ describe("one wire frame per contribution (1103/16-01)", () => { expect(composed.contributions.map(({ http }) => http.length)).toEqual([1, 2]); }); + + /** + * 1103/16-01 (rest). Assembly cannot tell a forgotten line from a bare + * backend when every operation of a contribution forgot it: a read-only + * contribution, or a write without `refusedBeforeWrite`. The line is + * required by the descriptor type, so `check:types` fails on such a + * descriptor (the directive below fails it when the type stops requiring + * the line). A descriptor typed outside TypeScript still composes as NONE. + */ + it("requires the line on every descriptor at compile time", () => { + const { responseEnvelope: _dropped, ...withoutLine } = listRow.contract; + // @ts-expect-error 1103/16-01: responseEnvelope is required on a descriptor. + const descriptor: InstalledContractContribution["http"][number] = { ...listRow, contract: withoutLine }; + + const composed = composeContractContributions([contribution("read-only", [descriptor])]); + + expect( + composed.httpByOperationId.get("TEST_LIST_ENTITIES")?.contract.responseEnvelope ?? "NONE", + ).toBe("NONE"); + }); }); // The sample feature's own cases (its fixture composes, a second one does not) diff --git a/tests/unit/feature-residue.test.ts b/tests/unit/feature-residue.test.ts new file mode 100644 index 00000000..7ebbeff4 --- /dev/null +++ b/tests/unit/feature-residue.test.ts @@ -0,0 +1,73 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { productFeatureResidue } from "../../scripts/lib/feature-residue.ts"; + +/** + * 1105/16-04. The manual's example ID is `invoice-feature` (01 1단계), and + * its step 11 removes that feature with + * `test:sample-removal -- --feature=invoice-feature`. The drill searched every + * file under `src` and `tests` for the ID as a substring, so the template's + * own tests/unit/create-feature.test.ts, which writes that example ID 51 + * times as data, failed the removal (`fixture-id-residue`), and the advice + * was to edit that template file. + */ +const ID = "invoice-feature"; +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function fixture(files: Readonly>): Promise { + const root = await mkdtemp(path.join(tmpdir(), "feature-residue-")); + roots.push(root); + for (const [file, content] of Object.entries(files)) { + await mkdir(path.dirname(path.join(root, file)), { recursive: true }); + await writeFile(path.join(root, file), content); + } + return root; +} + +// Built at run time so this file does not itself read as an import of the +// feature when the repository is searched below. +const importOf = (target: string) => ["import { x } from", JSON.stringify(target)].join(" "); + +describe("product feature residue (1105/16-04)", () => { + it("does not count the template's own tests that name the manual's example ID", async () => { + expect(await productFeatureResidue(process.cwd(), ID, ID)).toEqual([]); + }); + + it("counts what still points at the removed feature", async () => { + const root = await fixture({ + "src/contracts/leftover.ts": `export const OWNER = "${ID}";\n`, + "src/platform/clean.ts": "export const NOTHING = 1;\n", + [`tests/e2e/${ID}.spec.ts`]: "test('opens', () => {});\n", + "tests/unit/imports-feature.test.ts": `${importOf(`../../src/features/${ID}/feature-module.ts`)};\n`, + "tests/unit/imports-feature-tests.test.ts": `${importOf(`../features/${ID}/helpers.ts`)};\n`, + "tests/unit/example-data.test.ts": `const request = { id: "${ID}" };\nconst path = "src/features/${ID}/feature-module.ts";\n`, + }); + + expect(await productFeatureResidue(root, ID, ID)).toEqual([ + "src/contracts/leftover.ts", + `tests/e2e/${ID}.spec.ts`, + "tests/unit/imports-feature-tests.test.ts", + "tests/unit/imports-feature.test.ts", + ]); + }); + + it("matches the folder name as well as the ID", async () => { + const root = await fixture({ + "src/contracts/leftover.ts": 'export const DIRECTORY = "invoices";\n', + "tests/unit/x.test.ts": `${importOf("../../src/features/invoices/index.ts")};\n`, + }); + + expect(await productFeatureResidue(root, ID, "invoices")).toEqual([ + "src/contracts/leftover.ts", + "tests/unit/x.test.ts", + ]); + }); +}); diff --git a/tests/unit/feature-shape-growth.test.ts b/tests/unit/feature-shape-growth.test.ts index fb267f0c..22ad957f 100644 --- a/tests/unit/feature-shape-growth.test.ts +++ b/tests/unit/feature-shape-growth.test.ts @@ -165,7 +165,14 @@ describe("feature-shape growth measurement (11-04)", () => { ).toEqual([]); }, 180_000); - it("reports a record more than 1% off the build, or a different file count", () => { + /** + * 1105/15-02. The total used to match within 1% (2,029 B at 202,927 B), + * more than the room left under the budget (1,873 B) and more than one + * feature (768 B), so a template change that took the room could leave the + * record. Now a few hundred bytes are enough to fail: above the build id + * spread (tens of bytes), below one feature. + */ + it("reports a record a few hundred bytes off the build, or a different file count", () => { const measured = { gzipBytes: 200_000, files: 25, @@ -173,9 +180,20 @@ describe("feature-shape growth measurement (11-04)", () => { perContextGzipBytes: 250, }; expect(initialJavascriptRecordDrift(measured, measured)).toEqual([]); + // The build id alone moves the total by tens of bytes. + expect( + initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 200_048 }), + ).toEqual([]); + expect( + initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 199_800 }), + ).toEqual([]); + // A template change that grows the initial JavaScript by 300 B. + expect( + initialJavascriptRecordDrift({ ...measured, gzipBytes: 200_300 }, measured), + ).toEqual(["gzipBytes: record 200000, build 200300"]); expect( initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 201_500 }), - ).toEqual([]); + ).toEqual(["gzipBytes: record 201500, build 200000"]); expect( initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 204_000 }), ).toEqual(["gzipBytes: record 204000, build 200000"]); diff --git a/tests/unit/feature-tracked-files.test.ts b/tests/unit/feature-tracked-files.test.ts new file mode 100644 index 00000000..c9e3ba33 --- /dev/null +++ b/tests/unit/feature-tracked-files.test.ts @@ -0,0 +1,58 @@ +import { readFile } from "node:fs/promises"; + +import { describe, expect, it } from "vitest"; + +import { FEATURE_TRACKED_FILE_REWRITES } from "../../scripts/create-feature.ts"; + +/** + * 1105/16-01. Adding a feature changes two tracked template files: the dev + * server's manifest (`create:feature` rewrites it) and, while the sample is + * installed, the initial JavaScript record (rewritten by command). The 03 + * manual's section A said the command writes two files outside the feature + * folder and named neither, the canonical table in starter-experience.md + * had neither, and nothing said what to do when two feature branches change + * the same `setDigest` line. The documents name each file with the command + * that rewrites it, which is also how a merge conflict on it is resolved. + */ +function between(text: string, start: string, end: string): string { + const from = text.indexOf(start); + const to = text.indexOf(end, from + start.length); + if (from < 0 || to < 0) throw new Error(`no section from "${start}" to "${end}"`); + return text.slice(from, to); +} + +describe("tracked files a feature changes (1105/16-01)", () => { + it("lists the generator's tracked rewrites", () => { + expect(FEATURE_TRACKED_FILE_REWRITES.map((file) => file.path)).toEqual([ + "public/release-manifest.json", + "config/scale/feature-shape-ceilings.json", + ]); + }); + + it("names each file and its rewrite command in the 03 manual's section A", async () => { + const section = between( + await readFile("docs/manual/03-outside-feature-folder.md", "utf8"), + "## A. 생성 명령이 만든다", + "## B. ", + ); + for (const file of FEATURE_TRACKED_FILE_REWRITES) { + expect(section, file.path).toContain(file.path); + expect(section, file.path).toContain(file.command); + } + expect(section).toMatch(/충돌/u); + }); + + it("names each file and its rewrite command in the canonical table", async () => { + const table = between( + await readFile("docs/architecture/starter-experience.md", "utf8"), + "Files outside the feature directory.", + "The central catalogs", + ); + for (const file of FEATURE_TRACKED_FILE_REWRITES) { + const row = table.split("\n").find((line) => line.startsWith("|") && line.includes(file.path)); + expect(row, file.path).toBeDefined(); + expect(row, file.path).toContain(file.command); + expect(row, file.path).toMatch(/merge conflict/u); + } + }); +}); diff --git a/tests/unit/lab-performance.test.ts b/tests/unit/lab-performance.test.ts index c3ea9d82..03e88a95 100644 --- a/tests/unit/lab-performance.test.ts +++ b/tests/unit/lab-performance.test.ts @@ -1,4 +1,5 @@ import { spawn } from "node:child_process"; +import { readFile } from "node:fs/promises"; import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; import path from "node:path"; @@ -8,9 +9,16 @@ import { afterEach, describe, expect, it } from "vitest"; import { assertPortUnused, assertServedRelease, + labBrowserLaunchOptions, + labFeatureRoute, previewArguments, summarizeSamples, } from "../../scripts/lib/lab-performance.ts"; +import { + NAVIGATION_ROUTES, + ROUTE_FEATURE_OWNER, + ROUTE_REGISTRY, +} from "../../src/features/installed-feature-contracts.ts"; /** * 11-07. The lab performance gate measured once, and measured whatever server @@ -104,3 +112,76 @@ describe("lab performance gate (11-07)", () => { expect(stderr).toMatch(/another server holds the port/u); }, 30_000); }); + +/** + * 1105/15-05. The home page's first render added a vertical scrollbar and + * pushed the header's right side 15 px (CLS 0.0002 at 1280x720 and + * 1366x657). Every gate's Chromium hid scrollbars, the lab included, so no + * gate could see it. The page reserves the gutter, and the lab measures with + * the scrollbar a Windows or Linux desktop draws. + */ +describe("lab performance with real scrollbars (1105/15-05)", () => { + it("starts Chromium without Playwright's --hide-scrollbars", () => { + expect(labBrowserLaunchOptions().ignoreDefaultArgs).toContain("--hide-scrollbars"); + }); + + it("reserves the root scrollbar gutter before the first route renders", async () => { + const base = await readFile("src/presentation/styles/theme/base.css", "utf8"); + const root = base.match(/:root\s*\{([^}]*)\}/u)?.[1] ?? ""; + + expect(root).toMatch(/scrollbar-gutter:\s*stable\s*;/u); + }); +}); + +/** + * 1105/15-04. The lab timed only the platform screen, which loads no feature + * code; a feature route's first entry (two request rounds, 406 ms under the + * lab conditions) had no gate. The lab now times the first public navigation + * route an installed feature owns, with the same clock. + */ +describe("lab feature route (1105/15-04)", () => { + const route = ( + routeId: string, + navigationOrder: number | null, + access: "public" | "session-required" = "public", + ) => ({ + routeId, + path: `/${routeId.toLowerCase()}`, + access, + title: routeId, + navigationLabel: navigationOrder === null ? null : routeId, + navigationOrder, + }); + + it("takes the first public navigation route a feature owns", () => { + const routes = [ + route("APP_HOME", 10), + route("EXAMPLES_PLATFORM", 15), + route("ORDERS_LIST", 50, "session-required"), + route("ORDERS_DETAIL", null), + route("GALLERY", 30), + route("CATALOG", 20), + ]; + const owners = { + ORDERS_LIST: "orders-feature", + ORDERS_DETAIL: "orders-feature", + GALLERY: "gallery-feature", + CATALOG: "catalog-feature", + }; + + expect(labFeatureRoute(routes, owners)?.routeId).toBe("CATALOG"); + expect(labFeatureRoute(routes, { ORDERS_LIST: "orders-feature" })).toBeNull(); + expect(labFeatureRoute(routes, {})).toBeNull(); + }); + + it("finds one in the installed registry while a feature has a public screen", () => { + const selected = labFeatureRoute(Object.values(ROUTE_REGISTRY), ROUTE_FEATURE_OWNER); + const publicFeatureRoutes = NAVIGATION_ROUTES.filter( + (definition) => + definition.access === "public" && ROUTE_FEATURE_OWNER[definition.routeId] !== undefined, + ); + + expect(selected?.routeId ?? null).toBe(publicFeatureRoutes[0]?.routeId ?? null); + if (selected) expect(ROUTE_FEATURE_OWNER[selected.routeId]).toEqual(expect.any(String)); + }); +}); diff --git a/tests/unit/performance-budgets.test.ts b/tests/unit/performance-budgets.test.ts index 7cff0612..220a001b 100644 --- a/tests/unit/performance-budgets.test.ts +++ b/tests/unit/performance-budgets.test.ts @@ -1,3 +1,5 @@ +import { readFile } from "node:fs/promises"; + import { describe, expect, it } from "vitest"; import { @@ -39,10 +41,10 @@ describe("performance budgets", () => { }); it("fails lab evidence when context is absent or a metric is over budget", () => { - const thresholds = { lcpMs: 2500, cls: 0.1, namedInteractionMs: 200 }; + const thresholds = { lcpMs: 2500, cls: 0.1, namedInteractionMs: 200, featureRouteInteractionMs: 500 }; expect( evaluateLabBudget( - { metrics: { lcpMs: 1000, cls: 0, namedInteractionMs: 50 } }, + { metrics: { lcpMs: 1000, cls: 0, namedInteractionMs: 50, targetDeepLinkCls: 0, featureRouteInteractionMs: null } }, thresholds, ), ).toMatchObject({ passed: false }); @@ -58,13 +60,82 @@ describe("performance budgets", () => { cache: {}, build: {}, }, - metrics: { lcpMs: 2501, cls: 0, namedInteractionMs: 50 }, + metrics: { lcpMs: 2501, cls: 0, namedInteractionMs: 50, targetDeepLinkCls: 0, featureRouteInteractionMs: null }, }, thresholds, ).passed, ).toBe(false); }); + /** + * 1105/15-01. The lab entered its target route only by a click, and a + * shift within 500 ms of a click is left out of CLS. The target screen + * pushed its content 21 px after its title and the lab reported 0. The + * direct visit's CLS is judged against the same threshold. + */ + it("fails lab evidence when a direct visit to the target route shifts over the CLS budget", () => { + const thresholds = { lcpMs: 2500, cls: 0.1, namedInteractionMs: 200, featureRouteInteractionMs: 500 }; + const context = { + runner: {}, + browser: {}, + viewport: {}, + network: {}, + cpu: {}, + cache: {}, + build: {}, + }; + const metrics = { lcpMs: 1000, cls: 0, namedInteractionMs: 50, targetDeepLinkCls: 0.0046, featureRouteInteractionMs: 406 }; + + expect(evaluateLabBudget({ context, metrics }, thresholds).passed).toBe(true); + const shifted = evaluateLabBudget( + { context, metrics: { ...metrics, targetDeepLinkCls: 0.11 } }, + thresholds, + ); + expect(shifted.passed).toBe(false); + expect(shifted.results).toMatchObject({ cls: true, targetDeepLinkCls: false }); + }); + + /** + * 1105/15-04. The lab timed only the platform screen, which loads no + * feature code. A feature route's first entry took 406 ms (403-410) under + * the lab conditions at 8a44226, two request rounds (the context route + * module, then the page chunk, the second about 100 ms), and no gate + * measured it. The committed budget passes that entry and fails it with + * one more round of that size. + */ + it("judges the feature route entry against its committed budget", async () => { + const { lab: thresholds } = JSON.parse( + await readFile("config/performance/budgets.json", "utf8"), + ) as { lab: Parameters[1] }; + const context = { + runner: {}, + browser: {}, + viewport: {}, + network: {}, + cpu: {}, + cache: {}, + build: {}, + }; + const metrics = { + lcpMs: 1000, + cls: 0, + namedInteractionMs: 150, + targetDeepLinkCls: 0, + featureRouteInteractionMs: 406, + }; + const judged = (featureRouteInteractionMs: number | null) => + evaluateLabBudget({ context, metrics: { ...metrics, featureRouteInteractionMs } }, thresholds); + + expect(thresholds.featureRouteInteractionMs).toEqual(expect.any(Number)); + expect(judged(406).passed).toBe(true); + expect(judged(406 + 110)).toMatchObject({ + passed: false, + results: { namedInteraction: true, featureRouteInteraction: false }, + }); + // No installed feature owns a public navigation route: nothing to judge. + expect(judged(null).passed).toBe(true); + }); + it("uses the nearest-rank p75 and fails closed while sample minimum is deferred", () => { expect(percentile75([4, 1, 3, 2])).toBe(3); expect( diff --git a/tests/unit/product-feature-selection-build.test.ts b/tests/unit/product-feature-selection-build.test.ts index 0828abc8..c9e665ea 100644 --- a/tests/unit/product-feature-selection-build.test.ts +++ b/tests/unit/product-feature-selection-build.test.ts @@ -8,6 +8,7 @@ import { afterAll, describe, expect, it } from "vitest"; import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts"; import { filesBelow } from "../../scripts/lib/removal-fixture.ts"; +import { VITE_BUILD_INPUTS } from "../../scripts/lib/vite-build-inputs.ts"; import { ROUTE_FEATURE_OWNER } from "../../src/features/installed-feature-contracts.ts"; import { COMPILED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts"; @@ -16,20 +17,10 @@ import { COMPILED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-produ * every consumer, not only the browser bundle: the generated context index * (router), the installed contract contributions (Node contract-set * generation) and the built assets. This runs the production generator and a - * Vite build over a copy of the build inputs. Written against whatever - * features the tree declares, so it holds after the sample's removal too. + * Vite build over a copy of the build inputs (scripts/lib/vite-build-inputs.ts, + * 1105/15-03). Written against whatever features the tree declares, so it + * holds after the sample's removal too. */ -const BUILD_INPUTS = [ - "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; // Feature ids stay: the generated index still declares them so the platform // overview reports NOT_INSTALLED. Their modules and route ids go. const FEATURE_ROUTE_IDS = Object.keys(ROUTE_FEATURE_OWNER); @@ -45,7 +36,7 @@ describe("VITE_PRODUCT_FEATURES=none build (09-02)", () => { it("leaves every feature out of the context index, the contract set and dist", async () => { const root = await mkdtemp(path.join(tmpdir(), "product-selection-build-")); roots.push(root); - 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 }); } diff --git a/tests/unit/vite-build-inputs.test.ts b/tests/unit/vite-build-inputs.test.ts new file mode 100644 index 00000000..228272c1 --- /dev/null +++ b/tests/unit/vite-build-inputs.test.ts @@ -0,0 +1,72 @@ +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +/** + * 1105/15-03. Two copies of the list of files `vite build` reads from the + * root (the initial JavaScript measurement and the + * `VITE_PRODUCT_FEATURES=none` build test) had to change together each time + * vite.config.ts imported a new local file (7f9a515, 799ab7f), and a missed + * copy failed with an unexplained "Could not resolve". There is one list + * now, and it has to cover what vite.config.ts imports. + */ +const LIST_MODULE = "scripts/lib/vite-build-inputs.ts"; +// The measurement goes with the reference feature it copies +// (test:sample-removal), so a project without that feature checks the build +// test alone. In the template, tests/unit/feature-shape-growth.test.ts +// imports the measurement and fails if the file is gone. +const CONSUMERS = [ + "scripts/scale/measure-feature-shape-growth.ts", + "tests/unit/product-feature-selection-build.test.ts", +].filter((file) => existsSync(file)); + +const LOCAL_IMPORT = + /\bfrom\s+["'](\.{1,2}\/[^"']+)["']|\bimport\s+["'](\.{1,2}\/[^"']+)["']/gu; + +/** Every repository file vite.config.ts reaches through relative imports. */ +function localImportGraph(entry: string): string[] { + const seen = new Set(); + const pending = [entry]; + while (pending.length > 0) { + const file = pending.pop()!; + if (seen.has(file)) continue; + seen.add(file); + const source = readFileSync(file, "utf8"); + for (const match of source.matchAll(LOCAL_IMPORT)) { + const specifier = match[1] ?? match[2]!; + const resolved = path + .relative(process.cwd(), path.resolve(path.dirname(file), specifier)) + .split(path.sep) + .join("/"); + if (existsSync(resolved)) pending.push(resolved); + } + } + return [...seen]; +} + +describe("vite build inputs (1105/15-03)", () => { + it("defines the list in one module that both builds import", () => { + for (const consumer of CONSUMERS) { + const source = readFileSync(consumer, "utf8"); + expect(source, consumer).not.toMatch(/\bconst BUILD_INPUTS\s*=/u); + expect(source, consumer).toMatch(/\bVITE_BUILD_INPUTS\b/u); + expect(source, consumer).toContain("vite-build-inputs.ts"); + } + }); + + it("covers every local file vite.config.ts imports", async () => { + // Imported here, not at the top, so the first test still reports the + // copies when the module is missing. + const { VITE_BUILD_INPUTS } = await import("../../scripts/lib/vite-build-inputs.ts"); + const covered = (file: string) => + VITE_BUILD_INPUTS.some((input) => file === input || file.startsWith(`${input}/`)); + + const missing = localImportGraph("vite.config.ts").filter((file) => !covered(file)); + + expect( + missing, + `vite.config.ts reads files ${LIST_MODULE} does not copy; add them there`, + ).toEqual([]); + }); +}); diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png index 03f375b5..5fc74252 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png index 866717e6..eef93379 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png index ba71b3c7..b5f4a480 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png index ff0a7948..8487c073 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png index 41181671..fae126f6 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png differ