chore(layout): R2·R5 검사를 저장소 전체와 소유자 기준으로 마무리한다 #18

Merged
donghyeon.kang merged 7 commits from chore/layout-rules-r2-r5 into main 2026-11-11 23:29:49 +00:00
22 changed files with 594 additions and 202 deletions
+2 -2
View File
@@ -11,8 +11,8 @@ coverage/
# artifacts/ is run output and is ignored as a whole. Ignoring it by extension
# let screenshots and a coverage report in (0929/14-01) and step logs until
# they got their own rule (1103/12-08).
# Only the folder markers and the manual a11y reviews, which people write and
# the a11y gates read (config/ci/gates.json), are tracked;
# Only the folder markers are tracked (R3); the manual a11y reviews people
# write are in docs/accessibility/route-reviews/.
# tests/unit/tracked-artifacts.test.ts keeps it so. Git cannot re-include a
# file under an ignored folder, so each folder on the way is re-included and
# its contents ignored again.
+11 -5
View File
@@ -43,7 +43,7 @@
## 미출시 — `48c7695b` → 정리 단계
2026-11-07 소유자가 지시한 저장소 정리다(design-docs `repo-structure/04-frontend-layout.md` 9.2절, 결정은 `repo-structure/README.md` 3.4절). 범위는 `main` `48c7695b`(PR #9 병합) 다음부터다. 1단계(PR #11, `85f941c4`~`121e1125`, `main` `f33e4778`에 합침), 2단계(브랜치 `chore/layout-2-sample-removal`, `c7e80f2f`~`ad3a071f`), 3단계(합치기)와 4단계(배치 규칙 검사)(브랜치 `chore/layout-3-merge`, `bf485f44`~`c54c3813`), CI 재편(브랜치 `chore/ci-merge-jobs`, `0739f26b`부터 브랜치 끝까지), 문서 체계 단계(브랜치 `claude/fe-b-docs-korean-645f55`, `99e76e87`부터 브랜치 끝까지. design-docs `conventions/docs-system.md`)를 담는다. 기준점 `48c7695b`를 빼면 이 절의 해시는 모두 이 범위에 있다.
2026-11-07 소유자가 지시한 저장소 정리다(design-docs `repo-structure/04-frontend-layout.md` 9.2절, 결정은 `repo-structure/README.md` 3.4절). 범위는 `main` `48c7695b`(PR #9 병합) 다음부터다. 1단계(PR #11, `85f941c4`~`121e1125`, `main` `f33e4778`에 합침), 2단계(브랜치 `chore/layout-2-sample-removal`, `c7e80f2f`~`ad3a071f`), 3단계(합치기)와 4단계(배치 규칙 검사)(브랜치 `chore/layout-3-merge`, `bf485f44`~`c54c3813`), CI 재편(브랜치 `chore/ci-merge-jobs`, `0739f26b`부터 브랜치 끝까지), 문서 체계 단계(브랜치 `claude/fe-b-docs-korean-645f55`, `99e76e87`부터 브랜치 끝까지. design-docs `conventions/docs-system.md`), 4단계에 남은 R2·R5 검사(브랜치 `chore/layout-rules-r2-r5`, `3f64c689`부터 브랜치 끝까지)를 담는다. 기준점 `48c7695b`를 빼면 이 절의 해시는 모두 이 범위에 있다.
### 먼저 할 일 (BREAKING)
@@ -71,13 +71,15 @@
12. **CI 계약 기준선을 자기 값으로 다시 기록한 프로젝트는 다시 기록한다.** FE-GATE-003 명령이 25개에서 2개로, FE-GATE-009·028의 수동 a11y 기록 산출물 경로와 id가 바뀌었다. 4단계와 같은 명령이다 (`bf485f44`, `79dc945a`)
13. **CI 계약 기준선 파일이 없어졌다.** `config/ci/contract-baseline.json`, `scripts/update-ci-contract-baseline.ts`, `update:ci-contract-baseline` script를 지웠다(소유자 결정). 위 12단계와 이 절 4단계, 아래 절들의 "기준선을 다시 기록한다"는 이 절까지 받으면 할 일이 없다. 병합에서 자기 기준선 파일이 수정/삭제 충돌이 되면 삭제 쪽을 고른다. 자기 script나 문서가 `update:ci-contract-baseline`을 부르면 지운다 (`f6b2b96c`)
14. **merge 단계 job 이름이 바뀌었다.** 게이트마다 하나이던 행렬 job(`FE-GATE-NNN / <이름>`)이 `merge / static checks`(`merge_static`), `merge / tests`(`merge_test`), `merge / browser tests`(`merge_browser`) 셋이 됐다. 게이트는 job 안의 단계 이름(`FE-GATE-NNN / <이름>`)으로 남는다. Gitea 브랜치 보호의 필수 검사를 옛 job 이름으로 걸었으면 새 job 셋으로 바꾼다. 증거 업로드 이름도 `FE-GATE-NNN-<run>`에서 `merge-static-<run>`·`merge-test-<run>`·`merge-browser-<run>`으로 바뀌었다 (`0739f26b`)
15. **코드에 적은 루트 경로 목록을 등록부 집합으로 바꾼다.** R2 검사가 등록부를 쓰는 7곳이 아니라 추적되는 코드 파일 전체를 본다. 루트 항목(이나 그 안 경로)만 담은 문자열 배열에 추적되는 루트 이름이 둘 이상이면 `tests/unit/repository-layout.test.ts`가 `choose a set from config/repository-layout.json with selectRepositoryPaths`로 실패한다. 템플릿의 19개 목록은 집합 12개로 옮겼다. 자기 목록은 맞는 집합을 고르거나, 없으면 `scripts/lib/repository-layout.ts`의 `REPOSITORY_LAYOUT_SETS`와 등록부 `sets` 설명에 집합을 더해 고른다. 시험이 메모리 안에 만드는 가상 저장소의 경로 목록(실제 루트 항목을 옮겨도 바뀌지 않는 것)은 `tests/unit/repository-layout.test.ts`의 `MADE_UP_REPOSITORY_LISTS`에 파일·목록·이유를 적는다. 사본이 건너뛰는 `node_modules`·`dist` 같은 추적 안 하는 항목은 종류 `untracked`, `optional: true`로 적는다(매뉴얼 03 E절 R1·R2) (`3f64c689`)
16. **샘플을 목록에 둔 프로젝트는 게이트 대상이 샘플 소유가 아닌지 본다.** R5 검사가 문자열 검색 대신 대상의 소유자를 따라간다: goto 경로 → 라우트 표의 기능, workshop story id → stories 파일, spec의 import → 불러오는 파일, 게이트 명령 → package script와 경로 인자, `sourceFeature` → 기능. `config/ci/gates.json`의 수동 a11y 기록이 라우트 표에 없는 라우트를 가리켜도 실패한다(지운 기능의 기록을 남긴 경우) (`1f57c38e`)
7. **자기 문서를 새 문서 검사에 맞춘다.** `verify:documentation`(FE-GATE-017)이 살아 있는 문서 전부(루트 `README.md`, `docs/` 아래 기록 밖 문서, 모듈 README)를 본다: 본문이 한국어인지, 「~한다」 체인지, 버전·개수를 복사하지 않았는지, 적은 경로·script·게이트 ID가 있는지. 루트 README는 `## 프로젝트 구조`부터 `## 규칙과 기여`까지 정해진 절을 순서대로 가져야 하고, `docs/README.md`는 `docs/` 아래 모든 폴더를 표 첫 칸 `폴더/`로 덮어야 한다. 자기 기록(`docs/design/`, `docs/history/`, `docs/adr/`)은 맨 위에 머리 블록을 단다(형식은 템플릿 `docs/README.md` 3절). 한 번에 다 고칠 수 없으면 걸린 줄을 `scripts/docs-system-exceptions.txt`에 기준선으로 적고 그 지문을 `scripts/lib/docs-system.ts`의 `FROZEN`에 넣는다. 그 목록은 줄기만 한다 (`7a9aefdf`)
8. **README의 바뀐 절 이름을 따른다.** 「Files you can delete after copying」은 「복사한 뒤 지워도 되는 것」이다. `verify:documentation`이 이 제목 아래 표의 첫 칸으로 지워도 되는 경로를 읽는다. 자기 README를 템플릿 README로 받았으면 이 제목을 지킨다 (`7a9aefdf`)
#### 옮긴 뒤 확인
1. 로컬 merge 게이트 14개를 돈다. 이 절 때문에 먼저 볼 것: `check:registries`(3단계), `check:ci`(4·12단계), `test:unit`(5·9·11단계), `generate:feature-index`(6단계), `check:types`·`check:types:fixtures`(7·8단계), `verify:documentation`(지운 샘플 경로를 적은 자기 문서, 9단계, 매뉴얼 03 E절 R6·R7), `test:sample-removal`(인자 없이 돌면 목록이 빈 템플릿에서는 `SKIP`을 출력한다).
1. 로컬 merge 게이트 14개를 돈다. 이 절 때문에 먼저 볼 것: `check:registries`(3단계), `check:ci`(4·12단계), `test:unit`(5·9·11·15·16단계), `generate:feature-index`(6단계), `check:types`·`check:types:fixtures`(7·8단계), `verify:documentation`(지운 샘플 경로를 적은 자기 문서, 9단계, 매뉴얼 03 E절 R6·R7), `test:sample-removal`(인자 없이 돌면 목록이 빈 템플릿에서는 `SKIP`을 출력한다).
- 검사기의 음성 fixture 명령 15개와 ungated 검사(`check:ci:gating`)는 PR이 아니라 브랜치 push의 FE-GATE-029(`main_gate`)에서 돈다. 새 시험 파일이나 검증 script를 게이트에 걸지 않으면 PR은 통과하고 main push가 실패한다. 로컬에서는 `corepack pnpm ci:gate FE-GATE-029`로 미리 본다 (`f6b2b96c`).
2. 시각 골든: 갤러리 두 장(`design-system-gallery-dark`, `state-surfaces-light`)은 이제 Storybook 정적 빌드의 story를 찍는다. 자기 골든을 다시 찍은 프로젝트는 `corepack pnpm test:visual:update`로 그 둘을 다시 찍는다.
3. `/examples/ui`·`/examples/states`·`/examples/auth`를 열던 자기 e2e는 플랫폼 라우트나 자기 화면으로 옮긴다. 템플릿의 그런 spec은 옮겼다(아래 표).
@@ -96,6 +98,7 @@
| [계약] **BREAKING** | 음성 타입 fixture 23개를 실행기 하나로 돈다. fixture 첫 줄의 `// expect:`가 기대이고, 판정은 전과 같다(tsc exit 1과 `error TS<code>:`). fixture별 결과와 맞은 진단 줄을 출력한다. `TelemetryPort.emit` 인자를 넓히는 변이(0925/07-05)에서 실패하는 것을 확인했다. recipes tsconfig는 test에 합쳤고 web-worker tsconfig(0파일 검사)는 지웠다(결정 D4). 위 "먼저 할 일" 7·8 | `scripts/check-type-fixtures.ts`, `scripts/check-typecheck-inputs.ts`, `tests/fixtures/typecheck/`, `package.json`, `config/ci/gates.json` | `bf485f44` |
| [계약] **BREAKING** | 루트 등록부 `config/repository-layout.json`이 생겼다. 루트 경로 목록을 쓰던 7곳(복사 대상, 비밀값 검사 범위, 공급망 시험, 이력 문서 검사, 규모 입력, vite 입력, TS 전용 규칙)이 등록부의 집합을 고른다. `schemas/`·수동 a11y 기록·hosting 응답 fixture를 옮겼다. 위 "먼저 할 일" 9~11 | `config/repository-layout.json`, `scripts/lib/repository-layout.ts`, `config/schemas/`, `docs/accessibility/route-reviews/`, `tests/fixtures/hosting/` | `79dc945a` |
| [계약] | 저장소 배치 규칙 R1~R10을 매뉴얼 03 E절에 적고, 기계로 볼 수 있는 것을 게이트에 넣었다: R1·R2·R7(파일)·R9 `tests/unit/repository-layout.test.ts`, R3 `tests/unit/tracked-artifacts.test.ts`, R4·R5 `tests/unit/example-feature-rules.test.ts`(이상 FE-GATE-005), R6·R7(문서) `verify:documentation`(FE-GATE-017, 산출물에 `layoutRuleViolations`), R8 FE-GATE-003 | `docs/manual/03-outside-feature-folder.md`, `scripts/verify-documentation-readiness.ts`, `scripts/contracts/release-artifacts.ts` | `e902e657` |
| [계약] **BREAKING** | R2 검사를 추적되는 코드 파일 전체로 넓히고 남은 루트 경로 목록 19개를 등록부 집합 12개로 옮겼다. 등록부에 종류 `untracked`가 생겼다. R5 검사는 게이트 대상을 라우트 표·stories 파일·import·package script 그래프·규모 기록 필드로 따라가 소유자를 본다. 위 "먼저 할 일" 15·16 | `config/repository-layout.json`, `scripts/lib/repository-layout.ts`, `tests/unit/repository-layout.test.ts`, `tests/unit/example-feature-rules.test.ts` | `3f64c689`, `1f57c38e` |
| [계약] **BREAKING** | merge 단계 job 14개(게이트마다 행렬 하나)를 셋으로 합쳤다. job마다 설치를 한 번 하고 게이트를 차례로 돈다. 앞 게이트가 실패해도 다음 게이트가 돈다(`if: ${{ !cancelled() }}`). release 단계는 세 job을 모두 기다린다. 위 "먼저 할 일" 14 | `config/ci/gates.json` `jobs`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `.gitea/workflows/quality-gates.yml` | `0739f26b` |
| [계약] **BREAKING** | 새 단계 `main`(`MAIN_READY`, 승격을 막지 않음)과 게이트 FE-GATE-029 `checker-self-tests`. FE-GATE-001·005·008·010·013의 `*:fixture` 명령 15개와 그 증거, `check:ci`의 ungated 검사(`check:ci:gating`으로 뗌)를 옮겼다. merge 단계 명령 참조 64 → 49. 음성 타입 fixture(`check:types:fixtures`)는 src 타입 계약 시험이라 merge에 남겼다. CI 계약 기준선 파일은 지웠다. 위 "먼저 할 일" 13 | `config/ci/gates.json`, `scripts/check-ci-gating.ts`, `scripts/lib/promotion-readiness.ts` | `f6b2b96c` |
| [계약] **BREAKING** | 문서 체계 검사가 생겼다. `verify:documentation`이 백엔드 `check-docs.py`와 같은 규칙 여섯(language, head, number, map, readme, style)을 `scripts/lib/docs-system.ts`로 돌리고, 참조 검사의 대상이 `docs/README.md` 1절이 링크한 문서에서 살아 있는 문서 전부로 넓어졌다. pull request에서는 FE-GATE-005의 `tests/unit/documentation-readiness.test.ts`가 이 repo로 `verify:documentation`을 돌리므로 문서가 걸리면 merge 단계가 실패한다. 예외 목록(`scripts/docs-system-exceptions.txt`)은 비어 있고 줄기만 한다. 위 "먼저 할 일" 7 | `scripts/lib/docs-system.ts`, `scripts/verify-documentation-readiness.ts`, `scripts/docs-system-exceptions.txt`, `docs/README.md` | `7a9aefdf` |
@@ -111,6 +114,7 @@
- 매뉴얼(`docs/manual/`)의 예제 칸은 생성기 출력 경로와 매뉴얼 안 코드 조각을 가리킨다. 코드 조각 일곱 개(problem details 백엔드의 분류와 매핑, 도메인 모델, 검색값 읽기, 실패 행동, 403 페이지 시험)는 `tests/unit/manual-code-blocks.test.ts`가 생성 기능 위에서 타입 검사·lint·아키텍처 검사·동작 시험을 돌린다. problem details 예는 소유자 결정대로 02 결정표 4절에 있다 (`01cac930`).
- 기능 스위치 시험(`tests/component/product-feature-switch.test.tsx`)과 홈 시작 링크의 스위치 시험은 시험 전용 fixture 기능으로 옮겼다 (`e3c8db48`).
- 라우트 런타임 음성 fixture(`tests/fixtures/typecheck/invalid-route-runtime.ts`)는 라우트 하나만 뺀다. 빠진 라우트 수에 따라 TS2739와 TS2740으로 갈리던 진단이 TS2741 하나가 됐고 FE-GATE-003의 기대 진단도 바꿨다. 라우트가 3개로 줄자 옛 기대(TS2740)가 어긋났다 (`e47a0ab2`).
- provider 업로드 시험(`tests/system/ci-runner/ci-artifact-contract.test.ts`, FE-GATE-013)의 기준 fixture가 `.claude/`를 통째로 건너뛰었다. 그래서 하네스가 `.claude/`에 추적 파일을 둔 뒤로 finalizer 시험 18개가 공급망 생성의 `ENOENT … .claude/agents/arch-reviewer.md`로 실패했다. 이제 다른 worktree가 있는 `.claude/worktrees`만 건너뛴다(등록부 `provider-fixture-skip`) (`ceaf21ea`).
- 살아 있는 문서를 모두 한국어로 옮겼다(현재 계약, 운영, runbook, 보안, 스타일, 접근성, 테스트, 모듈 README). 뜻은 바꾸지 않았고 백틱 안, 링크 대상, 절 번호, 표 구조는 그대로다. 문서를 읽는 테스트의 기대 문자열(`tests/unit/feature-tracked-files.test.ts`)과 절 이름을 인용한 주석을 같이 고쳤다 (`af10cae9`, `45e8cb77`, `11530b1a`).
- `check:remediation-ledger`는 옮긴 원장의 절 제목 `## 세 번째 재검토 (2026-08-14)`을 찾고, 「모두 닫혔다」를 한국어로도 잡는다 (`45e8cb77`).
@@ -123,9 +127,11 @@
### 알려진 제한
- 두 다운스트림에 시험 병합을 하지 않아 충돌 수를 모른다(S4 가정 F4).
- R2 검사는 등록부를 쓰는 7곳만 본다. 그 밖에 루트 이름 둘 이상을 담은 문자열 배열이 약 20곳 남았다(예: `tests/e2e/support/fixture-builds.ts`의 복사 제외 목록, `scripts/check-test-evidence.ts`의 playwright 설정 목록). 뜻이 다른 목록이라 이번에 옮기지 않았다.
- R5는 문자열 검색이라 샘플 ID나 라우트 경로를 조립해 쓰는 시험은 놓친다.
- CI 재편(merge job 셋, main 단계)은 desktop에서 게이트 명령으로 확인했다. Gitea runner에서 새 workflow가 도는지는 Actions를 켠 뒤 확인한다.
- (해결, `3f64c689`) R2 검사는 등록부를 쓰는 7곳만 본다. 그 밖에 루트 이름 둘 이상을 담은 문자열 배열이 약 20곳 남았다(예: `tests/e2e/support/fixture-builds.ts`의 복사 제외 목록, `scripts/check-test-evidence.ts`의 playwright 설정 목록). 뜻이 다른 목록이라 이번에 옮기지 않았다.
- (해결, `1f57c38e`) R5는 문자열 검색이라 샘플 ID나 라우트 경로를 조립해 쓰는 시험은 놓친다.
- R2 검사는 코드의 문자열 배열만 본다. 정규식의 대안 목록, 객체 키, `package.json` script 인자, tsconfig `include`의 루트 목록은 보지 않는다.
- R5 검사는 실행 때 정해지는 goto 대상(라우트 표 전체를 도는 a11y spec, 생성 기능의 경로)을 따라가지 않는다. 그런 spec이 샘플 모듈을 import하면 import 경로로 잡힌다.
- CI 재편(merge job 셋, main 단계)은 Gitea runner에서 돈다(2026-11-11 PR #16 실행 #5: job 셋이 시작하고 게이트별 단계와 `!cancelled()`가 동작). runner에서는 FE-GATE-005·020(`tests/unit/fixture-node-modules.test.ts` F-4 시험)과 FE-GATE-013(이미지에 bwrap 없음)이 실패한다. main의 옛 workflow도 같다.
- 성능 lab(FE-GATE-026)의 기능 라우트 측정(`featureRouteInteractionMs`)은 템플릿에 공개 기능 라우트가 없어 `measured: false`다. 제품 기능이 생기면 잰다.
- `TEMPLATE_FIXTURE` 출처와 `REFERENCE_EXTERNAL_BEARER` 별칭이 플랫폼 코드에 남았다. 쓰는 기능이 없다.
- visual 골든의 픽셀 비교는 색 허용치(`threshold` 0.2)를 넘지 않는 미세한 토큰 변경(예: 어두운 테마 `--color-danger` red-500 → red-600)을 잡지 못한다. 옛 골든도 같았다.
+113 -23
View File
@@ -6,7 +6,8 @@
"gate-input": "게이트와 런타임이 읽는 기준 데이터",
"document": "사람이 읽는 문서",
"history": "끝난 라운드의 기록. 이력 폴더로 옮길 대상이다(R10)",
"output": "실행 출력. 추적하는 것은 `.gitkeep`뿐이다(R3)"
"output": "실행 출력. 추적하는 것은 `.gitkeep`뿐이다(R3)",
"untracked": "추적하지 않는 로컬 항목(의존성·VCS·생성물·실행 출력·다른 worktree). 집합이 이름으로 고를 때만 적는다. 추적 파일이 없어야 한다"
},
"sets": {
"fixture-copy": "제거·생성 drill과 사본 시험이 복사하는 것(scripts/lib/removal-fixture.ts)",
@@ -15,14 +16,30 @@
"history-free": "이력 문서를 읽으면 안 되는 코드(tests/unit/deletable-history-documents.test.ts)",
"scale-source": "규모 증거에서 '지금 코드'를 정하는 입력(scripts/verify-extreme-scale.ts)",
"vite-build": "vite build가 읽는 입력(scripts/lib/vite-build-inputs.ts)",
"typescript-only": "JS 파일을 두면 안 되는 곳(scripts/check-architecture.ts)"
"typescript-only": "JS 파일을 두면 안 되는 곳(scripts/check-architecture.ts)",
"checkout-copy-skip": "저장소 전체를 임시 폴더로 복사하는 시험이 건너뛰는 항목(tests/e2e/support/fixture-builds.ts, tests/e2e/support/service-worker-builds.ts, tests/unit/run-output-root-build.test.ts)",
"provider-fixture-skip": "provider 업로드 시험의 기준 fixture가 복사하지 않는 항목과 경로. .claude는 다른 worktree만 건너뛴다(tests/system/ci-runner/ci-artifact-contract.test.ts)",
"supply-chain-fixture-skip": "공급망 provider fixture가 복사하지 않는 항목. artifacts는 따로 복사한다(scripts/check-supply-chain-provider-fixtures.ts, tests/integration/security-followup-archive.test.ts)",
"fixture-code": "사본을 만들고 node_modules를 잇는 코드가 있는 곳. linkFixtureNodeModules 규칙을 보는 범위(scripts/check-adapter-inventory.ts, tests/unit/fixture-node-modules.test.ts)",
"package-manifest": "pnpm 설치를 정하는 매니페스트(tests/unit/fixture-node-modules.test.ts)",
"playwright-configs": "자기 forbidOnly를 가져야 하는 Playwright 설정. dev 설정은 기본 설정을 펼친다(scripts/check-test-evidence.ts)",
"visual-evidence": "시험 증거 검사가 있어야 한다고 보는 visual·workshop 입력(scripts/check-test-evidence.ts)",
"documentation-inputs": "verify:documentation이 읽는 문서 입력. 문서 시험이 사본으로 복사한다(tests/unit/documentation-readiness.test.ts, tests/unit/template-feature-removal-documents.test.ts)",
"agent-harness": "에이전트 하네스 파일(tests/unit/template-contract-documents.test.ts)",
"feature-typecheck": "기능 코드와 기능 시험을 타입 검사하는 tsconfig(tests/unit/manual-code-blocks.test.ts)",
"product-typecheck": "제품 사본을 타입 검사하는 tsconfig(tests/unit/product-extension-typecheck.test.ts)",
"app-typecheck": "앱 프로그램 tsconfig와 그 기반 설정(tests/unit/two-feature-install-typecheck.test.ts)"
},
"entries": [
{
"path": ".claude",
"kind": "tool-convention",
"role": "Claude Code 설정·규칙·스킬·서브에이전트",
"readBy": "Claude Code"
"readBy": "Claude Code",
"sets": ["checkout-copy-skip", "agent-harness"],
"setPaths": {
"provider-fixture-skip": [".claude/worktrees"]
}
},
{
"path": ".dependency-cruiser.json",
@@ -37,6 +54,22 @@
"role": "빌드 시점 공개 변수의 견본",
"readBy": "Vite(VITE_*), 사람"
},
{
"path": ".generated",
"kind": "untracked",
"role": "빌드가 쓰는 런타임 생성물(.generated/frontend-runtime)",
"readBy": "scripts/build-frontend.ts, scripts/generate-contract-set.ts",
"optional": true,
"sets": ["checkout-copy-skip"]
},
{
"path": ".git",
"kind": "untracked",
"role": "git 저장소. worktree에서는 파일이다",
"readBy": "git",
"optional": true,
"sets": ["checkout-copy-skip"]
},
{
"path": ".gitattributes",
"kind": "tool-convention",
@@ -74,6 +107,14 @@
"readBy": "nvm, CI",
"sets": ["fixture-copy", "secret-scan"]
},
{
"path": ".release",
"kind": "untracked",
"role": "CI가 만드는 릴리스 후보 묶음",
"readBy": "release 단계 job(config/ci/gates.json)",
"optional": true,
"sets": ["provider-fixture-skip", "supply-chain-fixture-skip"]
},
{
"path": ".storybook",
"kind": "tool-convention",
@@ -81,12 +122,28 @@
"readBy": "storybook, build:storybook (FE-GATE-011)",
"sets": ["fixture-copy", "secret-scan", "scale-source", "typescript-only"]
},
{
"path": ".tmp",
"kind": "untracked",
"role": "drill 사본과 실행별 빌드·결과(.tmp/runs/<id>)",
"readBy": "scripts/lib/run-isolation.ts, 제거 drill",
"optional": true,
"sets": ["checkout-copy-skip", "provider-fixture-skip"]
},
{
"path": ".worktrees",
"kind": "untracked",
"role": "이 저장소의 다른 worktree를 두는 자리",
"readBy": "git worktree",
"optional": true,
"sets": ["provider-fixture-skip"]
},
{
"path": "AGENTS.md",
"kind": "tool-convention",
"role": "에이전트 진입 문서(꼭 지킬 것·지도·검증). docs/README.md 1절이 가리키는 현재 계약 문서",
"readBy": "코딩 에이전트, verify:documentation (FE-GATE-017)",
"sets": ["fixture-documents"]
"sets": ["fixture-documents", "agent-harness"]
},
{
"path": "CHANGELOG.md",
@@ -99,7 +156,8 @@
"path": "CLAUDE.md",
"kind": "tool-convention",
"role": "Claude Code 진입 문서",
"readBy": "Claude Code"
"readBy": "Claude Code",
"sets": ["agent-harness"]
},
{
"path": "PRODUCT.md",
@@ -112,29 +170,42 @@
"kind": "document",
"role": "시작·설정·검증",
"readBy": "verify:documentation (FE-GATE-017), 사람",
"sets": ["fixture-documents"]
"sets": ["fixture-documents", "documentation-inputs"]
},
{
"path": "artifacts",
"kind": "output",
"role": "게이트와 시험의 실행 출력",
"readBy": "scripts/run-ci-gate.ts, CI 업로드"
"readBy": "scripts/run-ci-gate.ts, CI 업로드",
"sets": ["checkout-copy-skip", "provider-fixture-skip", "supply-chain-fixture-skip"]
},
{
"path": "config",
"kind": "gate-input",
"role": "게이트·런타임·보안·성능의 기준 데이터와 JSON Schema(config/schemas)",
"readBy": "scripts/, tests/, src/",
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source"]
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source"],
"setPaths": {
"documentation-inputs": ["config/contracts/backend-contract-pin.json"]
}
},
{
"path": "dist",
"kind": "untracked",
"role": "vite build 출력",
"readBy": "vite build, preview 서버",
"optional": true,
"sets": ["checkout-copy-skip", "provider-fixture-skip", "supply-chain-fixture-skip"]
},
{
"path": "docs",
"kind": "document",
"role": "매뉴얼·설계·운영 문서와 수동 접근성 검토 기록",
"readBy": "verify:documentation (FE-GATE-017), review:a11y-manual (FE-GATE-009·028)",
"sets": ["fixture-documents"],
"sets": ["fixture-documents", "documentation-inputs"],
"setPaths": {
"fixture-copy": ["docs/accessibility/route-reviews"]
"fixture-copy": ["docs/accessibility/route-reviews"],
"agent-harness": ["docs/work"]
}
},
{
@@ -144,6 +215,14 @@
"readBy": "eslint (FE-GATE-002)",
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source"]
},
{
"path": "graphify-out",
"kind": "untracked",
"role": "graphify 지식 그래프 출력(로컬 분석)",
"readBy": "graphify",
"optional": true,
"sets": ["checkout-copy-skip", "provider-fixture-skip"]
},
{
"path": "index.html",
"kind": "tool-convention",
@@ -151,26 +230,34 @@
"readBy": "Vite",
"sets": ["fixture-copy", "secret-scan", "vite-build"]
},
{
"path": "node_modules",
"kind": "untracked",
"role": "설치된 의존성",
"readBy": "pnpm, Node",
"optional": true,
"sets": ["checkout-copy-skip", "provider-fixture-skip", "supply-chain-fixture-skip"]
},
{
"path": "package.json",
"kind": "tool-convention",
"role": "의존성과 package script",
"readBy": "pnpm, 모든 게이트",
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source", "vite-build"]
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source", "vite-build", "package-manifest"]
},
{
"path": "playwright.capabilities.config.ts",
"kind": "tool-convention",
"role": "브라우저 capability 시험 설정",
"readBy": "test:browser-capabilities (FE-GATE-008)",
"sets": ["fixture-copy", "secret-scan"]
"sets": ["fixture-copy", "secret-scan", "playwright-configs"]
},
{
"path": "playwright.config.ts",
"kind": "tool-convention",
"role": "e2e 설정(빌드 미리보기)",
"readBy": "test:e2e (FE-GATE-008)",
"sets": ["fixture-copy", "secret-scan", "history-free"]
"sets": ["fixture-copy", "secret-scan", "history-free", "playwright-configs"]
},
{
"path": "playwright.dev.config.ts",
@@ -184,28 +271,28 @@
"kind": "tool-convention",
"role": "Storybook 정적 빌드 시험 설정",
"readBy": "test:storybook (FE-GATE-008)",
"sets": ["fixture-copy", "secret-scan"]
"sets": ["fixture-copy", "secret-scan", "playwright-configs", "visual-evidence"]
},
{
"path": "playwright.visual.config.ts",
"kind": "tool-convention",
"role": "visual 골든 설정",
"readBy": "test:visual (FE-GATE-008)",
"sets": ["fixture-copy", "secret-scan"]
"sets": ["fixture-copy", "secret-scan", "playwright-configs", "visual-evidence"]
},
{
"path": "pnpm-lock.yaml",
"kind": "tool-convention",
"role": "잠금 파일",
"readBy": "pnpm, 공급망 생성",
"sets": ["fixture-copy", "secret-scan", "scale-source"]
"sets": ["fixture-copy", "secret-scan", "scale-source", "package-manifest"]
},
{
"path": "pnpm-workspace.yaml",
"kind": "tool-convention",
"role": "pnpm 11 설정",
"readBy": "pnpm, scripts/lib/package-script-graph.ts",
"sets": ["fixture-copy", "secret-scan"]
"sets": ["fixture-copy", "secret-scan", "package-manifest"]
},
{
"path": "public",
@@ -233,7 +320,7 @@
"kind": "source",
"role": "게이트·생성기·drill 스크립트",
"readBy": "package.json scripts",
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source", "typescript-only"],
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source", "typescript-only", "fixture-code"],
"setPaths": {
"vite-build": ["scripts/lib/run-isolation.ts", "scripts/lib/vite-module-inventory.ts"]
}
@@ -250,21 +337,24 @@
"kind": "source",
"role": "시험과 fixture",
"readBy": "test:* scripts, playwright 설정",
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source", "typescript-only"]
"sets": ["fixture-copy", "secret-scan", "history-free", "scale-source", "typescript-only", "fixture-code"],
"setPaths": {
"visual-evidence": ["tests/storybook/workshop.spec.ts"]
}
},
{
"path": "tsconfig.app.json",
"kind": "tool-convention",
"role": "src 타입 검사(DOM, Node 타입 없음)",
"readBy": "check:types:app (FE-GATE-003), Vite",
"sets": ["fixture-copy", "secret-scan", "scale-source", "vite-build"]
"sets": ["fixture-copy", "secret-scan", "scale-source", "vite-build", "feature-typecheck", "product-typecheck", "app-typecheck"]
},
{
"path": "tsconfig.base.json",
"kind": "tool-convention",
"role": "공통 컴파일 옵션",
"readBy": "다른 tsconfig의 extends",
"sets": ["fixture-copy", "secret-scan", "vite-build"]
"sets": ["fixture-copy", "secret-scan", "vite-build", "app-typecheck"]
},
{
"path": "tsconfig.json",
@@ -278,7 +368,7 @@
"kind": "tool-convention",
"role": "scripts·설정 파일 타입 검사(NodeNext)",
"readBy": "check:types:node (FE-GATE-003)",
"sets": ["fixture-copy", "secret-scan", "scale-source"]
"sets": ["fixture-copy", "secret-scan", "scale-source", "product-typecheck"]
},
{
"path": "tsconfig.service-worker.json",
@@ -292,7 +382,7 @@
"kind": "tool-convention",
"role": "tests·recipes·시험 설정 파일 타입 검사",
"readBy": "check:types:test (FE-GATE-003)",
"sets": ["fixture-copy", "secret-scan", "scale-source"]
"sets": ["fixture-copy", "secret-scan", "scale-source", "feature-typecheck", "product-typecheck"]
},
{
"path": "vite.config.ts",
+4 -3
View File
@@ -227,11 +227,11 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE)
| ID | 규칙 | 검사 |
| --- | --- | --- |
| R1 | 루트 항목은 모두 `config/repository-layout.json`에 있다. 항목마다 종류(source·tool-convention·gate-input·document·history·output), 역할, 읽는 곳을 적는다 | `tests/unit/repository-layout.test.ts`(FE-GATE-005). 등록부에 없는 루트 항목이 추적되면 실패 |
| R2 | 루트 경로 목록은 등록부의 이름 붙은 집합(`sets`, 하위 경로는 `setPaths`)에서만 고른다. 목록을 코드에 새로 적지 않는다. JSON 정책 파일(`config/security/secret-scan-policy.json`)은 그 집합의 사본을 갖고 시험이 같은지 본다 | 같은 시험. 목록을 쓰던 곳이 `scripts/lib/repository-layout.ts`를 import하는지, 루트 이름 두 개 이상의 문자열 배열이 없는지 |
| R1 | 루트 항목은 모두 `config/repository-layout.json`에 있다. 항목마다 종류(source·tool-convention·gate-input·document·history·output), 역할, 읽는 곳을 적는다. 추적하지 않는 항목(`node_modules`, `dist`, 다른 worktree)은 집합이 이름으로 고를 때만 종류 `untracked`, `optional`로 적는다 | `tests/unit/repository-layout.test.ts`(FE-GATE-005). 등록부에 없는 루트 항목이 추적되거나 `untracked` 항목에 추적 파일이 있으면 실패 |
| R2 | 루트 경로 목록은 등록부의 이름 붙은 집합(`sets`, 하위 경로는 `setPaths`)에서 `selectRepositoryPaths(<집합>)`으로만 고른다. 목록을 코드에 새로 적지 않는다. JSON 정책 파일(`config/security/secret-scan-policy.json`)은 그 집합의 사본을 갖고 시험이 같은지 본다 | 같은 시험. 추적되는 코드 파일 전체에서, 루트 항목이나 그 안 경로만 담은 문자열 배열에 추적되는 루트 이름이 둘 이상이면 실패. 인자 목록은 `--` 뒤의 경로만 본다. 시험이 메모리 안에 만드는 가상 저장소의 목록은 `tests/unit/repository-layout.test.ts`의 `MADE_UP_REPOSITORY_LISTS`에 파일·목록·이유로 적는다. 집합마다 그것을 고르는 코드가 있어야 한다 |
| R3 | 추적 파일은 읽는 곳이 있다. `artifacts/`는 출력 전용이라 `.gitkeep`만 추적한다. 사람이 쓴 기록은 `docs/` 아래에 둔다(수동 a11y 기록은 `docs/accessibility/route-reviews/`) | `tests/unit/tracked-artifacts.test.ts`(FE-GATE-005). `config/` 아래 고아 JSON은 리뷰가 본다 |
| R4 | 템플릿이나 제품이 넣은 샘플 기능은 `scripts/lib/removable-template-features.ts` 목록에 있고, 복사본에서 지우고 빌드·시험하는 drill로 증명한다. 문서 검사만으로는 안 된다 | `tests/unit/example-feature-rules.test.ts`(FE-GATE-005). FE-GATE-020이 `test:sample-removal`을 목록 전체로 도는지 |
| R5 | 게이트의 검사 대상(visual 골든, e2e 라우트, 게이트 증거 목록, 규모 측정)은 플랫폼 화면·시험 fixture·생성기 출력이다. 지울 샘플 기능이 아니다 | 같은 시험. 샘플의 기능 ID·라우트가 visual·e2e의 `goto`, `config/ci/gates.json` 산출물 경로, `config/scale/`에 나오면 실패 |
| R5 | 게이트의 검사 대상(visual 골든, e2e 라우트, 게이트 증거 목록, 규모 측정)은 플랫폼 화면·시험 fixture·생성기 출력이다. 지울 샘플 기능이 아니다 | 같은 시험. 대상마다 소유자를 따라간다: visual·e2e의 `goto` 경로는 라우트 표로 라우트와 그 기능을, workshop story id는 그 story를 정의한 파일을, spec의 import는 불러오는 파일을(생성기 출력 `src/.generated/`에서 멈춘다), `config/ci/gates.json`의 라우트 기록은 그 라우트를, 게이트 명령은 package script 그래프로 script와 경로 인자를, `config/scale/feature-shape-growth.json`의 `sourceFeature`는 그 기능을. 소유자가 목록의 샘플이거나 라우트 기록의 라우트가 라우트 표에 없으면 실패 |
| R6 | 매뉴얼의 예제 위치는 `create:feature` 출력이나 매뉴얼 안 코드 조각을 가리킨다. 지울 샘플 기능의 경로를 가리키지 않는다 | `verify:documentation`(FE-GATE-017). `docs/manual/`에 목록 샘플의 경로가 나오면 실패 |
| R7 | 이 repo에 둘 수 있는 실행 환경 파일은 개발 의존 서비스용 compose와 개발 Dockerfile뿐이다. nginx·Kubernetes·Helm·Terraform 설정은 인프라 repo에 두고 링크한다. 호스트에 요구하는 것은 계약(`config/hosting/`)과 검사(FE-GATE-019)로 둔다 | 파일: `tests/unit/repository-layout.test.ts`(FE-GATE-005). 문서: `verify:documentation`(FE-GATE-017)이 현재 문서의 ```` ```nginx ````·```` ```hcl ```` 블록과 `kind: Deployment` 같은 매니페스트 줄을 막는다. 이력 폴더(`docs/history/`, `docs/reviews/`, `docs/superpowers/`)는 기록이라 보지 않는다 |
| R8 | 검사 대상이 0개인 게이트 명령은 실패하거나 SKIP을 출력한다. 통과로 보이면 안 된다 | FE-GATE-003: `scripts/check-typecheck-inputs.ts`(package script가 tsc에 넘기는 tsconfig마다 이 repo 파일이 1개 이상), `scripts/check-type-fixtures.ts`(fixture 0개면 실패) |
@@ -242,6 +242,7 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE)
1. `config/repository-layout.json`에 항목을 더하거나 고친다. 종류·역할·읽는 곳을 적는다(R1).
2. 그 항목이 들어갈 집합을 `sets`(항목 전체)나 `setPaths`(항목 안 경로)에 적는다. 집합의 뜻은 파일 머리의 `sets` 설명에 있다(R2).
- 새 목록이 필요하면 집합을 새로 만든다. `scripts/lib/repository-layout.ts`의 `REPOSITORY_LAYOUT_SETS`와 파일의 `sets` 설명(읽는 파일 포함)에 함께 더하고, 쓰는 곳은 `selectRepositoryPaths(<집합>)`으로 고른다.
3. `secret-scan` 집합을 바꿨으면 `config/security/secret-scan-policy.json`의 `trackedRoots`도 같게 고친다.
4. 새 tsconfig라면 R9를 먼저 본다. 다른 tsconfig와 옵션이 같으면 만들지 않는다.
+3 -2
View File
@@ -4,6 +4,7 @@ import path from "node:path";
import { spawnSync } from "node:child_process";
import { CACHEABLE_ASSET_CONTENT_TYPES } from "../src/contracts/service-worker-static-manifest.ts";
import { selectRepositoryPaths } from "./lib/repository-layout.ts";
/**
* GOV-01 / SW-RR-03. Structural gates for facts that a hand-maintained document
@@ -99,7 +100,7 @@ async function main(): Promise<void> {
// dependencies mid-run. `linkFixtureNodeModules` is the only sanctioned form.
const sources = spawnSync(
"git",
["grep", "-n", "-e", 'symlink(', "--", "scripts", "tests"],
["grep", "-n", "-e", 'symlink(', "--", ...selectRepositoryPaths("fixture-code")],
{ encoding: "utf8" },
);
if (sources.status === 0) {
@@ -113,7 +114,7 @@ async function main(): Promise<void> {
}
const linkedFixtures = spawnSync(
"git",
["grep", "-l", "linkFixtureNodeModules", "--", "scripts", "tests"],
["grep", "-l", "linkFixtureNodeModules", "--", ...selectRepositoryPaths("fixture-code")],
{ encoding: "utf8" },
);
if (
@@ -45,8 +45,10 @@ import {
FIXTURE_PNPM_ENVIRONMENT,
linkFixtureNodeModules,
} from "./lib/fixture-node-modules.ts";
import { selectRepositoryPaths } from "./lib/repository-layout.ts";
const repositoryRoot = process.cwd();
const UNCOPIED_ROOTS = selectRepositoryPaths("supply-chain-fixture-skip");
const fixtureRoot = await mkdtemp(path.join(tmpdir(), "provider-exact-five-fixture-"));
try {
await cp(repositoryRoot, fixtureRoot, {
@@ -55,7 +57,7 @@ try {
const relative = path.relative(repositoryRoot, source);
if (!relative) return true;
const first = relative.split(path.sep)[0];
return ![".release", "artifacts", "dist", "node_modules"].includes(first ?? "");
return !UNCOPIED_ROOTS.includes(first ?? "");
},
});
await cp(path.join(repositoryRoot, "artifacts"), path.join(fixtureRoot, "artifacts"), {
+3 -11
View File
@@ -12,6 +12,7 @@ import {
type HttpScenarioExpectation,
type HttpScenarioReceipt,
} from "./lib/http-scenario-evidence.ts";
import { selectRepositoryPaths } from "./lib/repository-layout.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
import { testEvidenceReportSchema } from "./lib/test-evidence-artifact.ts";
@@ -381,12 +382,7 @@ if (!fixtureMode && !scenarioOnly) {
}
}
// playwright.dev.config.ts spreads playwright.config.ts.
for (const config of [
"playwright.config.ts",
"playwright.visual.config.ts",
"playwright.storybook.config.ts",
"playwright.capabilities.config.ts",
]) {
for (const config of selectRepositoryPaths("playwright-configs")) {
if (!(await readFile(config, "utf8")).includes("forbidOnly: true")) {
failures.push(`${config}: missing forbidOnly: true, so a committed test.only passes the gate`);
}
@@ -409,11 +405,7 @@ if (!fixtureMode && !scenarioOnly) {
if (facts.visualBaselines < 4) {
failures.push("visual baseline requires at least four risk surfaces");
}
for (const required of [
"playwright.storybook.config.ts",
"playwright.visual.config.ts",
"tests/storybook/workshop.spec.ts",
]) {
for (const required of selectRepositoryPaths("visual-evidence")) {
if ((await filesBelow(required)).length === 0) {
failures.push(`test evidence missing ${required}`);
}
+32 -1
View File
@@ -6,7 +6,10 @@ import { readFileSync } from "node:fs";
* entry, and every list of root paths is a named set chosen from it (R2).
* Seven places used to keep their own literal lists of root paths, each a
* different subset, so moving one root item meant editing all seven
* (design-docs repo-structure/04-frontend-layout.md §2.4).
* (design-docs repo-structure/04-frontend-layout.md §2.4); about twenty more
* lists followed on 2026-11-11. An untracked item (node_modules, dist, other
* worktrees) has an entry only when a set names it, such as the items a copy
* of the checkout skips.
*/
export const REPOSITORY_LAYOUT_SETS = Object.freeze([
@@ -17,6 +20,18 @@ export const REPOSITORY_LAYOUT_SETS = Object.freeze([
"scale-source",
"vite-build",
"typescript-only",
"checkout-copy-skip",
"provider-fixture-skip",
"supply-chain-fixture-skip",
"fixture-code",
"package-manifest",
"playwright-configs",
"visual-evidence",
"documentation-inputs",
"agent-harness",
"feature-typecheck",
"product-typecheck",
"app-typecheck",
] as const);
export type RepositoryLayoutSet = (typeof REPOSITORY_LAYOUT_SETS)[number];
@@ -27,6 +42,7 @@ export const REPOSITORY_LAYOUT_KINDS = Object.freeze([
"document",
"history",
"output",
"untracked",
] as const);
export type RepositoryLayoutKind = (typeof REPOSITORY_LAYOUT_KINDS)[number];
@@ -49,6 +65,18 @@ export const REPOSITORY_LAYOUT_FILE = "config/repository-layout.json";
export function parseRepositoryLayout(value: unknown): readonly RepositoryLayoutEntry[] {
const document = record(value, "layout");
if (document["schemaVersion"] !== 1) throw new Error("layout: schemaVersion must be 1");
// Each kind and set the code knows is described once in the file, and the file names no other.
for (const [field, known] of [
["kinds", REPOSITORY_LAYOUT_KINDS],
["sets", REPOSITORY_LAYOUT_SETS],
] as const) {
if (!(field in document)) continue;
const described = Object.keys(record(document[field], `layout.${field}`)).sort();
const expected = [...known].sort();
if (described.join() !== expected.join()) {
throw new Error(`layout.${field} must describe exactly ${expected.join(", ")}; it has ${described.join(", ")}`);
}
}
const entries = document["entries"];
if (!Array.isArray(entries) || entries.length === 0) {
throw new Error("layout: entries must be a non-empty array");
@@ -66,6 +94,9 @@ export function parseRepositoryLayout(value: unknown): readonly RepositoryLayout
if (!(REPOSITORY_LAYOUT_KINDS as readonly string[]).includes(kind)) {
throw new Error(`${at}.kind: unknown kind ${kind}`);
}
if (kind === "untracked" && entry["optional"] !== true) {
throw new Error(`${at}: an untracked item may be absent, so it is optional`);
}
const sets = (entry["sets"] ?? []) as unknown;
if (!Array.isArray(sets)) throw new Error(`${at}.sets must be an array`);
const setPaths = record(entry["setPaths"] ?? {}, `${at}.setPaths`);
+2 -10
View File
@@ -5,6 +5,7 @@ import path from "node:path";
import { localBuildEnvironment } from "../../../scripts/lib/build-environment.ts";
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
import { selectRepositoryPaths } from "../../../scripts/lib/repository-layout.ts";
/**
* Real production builds of an edited temp copy of the repository, in the
@@ -16,16 +17,7 @@ import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-module
*/
const repoRoot = path.resolve(import.meta.dirname, "../../..");
const skipped = new Set([
"node_modules",
".git",
".claude",
".generated",
".tmp",
"dist",
"artifacts",
"graphify-out",
]);
const skipped = new Set(selectRepositoryPaths("checkout-copy-skip"));
export type FixtureBuild<Name extends string> = Readonly<{
name: Name;
+2 -10
View File
@@ -18,6 +18,7 @@ import { gzipSync } from "node:zlib";
import { SERVICE_WORKER_ASSETS_OUTPUT } from "../../../scripts/generate-service-worker-assets.ts";
import { localBuildEnvironment } from "../../../scripts/lib/build-environment.ts";
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
import { selectRepositoryPaths } from "../../../scripts/lib/repository-layout.ts";
import type { StaticAssetManifestV1 } from "../../../src/contracts/service-worker.ts";
/**
@@ -57,16 +58,7 @@ import type { StaticAssetManifestV1 } from "../../../src/contracts/service-worke
const repoRoot = path.resolve(import.meta.dirname, "../../..");
// 1105/12-04. `.tmp` holds other runs' builds and results (.tmp/runs/<id>),
// which change while this copy is made; fixture-builds.ts skips it too.
const skipped = new Set([
"node_modules",
".git",
".claude",
".generated",
".tmp",
"dist",
"artifacts",
"graphify-out",
]);
const skipped = new Set(selectRepositoryPaths("checkout-copy-skip"));
export type BuildName = "a" | "b";
export type ServiceWorkerBuilds = Readonly<{
@@ -19,6 +19,7 @@ import {
FIXTURE_PNPM_ENVIRONMENT,
linkFixtureNodeModules,
} from "../../scripts/lib/fixture-node-modules.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
it(
"builds a real candidate assessment and passes the default archived verifier from the captured archive",
@@ -32,12 +33,7 @@ it(
const relative = path.relative(sourceRoot, source);
if (!relative) return true;
const first = relative.split(path.sep)[0];
return ![
".release",
"artifacts",
"dist",
"node_modules",
].includes(first ?? "");
return !selectRepositoryPaths("supply-chain-fixture-skip").includes(first ?? "");
},
});
await cp(path.join(sourceRoot, "artifacts"), path.join(fixtureRoot, "artifacts"), {
@@ -24,6 +24,7 @@ import {
linkFixtureNodeModules,
} from "../../../scripts/lib/fixture-node-modules.ts";
import { copyReleaseEvidenceTree } from "../../../scripts/lib/removal-fixture.ts";
import { selectRepositoryPaths } from "../../../scripts/lib/repository-layout.ts";
import { captureCiCandidateArchive, verifyCiCandidateArchive } from "../../../scripts/lib/ci-candidate-archive.ts";
import {
CANDIDATE_ARCHIVE_USAGE,
@@ -2230,18 +2231,12 @@ async function createProviderFixture() {
* removal-drill fixtures, each with its own node_modules; copying them filled
* every /tmp/ci-provider-upload-* root with those trees, and the suite failed
* with timeouts and ENOTEMPTY clean-ups (1103/11-04). None of them is tracked,
* so the candidate's tracked-file inventory does not miss them.
* so the candidate's tracked-file inventory does not miss them. The rest of
* `.claude/` is tracked and copied: the fixture keeps `.git`, and supply-chain
* generation lstat()s every tracked file, so skipping all of `.claude` failed
* every finalizer test with ENOENT once `.claude/` had tracked files.
*/
const PROVIDER_BASE_FIXTURE_UNCOPIED_ENTRIES: readonly string[] = Object.freeze([
".release",
"artifacts",
"dist",
"node_modules",
".claude",
".worktrees",
".tmp",
"graphify-out",
]);
const PROVIDER_BASE_FIXTURE_UNCOPIED_ENTRIES: readonly string[] = selectRepositoryPaths("provider-fixture-skip");
async function ensureProviderBaseFixture(): Promise<string> {
if (providerBaseRoot) return providerBaseRoot;
@@ -2252,8 +2247,10 @@ async function ensureProviderBaseFixture(): Promise<string> {
filter: (source) => {
const relative = path.relative(sourceRoot, source);
if (!relative) return true;
const first = relative.split(path.sep)[0];
return !PROVIDER_BASE_FIXTURE_UNCOPIED_ENTRIES.includes(first ?? "");
const entry = relative.split(path.sep).join("/");
return !PROVIDER_BASE_FIXTURE_UNCOPIED_ENTRIES.some(
(skipped) => entry === skipped || entry.startsWith(`${skipped}/`),
);
},
});
// The release evidence, minus the trace and Storybook trees. Copying the
+3 -1
View File
@@ -6,8 +6,10 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
// The pin says which commit of the paired backend the documents describe.
const INPUTS = ["README.md", "docs", "config/contracts/backend-contract-pin.json"];
const INPUTS = selectRepositoryPaths("documentation-inputs");
const PAIRED_BACKEND = "clean-architecture-backend-template";
type Changes = Readonly<Record<string, (text: string) => string>>;
+269 -62
View File
@@ -1,14 +1,18 @@
import { readdir, readFile } from "node:fs/promises";
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
import { reachablePackageScripts } from "../../scripts/lib/package-script-graph.ts";
import {
REMOVABLE_TEMPLATE_FEATURES,
removableTemplateFeaturePaths,
type RemovableTemplateFeature,
} from "../../scripts/lib/removable-template-features.ts";
import { INSTALLED_FEATURE_CONTRACTS } from "../../src/features/installed-feature-contracts.ts";
import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts";
import { ROUTE_FEATURE_OWNER, ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
/**
* R4 and R5 of docs/manual/03-outside-feature-folder.md. A sample feature
@@ -19,63 +23,208 @@ import { INSTALLED_FEATURE_CONTRACTS } from "../../src/features/installed-featur
* are platform screens, test fixtures and generator output, never a sample a
* copy is meant to delete (R5): the template's reference sample was the
* target of nine gates when it was deleted on 2026-11-07.
*
* R5 follows each target to what owns it, so a sample is found by what it
* owns, not by its name appearing in a string: a route path resolves through
* the route table to a route and its feature, a story id to the stories file
* that defines it, a spec's imports to the files they load, a route review in
* the evidence list to its route, and a gate's commands through the package
* script graph to the scripts and paths they run.
*/
type ExampleFeature = Readonly<{ featureId: string; routeIds: readonly string[]; routePaths: readonly string[] }>;
const PLATFORM = "platform";
type Sample = Readonly<{ featureId: string; paths: readonly string[]; scripts: readonly string[] }>;
type RouteRow = Readonly<{ routeId: string; path: string; owner: string }>;
/** What the gates point at, each with where it was found. */
type GateTargets = Readonly<{
gotoTargets: readonly Readonly<{ file: string; target: string }>[];
artifactPaths: readonly string[];
scaleFiles: readonly Readonly<{ file: string; text: string }>[];
routeTargets: readonly Readonly<{ where: string; target: string }>[];
reachedFiles: readonly Readonly<{ where: string; file: string }>[];
artifacts: readonly string[];
gateScripts: readonly Readonly<{ gateId: string; script: string; command: string }>[];
scaleSourceFeature: string;
}>;
function exampleFeatures(features: readonly RemovableTemplateFeature[]): ExampleFeature[] {
return features.map(({ featureId }) => {
// The template installs no feature, so the composed list's type is empty.
const contracts = INSTALLED_FEATURE_CONTRACTS as readonly Readonly<{ featureId: string; routes: object }>[];
const routes = contracts.filter((contract) => contract.featureId === featureId).flatMap(
(contract) => Object.values(contract.routes as Record<string, { routeId: string; path: string }>),
function samplesOf(features: readonly RemovableTemplateFeature[]): Sample[] {
return features.map((feature) => ({
featureId: feature.featureId,
paths: removableTemplateFeaturePaths(feature),
scripts: feature.scripts,
}));
}
function owningSample(samples: readonly Sample[], file: string): Sample | undefined {
return samples.find(({ paths }) => paths.some((owned) => file === owned || file.startsWith(`${owned}/`)));
}
/** The route table the app boots with: each route and the feature that declares it. */
function repositoryRoutes(): RouteRow[] {
const routes = Object.values(ROUTE_REGISTRY) as readonly Readonly<{ routeId: string; path: string }>[];
return routes.map(({ routeId, path: routePath }) => ({
routeId,
path: routePath,
owner: ROUTE_FEATURE_OWNER[routeId] ?? (routeId in PLATFORM_ROUTE_REGISTRY ? PLATFORM : "unknown"),
}));
}
/** The route the router renders for `target`: a declared path, else the catch-all. */
function resolveRoute(target: string, routes: readonly RouteRow[]): RouteRow | undefined {
const pathname = target.split(/[?#]/u)[0] ?? "";
const segments = pathname.split("/").filter(Boolean);
const declared = routes.find((route) => {
if (route.path === "*") return false;
const pattern = route.path.split("/").filter(Boolean);
return (
pattern.length === segments.length &&
pattern.every((part, index) => (part.startsWith(":") ? segments[index] !== "" : part === segments[index]))
);
return {
featureId,
routeIds: routes.map(({ routeId }) => routeId),
routePaths: routes.map(({ path: routePath }) => routePath).filter((routePath) => routePath !== "/"),
};
});
return declared ?? routes.find((route) => route.path === "*");
}
/**
* The app paths a spec opens literally. A target computed at run time is left
* out: the a11y spec walks the whole route table, which names every installed
* feature and none in particular, and a generated feature's path is generator
* output. A sample module such a spec imports is still found by the import walk.
*/
function literalGotoTargets(source: string): string[] {
return [...source.matchAll(/\.goto\(\s*(["'`])((?:\\.|(?!\1)[^\\])*)\1/gu)].flatMap(([, , raw = ""]) => {
// `${server.origin}/` is the served build's origin, then the app path.
const target = raw.replace(/^\$\{[^}]*\}/u, "");
if (target.includes("${")) return [];
if (target === "") return ["/"];
return target.startsWith("/") ? [target] : [];
});
}
function gateTargetsNamingExamples(examples: readonly ExampleFeature[], targets: GateTargets): string[] {
return examples.flatMap(({ featureId, routeIds, routePaths }) => [
...targets.gotoTargets
.filter(({ target }) => target.includes(featureId) || routePaths.some((routePath) => target === routePath || target.startsWith(`${routePath}/`) || target.startsWith(`${routePath}?`)))
.map(({ file, target }) => `${file}: goto ${target}`),
...targets.artifactPaths
.filter((artifact) => artifact.includes(featureId) || routeIds.some((routeId) => artifact.includes(`/${routeId}.`)))
.map((artifact) => `config/ci/gates.json: ${artifact}`),
...targets.scaleFiles.filter(({ text }) => text.includes(featureId)).map(({ file }) => `${file}: ${featureId}`),
]);
const IMPORT_SPECIFIER =
/(?:\bimport\s+(?:type\s+)?(?:[^'"`;]*?\sfrom\s*)?|\bexport\s+(?:type\s+)?[^'"`;]*?\sfrom\s*|\bimport\(\s*)["']([^"']+)["']/gu;
/** Repository files `file` imports, resolved; package imports are not followed. */
function importedFiles(file: string, source: string, exists: (file: string) => boolean): string[] {
return [...source.matchAll(IMPORT_SPECIFIER)].flatMap(([, specifier = ""]) => {
if (!specifier.startsWith(".")) return [];
const base = path.posix.normalize(path.posix.join(path.posix.dirname(file), specifier));
const resolved = [base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`].find(exists);
return resolved === undefined ? [] : [resolved];
});
}
async function specFiles(directory: string): Promise<string[]> {
return ((await readdir(directory, { recursive: true })) as string[])
.filter((name) => /\.ts$/u.test(name))
.map((name) => path.join(directory, name));
/**
* Every file the entries load. The walk stops at `src/.generated/`: the
* feature index there is generator output that imports each installed
* feature, and removing a sample writes it again without that sample.
*/
function reachableFiles(
entries: readonly string[],
read: (file: string) => string,
exists: (file: string) => boolean,
): Readonly<{ where: string; file: string }>[] {
const reached = new Map<string, string>();
const queue = entries.map((entry) => ({ where: entry, file: entry }));
for (let next = queue.shift(); next !== undefined; next = queue.shift()) {
if (reached.has(next.file) || next.file.startsWith("src/.generated/")) continue;
reached.set(next.file, next.where);
for (const imported of importedFiles(next.file, read(next.file), exists)) {
queue.push({ where: next.where, file: imported });
}
}
return [...reached].map(([file, where]) => ({ where, file }));
}
/** Storybook's id prefix for a stories file's title: "Platform/Galleries" is "platform-galleries". */
function storyIdPrefix(title: string): string {
return title.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "");
}
/** Gate targets that a sample owns, or that point at nothing. Empty when R5 holds. */
function sampleGateTargets(samples: readonly Sample[], routes: readonly RouteRow[], targets: GateTargets): string[] {
const sampleIds = new Set(samples.map(({ featureId }) => featureId));
const findings: string[] = [];
for (const { where, target } of targets.routeTargets) {
const route = resolveRoute(target, routes);
if (route === undefined) findings.push(`${where}: goto ${target} matches no route`);
else if (sampleIds.has(route.owner)) findings.push(`${where}: goto ${target} is ${route.routeId} of sample ${route.owner}`);
}
for (const { where, file } of targets.reachedFiles) {
const sample = owningSample(samples, file);
if (sample) findings.push(`${where} loads ${file} of sample ${sample.featureId}`);
}
for (const artifact of targets.artifacts) {
const review = /^docs\/accessibility\/route-reviews\/([^/]+)\.md$/u.exec(artifact)?.[1];
const route = review === undefined ? undefined : routes.find(({ routeId }) => routeId === review);
if (review !== undefined && route === undefined) {
findings.push(`config/ci/gates.json: ${artifact} reviews no route in the route table`);
} else if (route !== undefined && sampleIds.has(route.owner)) {
findings.push(`config/ci/gates.json: ${artifact} reviews ${route.routeId} of sample ${route.owner}`);
}
const sample = owningSample(samples, artifact);
if (sample) findings.push(`config/ci/gates.json: ${artifact} is in sample ${sample.featureId}`);
}
for (const { gateId, script, command } of targets.gateScripts) {
for (const sample of samples) {
if (sample.scripts.includes(script)) findings.push(`${gateId} runs ${script}, a script of sample ${sample.featureId}`);
}
const words = command.split(/\s+/u).map((word) => word.replace(/^["']|["']$/gu, ""));
for (const [index, word] of words.entries()) {
const feature = /^--feature=(.+)$/u.exec(word)?.[1] ?? (word === "--feature" ? words[index + 1] : undefined);
if (feature !== undefined && sampleIds.has(feature)) findings.push(`${gateId} runs ${script} on sample ${feature}`);
const sample = owningSample(samples, word.replace(/^\.\//u, ""));
if (sample) findings.push(`${gateId} runs ${script} on ${word} of sample ${sample.featureId}`);
}
}
if (sampleIds.has(targets.scaleSourceFeature)) {
findings.push(`config/scale/feature-shape-growth.json: sourceFeature is sample ${targets.scaleSourceFeature}`);
}
return findings;
}
function trackedFiles(): string[] {
const listed = spawnSync("git", ["ls-files", "-z"], { encoding: "utf8" });
if (listed.error || listed.status !== 0) throw new Error(`git ls-files failed: ${listed.error?.message ?? listed.stderr}`);
return listed.stdout.split("\0").filter((file) => file !== "" && existsSync(file));
}
async function repositoryGateTargets(): Promise<GateTargets> {
const gotoTargets: { file: string; target: string }[] = [];
for (const file of [...(await specFiles("tests/visual")), ...(await specFiles("tests/e2e"))]) {
const source = await readFile(file, "utf8");
for (const [, target = ""] of source.matchAll(/\.goto\(\s*["'`]([^"'`]+)["'`]/gu)) gotoTargets.push({ file, target });
}
const tracked = trackedFiles();
const specs = tracked.filter((file) => /^tests\/(?:visual|e2e)\/.+\.tsx?$/u.test(file));
const read = (file: string) => readFileSync(file, "utf8");
const routeTargets = specs.flatMap((file) => literalGotoTargets(read(file)).map((target) => ({ where: file, target })));
// A workshop story a visual spec opens is drawn by the stories file whose title gives its id.
const stories = tracked
.filter((file) => file.endsWith(".stories.tsx"))
.flatMap((file) => {
const title = /^\s*title:\s*["']([^"']+)["']/mu.exec(read(file))?.[1];
return title === undefined ? [] : [{ file, prefix: storyIdPrefix(title) }];
});
const storyFiles = specs
.filter((file) => file.startsWith("tests/visual/"))
.flatMap((file) =>
[...read(file).matchAll(/["'`]([a-z0-9-]+)--[a-z0-9-]+["'`]/gu)].map(([story = "", prefix = ""]) => {
const owner = stories.find((candidate) => candidate.prefix === prefix);
return { where: `${file} (story ${story.slice(1, -1)})`, file: owner?.file ?? `<no stories file for ${prefix}>` };
}),
);
const contract = await loadCiGateContract(process.cwd());
const scaleFiles = await Promise.all(
(await readdir("config/scale")).map(async (name) => ({
file: `config/scale/${name}`,
text: await readFile(`config/scale/${name}`, "utf8"),
})),
const packageScripts = (JSON.parse(read("package.json")) as { scripts: Record<string, string> }).scripts;
const gateScripts = contract.gates.flatMap(({ id, commandIds }) =>
reachablePackageScripts(
packageScripts,
contract.commands.filter((command) => commandIds.includes(command.id)).map(({ script }) => script),
).map((script) => ({ gateId: id, script, command: packageScripts[script] ?? "" })),
);
return { gotoTargets, artifactPaths: contract.artifacts.map(({ path: artifact }) => artifact), scaleFiles };
const scale = JSON.parse(read("config/scale/feature-shape-growth.json")) as { sourceFeature: string };
return {
routeTargets,
reachedFiles: [...reachableFiles(specs, read, existsSync), ...storyFiles],
artifacts: contract.artifacts.map(({ path: artifact }) => artifact),
gateScripts,
scaleSourceFeature: scale.sourceFeature,
};
}
describe("sample features (R4)", () => {
@@ -89,38 +238,96 @@ describe("sample features (R4)", () => {
);
expect(scripts).toContain("test:sample-removal");
// Without `--feature` the drill deletes every listed sample.
const packageScripts = (JSON.parse(await readFile("package.json", "utf8")) as { scripts: Record<string, string> })
const packageScripts = (JSON.parse(readFileSync("package.json", "utf8")) as { scripts: Record<string, string> })
.scripts;
expect(packageScripts["test:sample-removal"]).not.toMatch(/--feature/u);
// It builds and tests the copy; a documents-only check does not prove removal.
const drill = await readFile("scripts/test-sample-removal.ts", "utf8");
const drill = readFileSync("scripts/test-sample-removal.ts", "utf8");
expect(drill).toMatch(/check\(`\$\{prefix\}build`, "build"\)/u);
expect(drill).toMatch(/check\(`\$\{prefix\}unit-integration`, "test:all"\)/u);
});
});
describe("gate targets (R5)", () => {
it("name no sample feature", async () => {
expect(gateTargetsNamingExamples(exampleFeatures(REMOVABLE_TEMPLATE_FEATURES), await repositoryGateTargets())).toEqual(
[],
it("are owned by no sample feature and each points at something", async () => {
const targets = await repositoryGateTargets();
// The walk reaches the real targets: an empty one would pass anything.
expect(targets.routeTargets.length).toBeGreaterThan(10);
expect(targets.reachedFiles.some(({ file }) => file.startsWith("src/"))).toBe(true);
expect(targets.artifacts.some((artifact) => artifact.startsWith("docs/accessibility/route-reviews/"))).toBe(true);
expect(targets.gateScripts.length).toBeGreaterThan(20);
expect(sampleGateTargets(samplesOf(REMOVABLE_TEMPLATE_FEATURES), repositoryRoutes(), targets)).toEqual([]);
});
it("finds this repository's targets once a sample owns what they point at", async () => {
// As if the platform overview screen, the design system and the message catalog were a sample's.
const sample: Sample = {
featureId: "overview-sample",
paths: ["src/presentation/design-system", "src/presentation/i18n"],
scripts: ["test:visual"],
};
const routes = repositoryRoutes().map((route) =>
route.routeId === "EXAMPLES_PLATFORM" ? { ...route, owner: sample.featureId } : route,
);
const findings = sampleGateTargets([sample], routes, await repositoryGateTargets());
expect(findings).toEqual(
expect.arrayContaining([
"tests/e2e/platform-overview.spec.ts: goto /examples/platform is EXAMPLES_PLATFORM of sample overview-sample",
"tests/visual/platform.visual.spec.ts (story platform-galleries--design-system) loads src/presentation/design-system/galleries.stories.tsx of sample overview-sample",
"tests/e2e/accessibility.spec.ts loads src/presentation/i18n/catalog.ts of sample overview-sample",
"FE-GATE-008 runs test:visual, a script of sample overview-sample",
]),
);
});
it("finds a sample's route in a visual spec, the evidence list and a scale record", () => {
const sample = { featureId: "order-feature", routeIds: ["ORDER_LIST"], routePaths: ["/orders"] };
expect(
gateTargetsNamingExamples([sample], {
gotoTargets: [
{ file: "tests/visual/a.visual.spec.ts", target: "/orders?page=2" },
{ file: "tests/visual/a.visual.spec.ts", target: "/examples/platform" },
],
artifactPaths: ["docs/accessibility/route-reviews/ORDER_LIST.md", "artifacts/quality/bundle.json"],
scaleFiles: [{ file: "config/scale/feature-shape-growth.json", text: '{"sourceFeature":"order-feature"}' }],
}),
).toEqual([
"tests/visual/a.visual.spec.ts: goto /orders?page=2",
"config/ci/gates.json: docs/accessibility/route-reviews/ORDER_LIST.md",
"config/scale/feature-shape-growth.json: order-feature",
it("follows routes, imports, route reviews, scripts and the scale record of a synthetic sample", () => {
const sample: Sample = {
featureId: "order-feature",
paths: ["src/features/order-feature", "tests/features/order-feature"],
scripts: ["test:orders"],
};
const routes: RouteRow[] = [
{ routeId: "APP_HOME", path: "/", owner: PLATFORM },
{ routeId: "ORDER_DETAIL", path: "/orders/:orderId", owner: "order-feature" },
{ routeId: "NOT_FOUND", path: "*", owner: PLATFORM },
];
const sources: Record<string, string> = {
"tests/e2e/orders.spec.ts": [
`import { ORDER } from "../../src/features/order-feature/order-contract.ts";`,
`import { INDEX } from "../../src/.generated/product-feature-index.ts";`,
`await page.goto(\`\${server.origin}/orders/7?tab=items\`);`,
`await page.goto("/");`,
`await page.goto("/no-such-page");`,
`await page.goto(route);`,
].join("\n"),
"src/features/order-feature/order-contract.ts": `export const ORDER = 1;`,
};
const exists = (file: string) => file in sources || file === "src/.generated/product-feature-index.ts";
const targets: GateTargets = {
routeTargets: literalGotoTargets(sources["tests/e2e/orders.spec.ts"]!).map((target) => ({
where: "tests/e2e/orders.spec.ts",
target,
})),
reachedFiles: reachableFiles(["tests/e2e/orders.spec.ts"], (file) => sources[file] ?? "", exists),
artifacts: ["docs/accessibility/route-reviews/ORDER_DETAIL.md", "docs/accessibility/route-reviews/GONE.md"],
gateScripts: [
{ gateId: "FE-GATE-008", script: "test:orders", command: "playwright test" },
{ gateId: "FE-GATE-005", script: "test:unit", command: "vitest run tests/features/order-feature" },
{ gateId: "FE-GATE-020", script: "test:sample-removal", command: "node drill.ts --feature=order-feature" },
],
scaleSourceFeature: "order-feature",
};
expect(sampleGateTargets([sample], routes, targets)).toEqual([
"tests/e2e/orders.spec.ts: goto /orders/7?tab=items is ORDER_DETAIL of sample order-feature",
"tests/e2e/orders.spec.ts loads src/features/order-feature/order-contract.ts of sample order-feature",
"config/ci/gates.json: docs/accessibility/route-reviews/ORDER_DETAIL.md reviews ORDER_DETAIL of sample order-feature",
"config/ci/gates.json: docs/accessibility/route-reviews/GONE.md reviews no route in the route table",
"FE-GATE-008 runs test:orders, a script of sample order-feature",
"FE-GATE-005 runs test:unit on tests/features/order-feature of sample order-feature",
"FE-GATE-020 runs test:sample-removal on sample order-feature",
"config/scale/feature-shape-growth.json: sourceFeature is sample order-feature",
]);
// `/no-such-page` is the catch-all's, a platform screen; the generated index ends the walk.
expect(targets.reachedFiles.map(({ file }) => file)).not.toContain("src/.generated/product-feature-index.ts");
});
});
+3 -2
View File
@@ -19,6 +19,7 @@ import {
FIXTURE_PNPM_ENVIRONMENT,
linkFixtureNodeModules,
} from "../../scripts/lib/fixture-node-modules.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
/**
* A removal or provider fixture runs `pnpm` inside a throwaway copy of the
@@ -239,7 +240,7 @@ describe("pnpm inside a linked fixture (F-4)", () => {
) {
const fixture = path.join(root, `fixture-${scratch.length}-${Date.now()}`);
await mkdir(fixture);
for (const file of ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"]) {
for (const file of selectRepositoryPaths("package-manifest")) {
await copyFile(path.join(source, file), path.join(fixture, file));
}
await linkFixtureNodeModules(fixture, source);
@@ -270,7 +271,7 @@ describe("pnpm inside a linked fixture (F-4)", () => {
it("is used by every fixture that links node_modules and runs pnpm", async () => {
const listed = spawnSync(
"git",
["grep", "-l", "linkFixtureNodeModules(", "--", "scripts", "tests"],
["grep", "-l", "linkFixtureNodeModules(", "--", ...selectRepositoryPaths("fixture-code")],
{ encoding: "utf8" },
);
expect(listed.status, listed.stderr).toBe(0);
+2 -1
View File
@@ -8,6 +8,7 @@ import { afterAll, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
/**
* 2026-11-07. The template ships no sample feature: what the generated
@@ -114,7 +115,7 @@ describe("docs/manual code blocks, pasted into a generated feature", () => {
);
}
for (const program of ["tsconfig.app.json", "tsconfig.test.json"]) {
for (const program of selectRepositoryPaths("feature-typecheck")) {
const typecheck = run(root, path.resolve("node_modules/.bin/tsc"), ["--project", program]);
expect(typecheck.output, program).toBe("");
expect(typecheck.status, program).toBe(0);
@@ -8,6 +8,7 @@ import { afterAll, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
/**
* 1103/09-02. The product extension point has to hold on the typecheck path,
@@ -291,7 +292,7 @@ function expectTypecheckPasses(root: string): void {
expect(generated.stderr).toBe("");
expect(generated.status).toBe(0);
for (const project of ["tsconfig.app.json", "tsconfig.node.json", "tsconfig.test.json"]) {
for (const project of selectRepositoryPaths("product-typecheck")) {
const typecheck = spawnSync(
path.resolve("node_modules/.bin/tsc"),
["--project", path.join(root, project)],
+113 -31
View File
@@ -8,9 +8,11 @@ import {
parseRepositoryLayout,
REPOSITORY_LAYOUT,
REPOSITORY_LAYOUT_FILE,
REPOSITORY_LAYOUT_SETS,
selectRepositoryEntries,
selectRepositoryPaths,
} from "../../scripts/lib/repository-layout.ts";
import { REMOVAL_FIXTURE_DOCUMENT_TESTS } from "../../scripts/lib/removal-fixture.ts";
/**
* The repository layout rules of docs/manual/03-outside-feature-folder.md
@@ -29,6 +31,10 @@ function trackedFiles(): string[] {
}
const rootItemNames = new Set(REPOSITORY_LAYOUT.map((entry) => entry.path));
/** Tracked items: the ones a list in code can go stale on when one moves. */
const trackedRootNames = new Set(
REPOSITORY_LAYOUT.filter(({ kind }) => kind !== "untracked").map((entry) => entry.path),
);
describe("repository layout registry (R1)", () => {
// A removal fixture copies part of the repository, so the claim is one way:
@@ -42,6 +48,13 @@ describe("repository layout registry (R1)", () => {
).toEqual([]);
});
it("lists untracked items that have no tracked file", () => {
const tracked = new Set(trackedFiles().map((file) => file.split("/")[0]!));
const untracked = REPOSITORY_LAYOUT.filter(({ kind }) => kind === "untracked");
expect(untracked.length).toBeGreaterThan(0);
expect(untracked.filter(({ path: item }) => tracked.has(item)).map(({ path: item }) => item)).toEqual([]);
});
it("rejects an entry that is not a root item, a duplicate and a path outside its item", () => {
const entry = { path: "src", kind: "source", role: "app", readBy: "build" };
expect(() => parseRepositoryLayout({ schemaVersion: 1, entries: [{ ...entry, path: "src/app" }] })).toThrow(
@@ -60,67 +73,136 @@ describe("repository layout registry (R1)", () => {
expect(() => parseRepositoryLayout({ schemaVersion: 1, entries: [{ ...entry, sets: ["everything"] }] })).toThrow(
/unknown set/u,
);
expect(() => parseRepositoryLayout({ schemaVersion: 1, entries: [{ ...entry, kind: "untracked" }] })).toThrow(
/optional/u,
);
expect(() =>
parseRepositoryLayout({ schemaVersion: 1, sets: { "fixture-copy": "copied" }, entries: [entry] }),
).toThrow(/must describe exactly/u);
});
it("selects whole items and paths inside items in registry order", () => {
const layout = parseRepositoryLayout({
schemaVersion: 1,
entries: [
{ path: ".gitea", kind: "tool-convention", role: "ci", readBy: "gitea", setPaths: { "secret-scan": [".gitea/workflows/a.yml"] } },
{ path: "recipes", kind: "source", role: "recipes", readBy: "tsc", optional: true, sets: ["secret-scan"] },
{ path: "src", kind: "source", role: "app", readBy: "build", sets: ["secret-scan", "vite-build"] },
{ path: ".ci", kind: "tool-convention", role: "ci", readBy: "ci", setPaths: { "secret-scan": [".ci/workflows/a.yml"] } },
{ path: "extras", kind: "source", role: "extras", readBy: "tsc", optional: true, sets: ["secret-scan"] },
{ path: "app", kind: "source", role: "app", readBy: "build", sets: ["secret-scan", "vite-build"] },
],
});
expect(selectRepositoryPaths("secret-scan", layout)).toEqual([".gitea/workflows/a.yml", "recipes", "src"]);
expect(selectRepositoryPaths("vite-build", layout)).toEqual(["src"]);
expect(selectRepositoryPaths("secret-scan", layout)).toEqual([".ci/workflows/a.yml", "extras", "app"]);
expect(selectRepositoryPaths("vite-build", layout)).toEqual(["app"]);
expect(selectRepositoryEntries("secret-scan", layout).filter(({ optional }) => optional)).toEqual([
{ path: "recipes", optional: true },
{ path: "extras", optional: true },
]);
});
});
/**
* design-docs repo-structure/04-frontend-layout.md §2.4: seven places kept
* their own literal lists of root paths, each a different subset. Six are
* code; the seventh is the secret scan policy, a JSON document the release
* candidate carries, which keeps a copy of its set held equal here.
* their own literal lists of root paths, each a different subset; about
* twenty more were found on 2026-11-11. Every tracked code file is checked, so
* a new list fails here instead of waiting for a review to find it.
*/
const LAYOUT_CONSUMERS = Object.freeze([
"scripts/lib/removal-fixture.ts",
"scripts/lib/vite-build-inputs.ts",
"scripts/verify-extreme-scale.ts",
"scripts/check-architecture.ts",
"tests/unit/deletable-history-documents.test.ts",
]);
/** It checked the policy against a list of its own; the copy check below replaces it. */
const FORMER_CONSUMERS = Object.freeze(["tests/unit/supply-chain.test.ts"]);
const CODE_FILE = /\.(?:[cm]?ts|tsx|[cm]?js)$/u;
/** The sets that only tests in REMOVAL_FIXTURE_DOCUMENT_TESTS read, sorted. */
const DOCUMENT_TEST_SETS = ["agent-harness", "documentation-inputs", "feature-typecheck"];
/**
* Lists that look like root path lists but describe a made-up repository a
* test builds in memory: moving a root item never changes them. Only the exact
* list in that file is excused, and an entry that no longer matches fails, so
* it cannot hide a later list.
*/
const MADE_UP_REPOSITORY_LISTS: readonly Readonly<{ file: string; list: string; reason: string }>[] = [
{
file: "tests/unit/docs-system.test.ts",
list: "docs, docs/architecture, docs/architecture/layers.md, src, src/platform",
reason: "knownPaths of the in-memory repository the docs-system checker test builds",
},
];
const STRING = String.raw`(?:"[^"\n]*"|'[^'\n]*'|` + "`[^`\\n]*`)";
const STRING_ARRAY = new RegExp(String.raw`\[\s*${STRING}(?:\s*,\s*${STRING})+\s*,?\s*\]`, "gu");
/** Array literals of two or more string literals that are root item names. */
function literalRootLists(source: string, roots: ReadonlySet<string>): string[] {
const code = source.replace(/^\s*\/\/.*$/gmu, "");
/**
* Array literals of string literals that are all root items or paths inside
* one, two or more of them tracked. In an argument vector only the paths after
* `--` count, so `git grep … -- <paths>` is a list and a list of subcommand
* names that happen to include `docs` is not.
*/
function literalRootLists(
source: string,
tracked: ReadonlySet<string> = trackedRootNames,
roots: ReadonlySet<string> = rootItemNames,
): string[] {
const code = source.replace(/\/\*[\s\S]*?\*\//gu, "").replace(/^\s*\/\/.*$/gmu, "");
const isRootPath = (value: string) => roots.has(value) || (value.includes("/") && roots.has(value.split("/")[0]!));
return [...code.matchAll(STRING_ARRAY)]
.map(([literal]) => [...literal.matchAll(new RegExp(STRING, "gu"))].map(([value]) => value.slice(1, -1)))
.filter((values) => new Set(values.filter((value) => roots.has(value))).size >= 2)
.map((values) => (values.includes("--") ? values.slice(values.lastIndexOf("--") + 1) : values))
.filter((values) => values.every(isRootPath) && new Set(values.filter((value) => tracked.has(value))).size >= 2)
.map((values) => values.join(", "));
}
describe("root path lists (R2)", () => {
it.each(LAYOUT_CONSUMERS)("%s chooses a set from the registry", (consumer) => {
const source = readFileSync(consumer, "utf8");
expect(source).toMatch(/repository-layout\.ts/u);
expect(literalRootLists(source, rootItemNames)).toEqual([]);
it("are chosen from the registry everywhere in the code", () => {
const files = trackedFiles().filter((file) => CODE_FILE.test(file) && existsSync(file));
expect(files.length).toBeGreaterThan(100);
const found = files.flatMap((file) => literalRootLists(readFileSync(file, "utf8")).map((list) => ({ file, list })));
const excused = (file: string, list: string) =>
MADE_UP_REPOSITORY_LISTS.some((entry) => entry.file === file && entry.list === list);
expect(
found.filter(({ file, list }) => !excused(file, list)).map(({ file, list }) => `${file}: [${list}]`),
`choose a set from ${REPOSITORY_LAYOUT_FILE} with selectRepositoryPaths`,
).toEqual([]);
// A removal drill copy may lack the excused file; an excuse is stale only where the file is checked.
expect(
MADE_UP_REPOSITORY_LISTS.filter(
(entry) => files.includes(entry.file) && !found.some(({ file, list }) => entry.file === file && entry.list === list),
),
"MADE_UP_REPOSITORY_LISTS entries that match no list any more",
).toEqual([]);
});
it.each(FORMER_CONSUMERS)("%s keeps no list of root paths", (consumer) => {
expect(literalRootLists(readFileSync(consumer, "utf8"), rootItemNames)).toEqual([]);
it("finds a literal root list, also after -- in an argument vector, and nothing else", () => {
const tracked = new Set(["alpha", "beta"]);
const roots = new Set(["alpha", "beta", "gamma"]);
expect(literalRootLists(`const ROOTS = ["alpha", "beta/x.ts", "gamma"];`, tracked, roots)).toEqual([]);
expect(literalRootLists(`const ROOTS = ["alpha", "beta", "gamma"];`, tracked, roots)).toEqual([
"alpha, beta, gamma",
]);
expect(literalRootLists(`spawn("git", ["grep", "-l", "x", "--", "alpha", "beta"]);`, tracked, roots)).toEqual([
"alpha, beta",
]);
// A command list that names two items among other words is not a list of paths.
expect(literalRootLists(`const COMMANDS = ["alpha", "beta", "help"];`, tracked, roots)).toEqual([]);
// Untracked items alone never move with the code, as in a list of build output folders.
expect(literalRootLists(`const SKIP = ["alpha", "gamma"];`, tracked, roots)).toEqual([]);
expect(literalRootLists(`/** ["alpha", "beta"] */\n// ["alpha", "beta"]`, tracked, roots)).toEqual([]);
});
it("finds a literal root list", () => {
expect(literalRootLists(`const ROOTS = ["src", "tests", "other"];`, rootItemNames)).toEqual(["src, tests, other"]);
expect(literalRootLists(`const ROOTS = ["src"];\nconst X = ["a", "b"];`, rootItemNames)).toEqual([]);
it("has a reader for every set", () => {
// A reader calls the registry with the set's name; naming it is not enough.
// This file reads secret-scan, which its policy test keeps equal.
const readers = trackedFiles()
.filter((file) => CODE_FILE.test(file) && existsSync(file) && file !== "scripts/lib/repository-layout.ts")
.map((file) => ({ file, source: readFileSync(file, "utf8") }));
const reads = (source: string, set: string) =>
new RegExp(String.raw`selectRepository(?:Paths|Entries)\(\s*"${set}"`, "u").test(source);
const unreadBy = (files: readonly { source: string }[]) =>
REPOSITORY_LAYOUT_SETS.filter((set) => !files.some(({ source }) => reads(source, set))).sort();
// A removal drill that copies no documents deletes the tests that read them
// (removalFixtureExcludedTests in scripts/lib/removal-fixture.ts), and with
// them the only readers of DOCUMENT_TEST_SETS; FE-GATE-020 failed on that.
const documentTestsDeleted = REMOVAL_FIXTURE_DOCUMENT_TESTS.some((file) => !existsSync(file));
expect(unreadBy(readers), "sets no code selects").toEqual(documentTestsDeleted ? DOCUMENT_TEST_SETS : []);
const documentTests = new Set<string>(REMOVAL_FIXTURE_DOCUMENT_TESTS);
expect(
unreadBy(readers.filter(({ file }) => !documentTests.has(file))),
"sets only REMOVAL_FIXTURE_DOCUMENT_TESTS select (DOCUMENT_TEST_SETS)",
).toEqual(DOCUMENT_TEST_SETS);
});
// A removal fixture deletes some of these inputs on purpose — removing the
+2 -10
View File
@@ -8,6 +8,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { localBuildEnvironment } from "../../scripts/lib/build-environment.ts";
import { verifyBuildManifestOutputs } from "../../scripts/lib/build-manifest-outputs.ts";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
import { buildManifestArtifactSchema } from "../../src/contracts/release-artifacts.ts";
import { turnOnServiceWorker } from "../e2e/support/service-worker-builds.ts";
@@ -24,16 +25,7 @@ import { turnOnServiceWorker } from "../e2e/support/service-worker-builds.ts";
*/
const ROOT = ".tmp/runs/build-probe";
const repoRoot = process.cwd();
const skipped = new Set([
"node_modules",
".git",
".claude",
".generated",
".tmp",
"dist",
"artifacts",
"graphify-out",
]);
const skipped = new Set(selectRepositoryPaths("checkout-copy-skip"));
let copy: string | undefined;
let failed: SpawnSyncReturns<string> | undefined;
@@ -2,6 +2,8 @@ import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
/**
* Owner decision 2026-11-07 (docs/work/reference/decisions.md): the root
* AGENTS.md and CLAUDE.md, `.claude/` and `docs/work/` are the template's
@@ -10,7 +12,7 @@ import { describe, expect, it } from "vitest";
* work manual, which makes verify:documentation check the paths, scripts and
* gate IDs they name.
*/
const CONTRACT = Object.freeze(["AGENTS.md", "CLAUDE.md", ".claude", "docs/work"]);
const CONTRACT = selectRepositoryPaths("agent-harness");
// Built from pieces: deletable-history-documents.test.ts fails on code that
// names a folder a copy may delete.
const PAST_PLANS = ["docs", "history"].join("/");
@@ -11,7 +11,11 @@ import {
REMOVABLE_TEMPLATE_FEATURES,
removableTemplateFeaturePaths,
} from "../../scripts/lib/removable-template-features.ts";
import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts";
import {
REMOVAL_FIXTURE_COPY_TARGETS,
REMOVAL_FIXTURE_DOCUMENT_TARGETS,
} from "../../scripts/lib/removal-fixture.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
/**
* 1105/14-01. A copy that deleted a sample listed in
@@ -22,8 +26,8 @@ import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.
* writes, listed and named in a document, then deleted.
*/
const CHECKER = "scripts/verify-documentation-readiness.ts";
/** What verify:documentation reads besides the code. */
const DOCUMENTS = Object.freeze(["README.md", "CHANGELOG.md", "docs", "AGENTS.md"]);
/** What verify:documentation reads besides the code: the documents a drill copies. */
const DOCUMENTS = REMOVAL_FIXTURE_DOCUMENT_TARGETS;
const LISTED_SAMPLE = Object.freeze({
featureId: "listed-sample-feature",
@@ -100,8 +104,7 @@ async function verifyDocuments(document: string, mutate: (text: string) => strin
const root = path.join(parent, "frontend");
try {
// The pin says which commit of the paired backend the documents describe.
const inputs = ["README.md", "docs", "config/contracts/backend-contract-pin.json"];
for (const entry of inputs) await cp(entry, path.join(root, entry), { recursive: true });
for (const entry of selectRepositoryPaths("documentation-inputs")) await cp(entry, path.join(root, entry), { recursive: true });
const target = path.join(root, document);
await writeFile(target, mutate(await readFile(target, "utf8")));
const result = spawnSync(process.execPath, [path.resolve(CHECKER)], { cwd: root, encoding: "utf8" });
@@ -6,6 +6,7 @@ import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
/**
* 09-01. The central composers (`src/features/installed-*`) are typed from the
@@ -150,7 +151,7 @@ describe("installing a second feature (09-01)", () => {
const root = await mkdtemp(path.join(tmpdir(), "two-feature-install-"));
roots.push(root);
await cp(path.resolve("src"), path.join(root, "src"), { recursive: true });
for (const config of ["tsconfig.base.json", "tsconfig.app.json"]) {
for (const config of selectRepositoryPaths("app-typecheck")) {
await cp(path.resolve(config), path.join(root, config));
}
await linkFixtureNodeModules(root);