Merge lane K: CI, guardrails and release fixes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-25 23:42:40 +09:00
co-authored by Claude Opus 5.5
88 changed files with 2049 additions and 746 deletions
+69 -31
View File
@@ -2,6 +2,7 @@
"forbidden": [
{
"name": "domain-is-framework-neutral",
"comment": "domain holds framework-neutral models and pure policies. Keep the dependency out: move the code to application, or pass the value in from there.",
"severity": "error",
"from": {
"path": "^src/domain"
@@ -12,6 +13,7 @@
},
{
"name": "application-does-not-know-concrete-runtime",
"comment": "application owns use cases and the ports they need. Declare a port under src/application/ports and let src/bootstrap pass the concrete adapter.",
"severity": "error",
"from": {
"path": "^src/application"
@@ -22,6 +24,7 @@
},
{
"name": "presentation-does-not-know-adapters",
"comment": "§4. Presentation talks to application ports, not concrete adapters, the composition root or the TanStack runtime. Exception: src/presentation/adapters/query is the TanStack Query binding, the one place @tanstack is imported (docs/architecture/frontend-ports-adapters-and-boundaries.md). It needs @tanstack only; concrete-adapters-compose-only-in-bootstrap still keeps it off src/adapters. Owner: frontend-platform. Revisit if the binding moves out of presentation.",
"severity": "error",
"from": {
"path": "^src/presentation/(?!adapters/query)"
@@ -32,6 +35,7 @@
},
{
"name": "page-templates-own-layout-only",
"comment": "Page templates own layout only. Take data and actions as props from the page that uses the template.",
"severity": "error",
"from": {
"path": "^src/presentation/templates"
@@ -42,6 +46,7 @@
},
{
"name": "icon-vendor-is-facade-only",
"comment": "VD-05. lucide-react is imported by the icon vendor facade only; product code uses the semantic icons from the design-system index, so replacing the vendor touches one file.",
"severity": "error",
"from": {
"path": "^src",
@@ -51,8 +56,22 @@
"path": "^lucide-react$"
}
},
{
"name": "design-system-is-reached-through-its-index",
"comment": "VD-05, 12-08. Code outside src/presentation/design-system imports its public index.ts only, so the primitives can change behind it. Named facades: src/presentation/components/ui/*.ts re-export the canonical primitives under their pre-VD-05 paths (VD-05 Rollback). Exception: src/presentation/templates/page-templates.tsx reads PaginationLandmarkContext, which index.ts does not export. Owner: frontend-platform. Revisit: export it from index.ts or move the page templates into the design system.",
"severity": "error",
"from": {
"path": "^src/",
"pathNot": "^src/presentation/(design-system/|components/ui/[^/]+\\.ts$|templates/page-templates\\.tsx$)"
},
"to": {
"path": "^src/presentation/design-system/",
"pathNot": "^src/presentation/design-system/index\\.ts$"
}
},
{
"name": "adapters-do-not-know-presentation",
"comment": "An adapter implements an application port. It never imports UI or the composition root; pass what it needs through the port or its factory arguments.",
"severity": "error",
"from": {
"path": "^src/adapters"
@@ -63,6 +82,7 @@
},
{
"name": "feature-domain-is-framework-neutral",
"comment": "A feature's domain is framework-neutral, like src/domain. Move the code to the feature's application, or pass the value in from there.",
"severity": "error",
"from": {
"path": "^src/features/[^/]+/domain"
@@ -73,6 +93,7 @@
},
{
"name": "feature-application-does-not-know-runtime",
"comment": "A feature's application declares the ports it needs. Put the port in the feature's application and implement it in the feature's adapters/; bootstrap wires the two.",
"severity": "error",
"from": {
"path": "^src/features/[^/]+/application"
@@ -83,6 +104,7 @@
},
{
"name": "feature-presentation-does-not-know-outbound-adapters",
"comment": "Feature presentation calls its application API. The feature's adapters/ are wired by bootstrap, so import the application facade instead.",
"severity": "error",
"from": {
"path": "^src/features/[^/]+/presentation"
@@ -93,6 +115,7 @@
},
{
"name": "feature-adapters-do-not-know-presentation",
"comment": "A feature adapter implements the feature's ports and never imports UI or the composition root. Pass what it needs through the port.",
"severity": "error",
"from": {
"path": "^src/features/[^/]+/adapters"
@@ -103,6 +126,7 @@
},
{
"name": "concrete-adapters-compose-only-in-bootstrap",
"comment": "Only src/bootstrap constructs concrete adapters. Depend on the application port or facade; bootstrap composes the adapter behind it.",
"severity": "error",
"from": {
"path": "^src/(domain|application|presentation|contracts)"
@@ -113,7 +137,7 @@
},
{
"name": "external-contract-package-single-import-path",
"comment": "§4.1: a generated service package may only be imported from src/features/<feature>/contracts/*-contract-contribution.ts",
"comment": "§4.1: a generated service package may only be imported from src/features/<feature>/contracts/*-contract-contribution.ts. Owner: frontend-platform.",
"severity": "error",
"from": {
"path": "^src",
@@ -125,7 +149,7 @@
},
{
"name": "presentation-does-not-fetch-directly",
"comment": "§9.2 / appendix B: a page or hook never opens a socket, worker or HTTP adapter itself",
"comment": "§9.2 / appendix B: a page or hook never opens a socket, worker or HTTP adapter itself. Call the application API; bootstrap composes the adapter behind it.",
"severity": "error",
"from": {
"path": "^src/(presentation|features/[^/]+/presentation)"
@@ -134,9 +158,20 @@
"path": "^src/adapters/(http|realtime|service-worker|web-worker|storage)"
}
},
{
"name": "unselected-realtime-runtime-is-not-composed",
"comment": "§9.2 / 12-10. Realtime and Web Push are NOT_SELECTED in the template (src/features/installed-runtime-capabilities.ts), so the composition root and the installed-feature registries do not import their concrete adapters. A project that selects one replaces this rule when it wires the runtime. Owner: frontend-platform.",
"severity": "error",
"from": {
"path": "^src/(bootstrap/|features/installed-feature-)"
},
"to": {
"path": "^src/adapters/(realtime|web-push)/"
}
},
{
"name": "generic-worker-has-no-network-or-credentials",
"comment": "§16.13 / §21.10: a CPU worker never imports HTTP, realtime or auth",
"comment": "§16.13 / §21.10: a CPU worker never imports HTTP, realtime or auth. Do the network call on the page side and post the data to the worker.",
"severity": "error",
"from": {
"path": "^src/adapters/web-worker"
@@ -180,7 +215,7 @@
},
{
"name": "generic-presentation-does-not-compose-the-product",
"comment": "§4 / §9. Which features are installed is a product decision that belongs to bootstrap. Generic presentation reads the installed registries directly today; the paths below are the exact set that does so, frozen so the coupling cannot spread while the assembly is lifted into bootstrap.",
"comment": "§4 / §9. Which features are installed is a product decision that belongs to bootstrap. Exception: the generic presentation modules in pathNot read the installed registries today. The list names exact files, so a new module that reads a registry fails the gate. Owner: frontend-platform. Revisit when the assembly is lifted into bootstrap; remove each file from the list as it stops reading the registries.",
"severity": "error",
"from": {
"path": "^src/presentation/",
@@ -192,7 +227,7 @@
},
{
"name": "adapters-do-not-know-other-concrete-adapters",
"comment": "docs/architecture/layers.md §4: a concrete adapter never depends on another concrete adapter. Only the adapter kernel is shared — `src/adapters/platform` (clock, abort primitive, capacity guard) and the browser-data result helpers. `query-cache` still reads two collaborator types from `cross-context-invalidation`; that edge is named here rather than left silent, and closes when those types are lifted to a port.",
"comment": "docs/architecture/layers.md §4: a concrete adapter never depends on another concrete adapter. The adapter kernel is shared on purpose and any adapter may import it: src/adapters/platform/** (clock, abort primitive, capacity guard), src/adapters/browser-file-storage/result.ts (browser-data result helpers) and src/adapters/cross-context-invalidation/index.ts (the cross-context invalidation transport and its types). Owner: frontend-platform. No new file-level exception is added here; a new shared primitive goes into src/adapters/platform/.",
"severity": "error",
"from": {
"path": "^src/adapters/([^/]+)/"
@@ -204,7 +239,7 @@
},
{
"name": "adapter-groups-are-reached-through-their-barrel",
"comment": "어댑터 그룹의 공개 표면은 그 그룹의 index.ts다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 src/adapters를 뺀 이유는 어댑터끼리의 간선은 바로 위 adapters-do-not-know-other-concrete-adapters가 이미 담당하고, 커널(platform/**)은 파일 단위로 공유되기 때문이다 — scripts/check-adapter-inventory.ts가 네 소비자에게 platform/abortable-operation.ts로 해석되는 specifier를 직접 요구한다. 도착점에서 1단계 중첩 index.ts를 허용한 이유는 storage/indexeddb와 storage/opfs가 각자 독립적으로 제거 가능한 런타임이고(scripts/test-browser-file-storage-runtime-removal.ts), 그래서 각자의 배럴이 곧 경계이기 때문이다.",
"comment": "어댑터 그룹의 공개 표면은 그 그룹의 index.ts다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 src/adapters를 뺀 이유는 어댑터끼리의 간선은 바로 위 adapters-do-not-know-other-concrete-adapters가 이미 담당하고, 커널(platform/**)은 파일 단위로 공유되기 때문이다 — scripts/check-adapter-inventory.ts가 네 소비자에게 platform/abortable-operation.ts로 해석되는 specifier를 직접 요구한다. 예외: 도착점에서 storage/indexeddb/index.ts와 storage/opfs/index.ts만 서브배럴로 허용한다. 두 폴더는 browser-file-storage 번들의 런타임이고, 제거 드릴(scripts/test-browser-file-storage-runtime-removal.ts)은 그 번들 전체(browser-file-storage, browser-files, browser-transfer, cache-storage, storage/indexeddb, storage/opfs)를 함께 지운다. 최상위 storage 배럴(Web Storage)은 그 뒤에도 남아야 하므로 두 폴더를 재수출하지 않고, 그래서 각 서브배럴이 그 런타임의 공개 경계다. 다른 2단계 index.ts는 공개 배럴이 아니다(리뷰 12-07). 담당: frontend-platform. 재검토: 새 런타임을 따로 제거할 수 있게 만들 때 그 서브배럴을 이 목록에 추가한다.",
"severity": "error",
"from": {
"path": "^src/",
@@ -212,7 +247,7 @@
},
"to": {
"path": "^src/adapters/[^/]+/",
"pathNot": "^src/adapters/[^/]+/index\\.ts$|^src/adapters/[^/]+/[^/]+/index\\.ts$"
"pathNot": "^src/adapters/[^/]+/index\\.ts$|^src/adapters/storage/(indexeddb|opfs)/index\\.ts$"
}
},
{
@@ -239,6 +274,30 @@
"pathNot": "^src/contexts/$1/"
}
},
{
"name": "feature-and-app-roots-do-not-reach-adapters",
"comment": "12-03. The graph checks one edge at a time, so a module that presentation may import must not re-export a concrete adapter: presentation would then reach it with every direct rule passing. That covers the files outside a feature's layer folders (src/features/*.ts, src/features/<feature>/*.ts), src/contexts and src/apps. Inside a feature, only its adapters/ folder reaches src/adapters; the product composes adapters in bootstrap. Exception: src/features/feature-adapter-contribution.ts imports the InstalledHttpOperationExecutor type that bootstrap hands to feature adapters (type only). Owner: frontend-platform. Revisit when that type moves to an application port.",
"severity": "error",
"from": {
"path": "^src/(features/[^/]+\\.tsx?$|features/[^/]+/[^/]+\\.tsx?$|contexts/|apps/)",
"pathNot": "^src/features/feature-adapter-contribution\\.ts$"
},
"to": {
"path": "^src/adapters/"
}
},
{
"name": "presentation-does-not-import-apps-or-contexts",
"comment": "12-03. Apps and contexts compose features, including their runtime, so presentation importing them is a path around presentation-does-not-know-adapters. Exception: src/presentation/routes/app-router.tsx mounts the deployable app's route tree (src/apps/template-app.ts). Owner: frontend-platform. Revisit when the router is assembled in bootstrap together with the frozen generic-presentation-does-not-compose-the-product list.",
"severity": "error",
"from": {
"path": "^src/(presentation/|features/[^/]+/presentation/)",
"pathNot": "^src/presentation/routes/app-router\\.tsx$"
},
"to": {
"path": "^src/(apps|contexts)/"
}
},
{
"name": "observability-vendors-live-behind-adapters",
"comment": "Spec §24. Features, platform, application, domain, contracts and presentation emit observability only through the provider-neutral TelemetryPort. A vendor telemetry SDK may be imported only by an adapter-side transport under src/adapters.",
@@ -253,7 +312,7 @@
},
{
"name": "platform-kernel-is-product-neutral",
"comment": "Spec §4. src/platform holds product-neutral primitives (budgets, execution, telemetry pipeline, validation, error envelopes). It never reaches up into a concrete feature, context, adapter, bootstrap or presentation module. Routing composes deployable-app descriptors by type and is the one named exception.",
"comment": "Spec §4. src/platform holds product-neutral primitives (budgets, execution, telemetry pipeline, validation, error envelopes). It never reaches up into a concrete feature, context, adapter, bootstrap or presentation module. Exception: src/platform/routing composes deployable-app descriptors by type. Owner: frontend-platform. Revisit if routing gains a product-specific import.",
"severity": "error",
"from": {
"path": "^src/platform/",
@@ -265,33 +324,12 @@
},
{
"name": "no-circular-dependencies",
"comment": "A cycle makes the modules impossible to load or remove one at a time. Move the shared part into a lower module that both import.",
"severity": "error",
"from": {},
"to": {
"circular": true
}
}
],
"options": {
"doNotFollow": {
"path": "node_modules"
},
"exclude": {
"path": "^(dist|artifacts|tests/fixtures)"
},
"enhancedResolveOptions": {
"exportsFields": [
"exports"
],
"conditionNames": [
"import",
"require",
"node",
"default"
]
},
"tsConfig": {
"fileName": "tsconfig.app.json"
}
}
]
}
+4 -4
View File
@@ -83,16 +83,14 @@ jobs:
if: ${{ startsWith(gitea.ref, 'refs/tags/v') || (gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'release' || inputs.stage == 'production' || inputs.stage == 'field')) }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
HOSTING_BASE_URL: "${{ vars.HOSTING_BASE_URL }}"
strategy:
fail-fast: false
matrix:
include:
- { gate: FE-GATE-012, name: bundle, browser: false }
- { gate: FE-GATE-014, name: config-compatibility, browser: false }
- { gate: FE-GATE-019, name: hosting-header, browser: false }
- { gate: FE-GATE-026, name: lab-performance, browser: true }
- { gate: FE-GATE-028, name: manual-accessibility-review, browser: false }
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
@@ -374,11 +372,13 @@ jobs:
if: ${{ gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'production' || inputs.stage == 'field') }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
HOSTING_BASE_URL: "${{ vars.HOSTING_BASE_URL }}"
strategy:
fail-fast: false
matrix:
include:
- { gate: FE-GATE-016, name: rollback-drill }
- { gate: FE-GATE-019, name: hosting-header }
- { gate: FE-GATE-021, name: runbook-boot-config }
- { gate: FE-GATE-022, name: runbook-chunk-mismatch }
- { gate: FE-GATE-023, name: runbook-api-degradation }
+2 -2
View File
@@ -1,2 +1,2 @@
engine-strict=true
save-exact=true
# pnpm 11 reads engineStrict and saveExact from pnpm-workspace.yaml, not from
# this file (review 13-09). Keep only npm-level settings such as registry auth here.
+61 -6
View File
@@ -21,8 +21,54 @@ corepack pnpm install --frozen-lockfile
corepack pnpm dev
```
Runtime-public settings live in `public/config.json` and are validated before
the product tree mounts. Client secrets are forbidden.
## Runtime configuration
Runtime-public settings are validated against one schema before the product
tree mounts (`runtimeConfigV2ArtifactSchema` in
`src/contracts/release-artifacts.ts`). Client secrets are forbidden.
The source of truth is `config/runtime/<profile>.json`, one file per
environment: `local`, `development`, `staging`, `production`. `corepack pnpm
build` writes `dist/config.json` from the selected profile
(`scripts/generate-runtime-config.ts`). `public/config.json` is only the local
profile for `corepack pnpm dev`; the build replaces it, so settings put there
never reach a deployment. Keep it equal to `config/runtime/local.json` plus
`BUILD_ID: local-build` and `RELEASE_ID: local-release`; nothing checks that
yet.
Build and deploy variables, lowest precedence first:
| Variable | Sets | Default |
| --- | --- | --- |
| `APP_PROFILE` | which `config/runtime/<profile>.json` is used | `local`; an empty value fails the build |
| `RUNTIME_API_BASE_URL` | `API_BASE_URL`, overriding the profile | the profile value |
| `RUNTIME_TELEMETRY_ENDPOINT` | `TELEMETRY_ENDPOINT`, overriding the profile | the profile value |
| `VITE_BUILD_ID` | `BUILD_ID` in the runtime config and the release manifest | `local-build` |
| `RELEASE_ID` | `RELEASE_ID` in the runtime config and the release manifest | `local-release` |
| `RELEASE_TARGET` | the environment FE-GATE-027 admits the build to; must equal `APP_PROFILE` | none; admission refuses without it |
`verify:documentation` fails if this table stops naming a variable the build or
admission reads (`scripts/verify-documentation-readiness.ts`).
Only the two `RUNTIME_*` values can differ from the reviewed profile. Anything
else changes by editing the profile file. Staging and production reject demo
auth and non-HTTPS endpoints.
A production build and its admission check:
```bash
APP_PROFILE=production \
RUNTIME_API_BASE_URL=https://api.example.com/ \
RUNTIME_TELEMETRY_ENDPOINT=https://telemetry.example.com/v1/events \
VITE_BUILD_ID=<unique build id> RELEASE_ID=<unique release id> \
corepack pnpm build
APP_PROFILE=production RELEASE_TARGET=production corepack pnpm check:release-admission
```
With `CI=true` the gate runner (`corepack pnpm ci:gate`) also requires
`VITE_COMMIT_SHA`, `SOURCE_DATE_EPOCH` and `CI_RUNNER_IMAGE` before it runs a
gate (`scripts/lib/build-environment.ts`, `scripts/run-ci-gate.ts`). The CI variable
list is in [`docs/operations/ci-quality-gates.md`](docs/operations/ci-quality-gates.md).
## Included starter experience
@@ -123,6 +169,11 @@ corepack pnpm drill:runbooks
corepack pnpm check:ci
```
`drill:runbooks` stops at the first drill that is not `PASS`. Without provider
evidence every drill ends `UNVERIFIED` (exit 3), because a drill never reports
a check it could not run locally as `PASS`; see "Runbook jobs" in
[`docs/operations/ci-quality-gates.md`](docs/operations/ci-quality-gates.md).
`test:all` is the ordinary product-development loop and intentionally excludes
host-level CI-runner assurance. Run `corepack pnpm test:system` only on the
compatible Linux assurance host described in
@@ -152,17 +203,21 @@ corepack pnpm exec playwright install --with-deps chromium firefox webkit
Two gates intentionally need external evidence:
- `review:a11y-manual` needs a signed human keyboard/focus/screen-reader review
for all ten registered routes: `APP_HOME`, `EXAMPLES_PLATFORM`,
- `review:a11y-manual` (release gate FE-GATE-028) needs a signed human
keyboard/focus/screen-reader review for all ten registered routes: `APP_HOME`, `EXAMPLES_PLATFORM`,
`EXAMPLES_UI`, `EXAMPLES_STATES`, `EXAMPLES_AUTH`, `NOT_FOUND`,
`REFERENCE_RESOURCE_LIST`, `REFERENCE_RESOURCE_DETAIL`,
`REFERENCE_RESOURCE_FORM` and `REFERENCE_RESOURCE_STATUS`.
`verify:documentation` derives that list from the route registry and fails if
this paragraph falls behind it.
this paragraph falls behind it. The merge gate FE-GATE-009 runs only
`review:a11y-manual -- --format-only`, which checks that every route record
keeps the template's fields, reviewed or still pending.
- `collect:web-vitals-evidence` stays `FAIL_UNVERIFIED` until a reviewed minimum
eligible-sample threshold and 28 days of production data exist.
Live release verification additionally requires `HOSTING_BASE_URL`.
Live hosting verification (FE-GATE-019, production stage) requires
`HOSTING_BASE_URL` and a deployed promoted release; without it the result is
`UNVERIFIED`, not `PASS`.
## CI and evidence
-38
View File
@@ -1,38 +0,0 @@
{
"schemaVersion": 1,
"layers": {
"domain": {
"root": "src/domain",
"mayImport": ["src/domain"]
},
"application": {
"root": "src/application",
"mayImport": ["src/application", "src/domain", "src/contracts"]
},
"presentation": {
"root": "src/presentation",
"mayImport": ["src/presentation", "src/application", "src/domain", "src/contracts"]
},
"adapters": {
"root": "src/adapters",
"mayImport": ["src/adapters", "src/application", "src/domain", "src/contracts"]
},
"bootstrap": {
"root": "src/bootstrap",
"mayImport": ["src"]
}
},
"forbidden": [
["domain", "application"],
["domain", "presentation"],
["domain", "adapters"],
["domain", "bootstrap"],
["application", "presentation"],
["application", "adapters"],
["application", "bootstrap"],
["presentation", "adapters"],
["presentation", "bootstrap"],
["adapters", "presentation"],
["adapters", "bootstrap"]
]
}
+3 -3
View File
@@ -1,11 +1,11 @@
{
"schemaVersion": 1,
"owner": "frontend-platform",
"reason": "12-04: FE-GATE-003 runs the image resolve-signal type fixture and FE-GATE-010 runs check:adapter-inventory",
"reason": "13-05 (D-14): FE-GATE-019 probes the deployed promoted release in the production stage; the fixture is UNVERIFIED",
"gates": 27,
"commands": 93,
"commands": 95,
"commandReferences": 105,
"artifacts": 109,
"stages": 5,
"gateShapeSha256": "36d731b377e03518e744e2aea14f049bcf1286b6cd40ff24869a380db44d39b0"
"gateShapeSha256": "648066f2ba0dd38c3193550ecb4bd030a2e0f66027919256648f78333564db3c"
}
+62 -67
View File
@@ -215,6 +215,11 @@
"expectedExitCode": 1,
"expectedDiagnosticId": "Risk coverage failed:"
},
{
"id": "check-scale-pr",
"script": "check:scale:pr",
"expect": "pass"
},
{
"id": "test-component",
"script": "test:component",
@@ -292,6 +297,15 @@
"script": "review:a11y-manual",
"expect": "pass"
},
{
"id": "check-a11y-manual-format",
"script": "review:a11y-manual",
"args": [
"--",
"--format-only"
],
"expect": "pass"
},
{
"id": "check-architecture",
"script": "check:architecture",
@@ -1109,55 +1123,37 @@
"id": "artifact-artifacts-tests-a11y-manual-APP-HOME-md",
"path": "artifacts/tests/a11y-manual/APP_HOME.md",
"schemaId": "markdown",
"production": "command-generated",
"producerCommandIds": [
"review-a11y-manual"
]
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-UI-md",
"path": "artifacts/tests/a11y-manual/EXAMPLES_UI.md",
"schemaId": "markdown",
"production": "command-generated",
"producerCommandIds": [
"review-a11y-manual"
]
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-STATES-md",
"path": "artifacts/tests/a11y-manual/EXAMPLES_STATES.md",
"schemaId": "markdown",
"production": "command-generated",
"producerCommandIds": [
"review-a11y-manual"
]
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-AUTH-md",
"path": "artifacts/tests/a11y-manual/EXAMPLES_AUTH.md",
"schemaId": "markdown",
"production": "command-generated",
"producerCommandIds": [
"review-a11y-manual"
]
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-REFERENCE-RESOURCE-LIST-md",
"path": "artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md",
"schemaId": "markdown",
"production": "command-generated",
"producerCommandIds": [
"review-a11y-manual"
]
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-NOT-FOUND-md",
"path": "artifacts/tests/a11y-manual/NOT_FOUND.md",
"schemaId": "markdown",
"production": "command-generated",
"producerCommandIds": [
"review-a11y-manual"
]
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-report-json",
@@ -1511,12 +1507,6 @@
"build-release-candidate"
]
},
{
"id": "artifact-artifacts-quality-gates-FE-GATE-016-txt",
"path": "artifacts/quality/gates/FE-GATE-016.txt",
"schemaId": "text",
"production": "runner-generated"
},
{
"id": "artifact-artifacts-runbooks-FE-RB-005-record-json",
"path": "artifacts/runbooks/FE-RB-005/record.json",
@@ -1717,6 +1707,12 @@
"path": "artifacts/quality/gates/FE-GATE-027.txt",
"schemaId": "text",
"production": "runner-generated"
},
{
"id": "artifact-artifacts-quality-gates-FE-GATE-028-txt",
"path": "artifacts/quality/gates/FE-GATE-028.txt",
"schemaId": "text",
"production": "runner-generated"
}
],
"gates": [
@@ -1800,7 +1796,8 @@
"test-unit",
"test-contract",
"test-coverage",
"check-coverage-fixture"
"check-coverage-fixture",
"check-scale-pr"
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-005-txt",
"evidenceArtifactIds": [
@@ -1877,18 +1874,11 @@
"name": "accessibility",
"commandIds": [
"test-a11y",
"review-a11y-manual"
"check-a11y-manual-format"
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-009-txt",
"evidenceArtifactIds": [
"artifact-artifacts-tests-a11y-json",
"artifact-artifacts-tests-a11y-manual-APP-HOME-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-UI-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-STATES-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-AUTH-md",
"artifact-artifacts-tests-a11y-manual-REFERENCE-RESOURCE-LIST-md",
"artifact-artifacts-tests-a11y-manual-NOT-FOUND-md",
"artifact-artifacts-tests-a11y-manual-report-json"
"artifact-artifacts-tests-a11y-json"
],
"retentionClassId": "merge-cycle"
},
@@ -2025,19 +2015,6 @@
],
"retentionClassId": "release-coherence"
},
{
"id": "FE-GATE-016",
"name": "rollback-drill",
"commandIds": [
"build",
"drill-runbook"
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-016-txt",
"evidenceArtifactIds": [
"artifact-artifacts-runbooks-FE-RB-005-record-json"
],
"retentionClassId": "prod-drill"
},
{
"id": "FE-GATE-017",
"name": "diagram-review",
@@ -2077,7 +2054,7 @@
"evidenceArtifactIds": [
"artifact-artifacts-release-hosting-headers-json"
],
"retentionClassId": "release-coherence",
"retentionClassId": "prod-drill",
"requiresEnvironment": [
"HOSTING_BASE_URL"
]
@@ -2189,6 +2166,24 @@
"artifact-artifacts-release-deployment-admission-json"
],
"retentionClassId": "release-coherence"
},
{
"id": "FE-GATE-028",
"name": "manual-accessibility-review",
"commandIds": [
"review-a11y-manual"
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-028-txt",
"evidenceArtifactIds": [
"artifact-artifacts-tests-a11y-manual-APP-HOME-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-UI-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-STATES-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-AUTH-md",
"artifact-artifacts-tests-a11y-manual-REFERENCE-RESOURCE-LIST-md",
"artifact-artifacts-tests-a11y-manual-NOT-FOUND-md",
"artifact-artifacts-tests-a11y-manual-report-json"
],
"retentionClassId": "release-coherence"
}
],
"stages": [
@@ -2222,9 +2217,9 @@
"FE-GATE-012",
"FE-GATE-014",
"FE-GATE-015",
"FE-GATE-019",
"FE-GATE-026",
"FE-GATE-027"
"FE-GATE-027",
"FE-GATE-028"
]
},
{
@@ -2234,7 +2229,7 @@
"release"
],
"gateIds": [
"FE-GATE-016",
"FE-GATE-019",
"FE-GATE-021",
"FE-GATE-022",
"FE-GATE-023",
@@ -2328,18 +2323,13 @@
"gateIds": [
"FE-GATE-012",
"FE-GATE-014",
"FE-GATE-019",
"FE-GATE-026"
"FE-GATE-026",
"FE-GATE-028"
],
"browserGateIds": [
"FE-GATE-026"
],
"environment": [
{
"name": "HOSTING_BASE_URL",
"value": "${{ vars.HOSTING_BASE_URL }}"
}
],
"environment": [],
"steps": [
{
"kind": "checkout"
@@ -2764,7 +2754,7 @@
"condition": "production",
"timeoutMinutes": 45,
"gateIds": [
"FE-GATE-016",
"FE-GATE-019",
"FE-GATE-021",
"FE-GATE-022",
"FE-GATE-023",
@@ -2772,7 +2762,12 @@
"FE-GATE-025"
],
"browserGateIds": [],
"environment": [],
"environment": [
{
"name": "HOSTING_BASE_URL",
"value": "${{ vars.HOSTING_BASE_URL }}"
}
],
"steps": [
{
"kind": "checkout"
+6 -34
View File
@@ -1,57 +1,29 @@
{
"schemaVersion": 1,
"entries": [
{
"path": "tests/scale/benchmark.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
},
{
"path": "tests/scale/composition-scale.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
"reason": "Scale suite in the main or nightly tier (scripts/scale/run-scale-profile.ts). No CI job runs those tiers: both include baseline-regression, which compares timings only on the CPU model that recorded config/scale/benchmark-baseline.json and reports incomplete elsewhere (review 11-03). Run check:scale:main or check:scale:nightly on that machine. The CPU-independent pr tier runs in FE-GATE-005."
},
{
"path": "tests/scale/global-local-independence.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
},
{
"path": "tests/scale/growth-regression.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
},
{
"path": "tests/scale/scale-baseline.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
"reason": "Scale suite in the main or nightly tier (scripts/scale/run-scale-profile.ts). No CI job runs those tiers: both include baseline-regression, which compares timings only on the CPU model that recorded config/scale/benchmark-baseline.json and reports incomplete elsewhere (review 11-03). Run check:scale:main or check:scale:nightly on that machine. The CPU-independent pr tier runs in FE-GATE-005."
},
{
"path": "tests/scale/session/long-session.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
"reason": "Scale suite in the main or nightly tier (scripts/scale/run-scale-profile.ts). No CI job runs those tiers: both include baseline-regression, which compares timings only on the CPU model that recorded config/scale/benchmark-baseline.json and reports incomplete elsewhere (review 11-03). Run check:scale:main or check:scale:nightly on that machine. The CPU-independent pr tier runs in FE-GATE-005."
},
{
"path": "tests/scale/session/network-flap.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
},
{
"path": "tests/scale/synthetic-topology.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
"reason": "Scale suite in the main or nightly tier (scripts/scale/run-scale-profile.ts). No CI job runs those tiers: both include baseline-regression, which compares timings only on the CPU model that recorded config/scale/benchmark-baseline.json and reports incomplete elsewhere (review 11-03). Run check:scale:main or check:scale:nightly on that machine. The CPU-independent pr tier runs in FE-GATE-005."
},
{
"path": "tests/scale/telemetry/telemetry-storm.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
},
{
"path": "tests/scale/traffic/amplification-metrics.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
},
{
"path": "tests/scale/traffic/failure-scenarios.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
},
{
"path": "tests/scale/traffic/retry-after-jitter.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
"reason": "Scale suite in the main or nightly tier (scripts/scale/run-scale-profile.ts). No CI job runs those tiers: both include baseline-regression, which compares timings only on the CPU model that recorded config/scale/benchmark-baseline.json and reports incomplete elsewhere (review 11-03). Run check:scale:main or check:scale:nightly on that machine. The CPU-independent pr tier runs in FE-GATE-005."
},
{
"path": "tests/scale/tsc-diagnostics-parser.test.ts",
"reason": "Scale suite. It runs through check:scale:* (scripts/scale/run-scale-profile.ts) and verify:extreme-scale, which no CI gate calls, because its timing baseline passes only on the CPU that recorded it. Review 11-03 moves it into a PR tier; drop the entry when a gate runs it."
"reason": "Scale suite in the main or nightly tier (scripts/scale/run-scale-profile.ts). No CI job runs those tiers: both include baseline-regression, which compares timings only on the CPU model that recorded config/scale/benchmark-baseline.json and reports incomplete elsewhere (review 11-03). Run check:scale:main or check:scale:nightly on that machine. The CPU-independent pr tier runs in FE-GATE-005."
}
]
}
@@ -1,6 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "ART-FE-RUNBOOK-DRILL@1",
"$id": "ART-FE-RUNBOOK-DRILL@2",
"type": "object",
"required": [
"schemaVersion",
@@ -14,29 +14,39 @@
"recoveryAssertions",
"negativeFixtureFailedAsExpected",
"windowObservedBucket",
"passed"
"providerVerificationRequired",
"result"
],
"$defs": {
"verdict": { "enum": ["PASS", "FAIL", "UNVERIFIED"] }
},
"properties": {
"schemaVersion": { "const": 1 },
"schemaVersion": { "const": 2 },
"runbookId": { "pattern": "^FE-RB-00[1-5]$" },
"releaseId": { "type": "string", "minLength": 1 },
"drillTimestamp": { "type": "string", "format": "date-time" },
"triggerInjected": { "type": "string" },
"triggerAsserted": { "type": "boolean" },
"containmentAsserted": { "type": "boolean" },
"escalationPathAsserted": { "type": "boolean" },
"triggerAsserted": { "$ref": "#/$defs/verdict" },
"containmentAsserted": { "$ref": "#/$defs/verdict" },
"escalationPathAsserted": { "$ref": "#/$defs/verdict" },
"recoveryAssertions": {
"type": "array",
"minItems": 4,
"items": {
"type": "object",
"required": ["assertion", "evidence", "passed"]
"required": ["assertion", "evidence", "result"],
"properties": {
"assertion": { "type": "string", "minLength": 1 },
"evidence": { "type": "string", "minLength": 1 },
"result": { "$ref": "#/$defs/verdict" }
},
"additionalProperties": false
}
},
"negativeFixtureFailedAsExpected": { "type": "boolean" },
"negativeFixtureFailedAsExpected": { "$ref": "#/$defs/verdict" },
"windowObservedBucket": { "type": "string" },
"providerVerificationRequired": { "type": "boolean" },
"passed": { "type": "boolean" }
"result": { "$ref": "#/$defs/verdict" }
},
"additionalProperties": false
}
+6
View File
@@ -10,6 +10,12 @@ registry: `APP_HOME`, `EXAMPLES_PLATFORM`, `EXAMPLES_UI`, `EXAMPLES_STATES`,
blank identity/timestamp/signature fields, pending verdicts, mismatched release
IDs, or missing routes.
The signed review is the release gate FE-GATE-028 (`review:a11y-manual`), so
it is required once per release candidate, not on every merge. The merge gate
FE-GATE-009 runs `review:a11y-manual -- --format-only`: each record must keep
the fields below with `pending`, `pass` or `not-applicable (<reason>)` verdicts,
and a record marked `reviewed` must be complete.
This list is not maintained by hand: `verify:documentation` compares it against
the installed route registry and fails when a registered route is absent. It
said six routes while ten were registered, which put the platform overview and
@@ -206,7 +206,7 @@ src/shared/api
### 1.2 계층 방향
현재 `config/architecture/layers.json`의 방향을 유지한다.
현재 방향을 유지한다. 기준은 `.dependency-cruiser.json` 하나이고 `check:architecture`가 강제한다(`config/architecture/layers.json`은 아무도 읽지 않는 낡은 사본이라 지웠다, 리뷰 12-09).
```text
domain -> domain only
@@ -50,7 +50,10 @@ architecture/security/type negative input으로 전환했다. 이는 7번 결정
- `check:types`는 app, Node scripts/config, tests project를 모두 검사한다.
- TS invalid-call, invalid port, discriminated-union fixture는 실패해야 한다.
- ESLint와 dependency-cruiser는 TS/TSX architecture fixture를 검사한다.
- ESLint와 `check:architecture`의 import 그래프(`scripts/check-architecture.ts`)가
TS/TSX architecture fixture를 검사한다. dependency-cruiser 18은 TypeScript 7을
해석하지 못해 0개 모듈을 검사하고 통과했으므로 실행하지 않는다(리뷰 12-05).
`.dependency-cruiser.json`은 이름만 남은 규칙 파일이고 그래프가 읽는다.
- registry scanner는 TS registry의 required field, uniqueness와 reference를
검증한다.
- browser security gate는 TSX의 금지된 raw HTML fixture를 거절한다.
@@ -38,9 +38,18 @@
## 경계와 검증
- 제품 코드는 `presentation/design-system/index`만 import한다.
- design-system 검사기는 direct icon/headless import, deep import, raw palette,
undefined token과 tooltip-only required information fixture를 거절한다.
- 제품 코드는 `presentation/design-system/index`만 import한다. 예외는 규칙에
이름으로 적는다. `presentation/components/ui/*.ts`는 아래 Rollback의 재수출
facade이고, `presentation/templates/page-templates.tsx`는 index가 내보내지
않는 `PaginationLandmarkContext`를 읽는다.
- deep import와 direct icon import는 `check:architecture` 그래프 규칙
`design-system-is-reached-through-its-index`, `icon-vendor-is-facade-only`
(`.dependency-cruiser.json`)가 거절한다. 경로 해석이 끝난 간선을 보므로
presentation 안의 상대 경로 import도 잡는다(리뷰 12-08). 음성 fixture는
`tests/fixtures/architecture/dependency-graph/import-boundaries`다.
- design-system 검사기(`scripts/check-design-system.ts`)는 headless vendor
import, raw palette, undefined token과 tooltip-only required information
fixture를 거절한다.
- type negative fixture는 accessible name 없는 `IconButton`을 거절한다.
- component test는 decorative icon, form control, Menu, Tabs, Drawer와 Toast를
검증한다.
@@ -65,7 +65,7 @@ P0/P1 acceptance와 P2 recipe 기본값은 `LOCAL_TEMPLATE_READY`다. 다만 실
| 영역 | 현재 판정 | 근거 | 필요한 다음 상태 |
| --- | --- | --- | --- |
| 부트·런타임 설정 | 준비됨 | `src/bootstrap`, runtime schema, release 검사 | 현 상태 유지, TS 전환 시 동일 게이트 유지 |
| 계층 의존 방향 | 준비됨 | dependency-cruiser + TS-aware static graph, unresolved/parse/layer/cycle negative fixture | 새 rule shape와 source extension도 같은 fail-closed graph에 추가 |
| 계층 의존 방향 | 준비됨 | TS-aware static graph(`scripts/check-architecture.ts`, 규칙 `.dependency-cruiser.json`), unresolved/parse/layer/cycle negative fixture. dependency-cruiser 자체는 TS 7을 해석하지 못해 실행하지 않음(12-05) | 새 rule shape와 source extension도 같은 fail-closed graph에 추가 |
| application facade | 준비됨 | module-augmented feature input registry, typed output catalog, provider, production composition test | feature별 input contribution과 제거 gate 유지 |
| REST HTTP client | 준비됨 + hardening delta | reference vertical의 path/search/body projection, attempt timeout/retry, abort/cleanup은 `COMPOSED` | auth fail-close/final invariant, total deadline, bounded decoder, status/media/CSRF/conditional/pagination은 `DESIGNED_NOT_IMPLEMENTED` |
| Browser RPC 공통 계약/runtime | 준비됨/미조립 | V3 operation/profile registry, typed application port, bounded unary/server-stream lifecycle와 unavailable adapter는 `AVAILABLE_NOT_COMPOSED` | actual descriptor/generated client, protocol transport, proxy/provider/browser conformance |
+40 -13
View File
@@ -25,6 +25,15 @@ The following edges are forbidden:
- an adapter to presentation, bootstrap internals, or another concrete adapter
- feature domain/application to its presentation or outbound adapter, and
feature presentation to its outbound adapter
- a module presentation may import to a concrete adapter: files outside a
feature's layer folders (`src/features/*.ts`, `src/features/<id>/*.ts`),
`src/contexts` and `src/apps` (`feature-and-app-roots-do-not-reach-adapters`).
The graph checks one edge at a time, so a re-export there would carry an
adapter into presentation with every other rule passing. The one exception is
the type-only `src/features/feature-adapter-contribution.ts`
- presentation to `src/apps` or `src/contexts`, except
`src/presentation/routes/app-router.tsx`, which mounts the app's route tree
(`presentation-does-not-import-apps-or-contexts`)
## The adapter kernel
@@ -35,14 +44,25 @@ purpose and is the only adapter code an adapter may reach across a group for:
the bounded-capacity guard
- `src/adapters/browser-file-storage/result.ts` — the browser-data result and
failure constructors
- `src/adapters/cross-context-invalidation/index.ts` — the cross-context
invalidation transport and its types. Any adapter may import it; today
`query-cache` does
Each rule above is enforced by `check:architecture`, including the kernel
carve-out, so this table and the executable rules cannot drift apart. Two edges
are still open and are named explicitly in `.dependency-cruiser.json` rather
than left silent: the generic presentation modules that read the installed
registries today, and the two collaborator types `query-cache` reads from
`cross-context-invalidation`. Both lists are frozen — a new edge of either kind
fails the gate.
carve-out, so this table and the executable rules cannot drift apart.
Every exception is written in the rule itself (`.dependency-cruiser.json`): the
exempted path in `pathNot`, and the reason, owner and revisit condition in
`comment` (review 12-07). Besides the kernel, the exceptions are:
- the generic presentation modules that read the installed registries today
(`generic-presentation-does-not-compose-the-product`). The list names exact
files, so a new module that reads a registry fails the gate
- `src/presentation/adapters/query`, the TanStack Query binding
(`presentation-does-not-know-adapters`)
- `src/presentation/routes/app-router.tsx` importing the app
(`presentation-does-not-import-apps-or-contexts`)
- the design-system facades (`design-system-is-reached-through-its-index`)
## 어댑터 그룹의 공개 경계
@@ -63,10 +83,15 @@ fails the gate.
위한 것이다.
`storage`는 최상위 배럴이 `indexeddb/`·`opfs/` 서브배럴을 재수출하지
않는다. 두 런타임이 각자 독립적으로 제거 가능하고
(`test:browser-file-storage-removal`), 그래서 각 서브배럴이 곧 경계다.
규칙의 도착점 정규식이 1단계 중첩 `index.ts`를 배럴로 인정하는 이유가
이것이다.
않는다. 두 폴더는 browser-file-storage 번들의 런타임이다. 제거 드릴
(`test:browser-file-storage-removal`)은 그 번들 전체(`browser-file-storage`,
`browser-files`, `browser-transfer`, `cache-storage`, `storage/indexeddb`,
`storage/opfs`)를 함께 지운다. 최상위 `storage` 배럴(Web Storage)은 그 뒤에도
남아야 하므로 두 폴더를 재수출하지 않고, 그래서 각 서브배럴이 그 런타임의 공개
경계다.
규칙의 도착점 정규식은 이 두 서브배럴만 배럴로 인정한다. 다른 그룹의 2단계
`index.ts`(예: `http/internals/index.ts`)는 공개 배럴이 아니고, 그룹 바깥에서
import하면 실패한다(리뷰 12-07, `dependency-graph/barrel` fixture).
`service-worker/index.ts`는 `tsconfig.service-worker.json`의 `exclude`에
들어 있다. 그 설정이 그룹 폴더를 통째로 WebWorker lib로 컴파일하면서 페이지
@@ -83,8 +108,9 @@ application APIs augment the generic typed input registry. Concrete output
ports are composed in bootstrap and stay hidden behind the application facade.
Project-selected capabilities still implement the same output boundaries.
`check:architecture` keeps dependency-cruiser's report and adds the
authoritative TypeScript-aware graph below it:
`check:architecture` writes the TypeScript-aware graph below. It reads the rules
from `.dependency-cruiser.json` but does not run dependency-cruiser, which cannot
parse TypeScript 7 and checked zero modules (review 12-05):
```json
{
@@ -103,7 +129,8 @@ authoritative TypeScript-aware graph below it:
```
The graph scans TypeScript and TSX, including static, dynamic, type, CommonJS
and JSDoc import references. It applies the path rules from
and JSDoc import references. `import.meta.glob` is a parse failure: it loads
modules without naming one, so no edge rule could see them (review 12-06). It applies the path rules from
`.dependency-cruiser.json`, requires explicit TypeScript extensions for local
source imports, and fails closed on JavaScript-family source/specifiers,
unsupported rule shapes, unresolved imports, parse failures, error-severity
@@ -130,6 +130,15 @@ Web Push를 함께 설치하지 않는다.
integration test를 작성한다.
9. runtime config schema, dependency inventory/approval, SBOM, bundle budget,
browser support와 runbook을 갱신한다.
운영 CSP(`config/hosting/security-headers.json`)도 여기서 넓힌다. 기본 CSP는
아래 기능을 막는다(리뷰 13-08).
- 다른 origin의 realtime: `connect-src`에 `wss://<realtime origin>`을 더한다.
`https:`는 `wss:`를 허용하지 않는다(CSP3 scheme 비교).
- 파일 preview(`src/adapters/browser-files/object-url-lease.ts`의 object URL):
`img-src`에 `blob:`을 더한다.
- 이미지 CDN: `img-src`에 CDN origin을 더한다.
바꾼 CSP 아래에서 `tests/e2e/production-csp.spec.ts`가 그 기능의 화면을 열도록
smoke를 늘린다.
10. 실제 provider integration과 negative behavior가 통과한 뒤에만 catalog 상태를
별도 project catalog에서 `INSTALLED`로 바꾼다.
+3 -2
View File
@@ -53,8 +53,9 @@ and exact input type.
Route contracts/codecs, the route-input provider, and lazy runtime modules are
separate modules so feature pages do not import the router that loads them.
Expected application failures use the shared `Result`/`AppFailure` contract.
The architecture gate analyzes TS/TSX imports independently of
dependency-cruiser, rejects local JavaScript-family specifiers and executable
The architecture gate analyzes TS/TSX imports with its own graph (the rules
live in `.dependency-cruiser.json`; dependency-cruiser itself cannot parse
TypeScript 7 and does not run), rejects local JavaScript-family specifiers and executable
JavaScript-family files, and fails on unresolved imports, parse failures,
forbidden layer edges, or cycles. The remaining project-owned work includes
selecting and verifying real hosting, identity, telemetry, vulnerability and
+5
View File
@@ -29,5 +29,10 @@ sequenceDiagram
CI->>Browser: boot, route, API, and reload-loop smoke
```
In this repository the workflow stops at promotion. The upload, pointer switch
and smoke steps above belong to the project's provider adapter; after it has
deployed the promoted release, FE-GATE-019 probes the live headers (review
13-05, [`release-cache-rollback.md`](../operations/release-cache-rollback.md)).
Rollback changes the active pointer only after confirming that the prior
immutable release has a coherent HTML/assets/config/API/manifest tuple.
@@ -52,7 +52,9 @@ TypeScript 전환 목적은 확장자 변경이 아니라 이 계약을 컴파
1. ESLint가 product와 negative fixture의 `ts`/`tsx`를 모두 검사한다.
2. React Hooks 규칙을 추가하고 TypeScript/ESLint parser와 JSX accessibility
도구는 설치된 compiler/linter의 공식 peer 범위 안에서 선택한다.
3. dependency-cruiser의 extension과 resolver가 TS/TSX를 포함한다.
3. `check:architecture`의 import 그래프가 TS/TSX를 해석한다. 규칙은
`.dependency-cruiser.json`에 있지만 dependency-cruiser는 실행하지 않는다.
TypeScript 7을 해석하지 못해 0개 모듈을 검사했기 때문이다(리뷰 12-05).
4. `scripts/check-registries.ts`가 TS/TSX를 검색한다.
5. `config/contracts/registry-governance.json`과 승인 baseline은 `.ts/.tsx`
source 경로를 사용한다.
+46 -8
View File
@@ -1,6 +1,6 @@
# CI quality-gate orchestration
`config/ci/gates.json` is the executable registry for all 26 gates and the sole
`config/ci/gates.json` is the executable registry for all 27 gates and the sole
workflow model. `.gitea/workflows/quality-gates.yml` is generated from that
strict v2 contract; it is not an independent configuration authority. Update
the registry, run `corepack pnpm generate:ci-workflow`, and commit the generated
@@ -35,9 +35,20 @@ canonical `check:ci`를 돌린다(`scripts/lib/removal-fixture.ts`의
`check:ci`는 `tests/` 아래 테스트 파일(`tests/fixtures` 제외)이 모두 CI 게이트
명령에서 실행되는지도 확인한다. 게이트 명령이 닿는 package script의 Vitest 경로와
Playwright 설정의 `testDir`를 모아 비교한다(`scripts/lib/ungated-tests.ts`).
`run-scale-profile.ts <tier>`를 부르는 명령은 그 tier의 Vitest 경로로 센다.
게이트가 돌리지 않는 테스트는 `config/ci/ungated-tests.json`에 이유와 함께 적어야
한다. 지금은 `tests/scale`의 규모 테스트 13개만 있다(리뷰 11-03에서 PR tier로
옮길 때 뺀다). 게이트가 이미 돌리는 파일을 이 목록에 남겨 두면 실패한다.
한다. 게이트가 이미 돌리는 파일을 이 목록에 남겨 두면 실패한다.
규모 테스트는 이렇게 나뉜다(리뷰 11-03, `scripts/scale/run-scale-profile.ts`).
- `check:scale:pr`은 merge gate `FE-GATE-005`에서 돈다. 개수·상한·증가 모양만
검사하므로 CPU가 달라도 결과가 같다. S0~S2 조합 증가 검사가 여기 있다. S0/S1만
재면 모든 workload가 noise floor 아래라 이차 누적을 놓친다. 조합 timing은
산출물(`artifacts/scale/pr/composition-s0-s2.json`)에 기록만 한다.
- `main`·`nightly`·`release` tier는 CI에서 돌지 않는다. 이 tier들은
`baseline-regression`을 포함한다. 이 단계는 `config/scale/benchmark-baseline.json`을
기록한 CPU 모델에서만 timing을 비교하고, 다른 CPU에서는 `incomplete`로 끝난다.
이 tier에만 있는 테스트 6개는 `ungated-tests.json`에 이유와 함께 남아 있다.
템플릿을 복사해 새 프로젝트를 시작하면 아래 기준선은 템플릿의 값이다. 샘플을
지우거나 구조를 바꾸면 프로젝트 값으로 다시 찍는다.
@@ -83,6 +94,16 @@ The gate runner checks the same inherited environment names before loading the
contract or entering the execution callback, so they cannot reach a child gate
process.
이 셸 파서(`scripts/lib/package-script-graph.ts`)는 리뷰 12-10에서 줄일 수
있는지 확인했고 남겼다. workflow 설치의 `--ignore-scripts`와
`pnpm-workspace.yaml`의 `allowBuilds`로는 막히지 않는 위험이 있기 때문이다.
첫째, 게이트 명령이 직접 설치를 돈다(`verify:lockfile`, 제거 fixture).
`allowBuilds`는 pnpm의 의존성 build script만 제한한다. 루트 프로젝트의 install
hook과 npm/yarn 설치는 `--ignore-scripts`가 없으면 그대로 돈다. 둘째, 게이트가
부르는 이름이 다른 manifest의 script로 바뀌는 경로다(`--prefix`, `--filter`,
`-C`, npm pre/post hook, `npm_config_*`). 이것은 설치 옵션과 관계가 없다. 이유는
파일 머리 주석에도 있다.
The dependency graph is:
```text
@@ -94,9 +115,11 @@ MERGE_READY
DOCUMENTATION_READY (off-chain)
```
`check:architecture`는 dependency-cruiser 결과와 별도로 Babel parser/Node
resolver 기반 `staticImportGraph`를 `artifacts/quality/dependency-report.json`에
기록한다. TS/TSX의 static, dynamic, type, CommonJS 및 JSDoc import를 검사하고,
`check:architecture`는 Babel parser/Node resolver 기반 `staticImportGraph`를
`artifacts/quality/dependency-report.json`에 기록한다. 규칙은
`.dependency-cruiser.json`에서 읽지만 dependency-cruiser는 실행하지 않는다.
dependency-cruiser 18은 TypeScript 7을 해석하지 못해 0개 모듈을 검사하고
통과했다(리뷰 12-05). TS/TSX의 static, dynamic, type, CommonJS 및 JSDoc import를 검사하고,
로컬 source import에는 실제 TypeScript 확장자를 요구한다. 실행 source나 로컬
specifier에 `.js/.jsx/.mjs/.cjs`가 있거나 unresolved dependency, parse failure,
error-severity layer violation, cycle 또는 지원하지 않는 architecture rule
@@ -269,7 +292,20 @@ promotion, and field evidence through aggregation.
Runbook jobs write to the stable path
`artifacts/runbooks/<runbook-id>/record.json`; the dynamic release identity is
stored inside the record. This keeps gate evidence lookup independent from
stored inside the record.
A runbook drill (`drill:runbook`, FE-GATE-021..025) records each verdict as
`PASS`, `FAIL` or `UNVERIFIED` (`scripts/drill-runbook.ts`, record schema in
`scripts/contracts/release-artifacts.ts`). `PASS`/`FAIL` means the drill checked
it against the local `dist/` build; it reads no `public/` placeholder, so a
missing build fails. Browser boot, live API traffic, smoke after a provider
switch, and anything the runbook marks as needing provider verification are
`UNVERIFIED`. One `FAIL` makes the drill `FAIL` (exit 1). Otherwise any
`UNVERIFIED` makes it `UNVERIFIED` (exit 3), and the gate is not `PASS`. So
without provider evidence the production stage stays open. That is the intended
result: a local drill cannot show that the promoted release can be rolled back.
FE-GATE-016 (`rollback-drill`) is retired because it ran the same FE-RB-005
drill as FE-GATE-025 (`RETIRED_GATE_IDS` in `scripts/contracts/ci-gates.ts`). This keeps gate evidence lookup independent from
slashes or other provider-specific characters in `RELEASE_ID`, while each
workflow artifact remains scoped to its own run.
@@ -335,7 +371,9 @@ Repository variables required by higher tiers:
- `RUNNER_IMAGE_DIGEST` for the immutable job-container image digest used by the
`ubuntu-latest` runner label; the workflow exposes it to gates as
`CI_RUNNER_IMAGE` (required by every tier)
- `HOSTING_BASE_URL` for live header verification
- `HOSTING_BASE_URL` for live header verification of the deployed promoted
release (FE-GATE-019, production stage). Without it the gate fails; the
local fixture result is `UNVERIFIED`
- `APP_PROFILE` for the runtime profile the release candidate is built from
(`local`, `development`, `staging`, `production`;
`scripts/generate-runtime-config.ts`). An unset value builds `local`; an empty
+36
View File
@@ -10,6 +10,42 @@ Performance evidence is deliberately split by measurement context:
release-specific production samples over 28 days and evaluates p75 LCP, CLS,
and INP against 2.5 s, 0.10, and 200 ms.
## 번들 예산의 기준선과 여유
리뷰 13-14. 예산은 `config/performance/budgets.json`에 있고
`scripts/check-bundle.ts`가 강제한다. 템플릿 기본 화면만으로 초기 JS 예산의
96%를 쓴다. 첫 기능을 추가하기 전에 아래 숫자를 보고 예산을 정한다.
| 항목 | 값 |
|---|---|
| 초기 JS 예산 | 204,800 gzip bytes(200 KiB) |
| 템플릿 기준선(2026-09-25 측정) | 196,573 gzip bytes. 빌드 ID가 번들에 들어가므로 빌드마다 수백 바이트 달라진다(196,386~196,623 관측) |
| 여유 | 약 8,200 bytes(4%) |
| lazy chunk 예산 | 파일마다 122,880 gzip bytes(120 KiB). 기준선의 가장 큰 lazy chunk는 약 8 KB |
초기 JS 9개 파일 중 세 개가 대부분이다. `index` 93.5 KB, `design-system`
65.6 KB, `preload-helper` 28.5 KB(zod 포함). 나머지 여섯은 합쳐 9 KB 정도다.
측정 조건:
- 초기 파일은 Vite manifest의 entry와 그 static import다
(`scripts/lib/classify-vite-bundle.ts`). dynamic import chunk는 lazy다.
- 합계는 JavaScript만 센다. CSS(`index-*.css`, 8.5 KB gzip)는 예산에 들어가지
않는다.
- gzip은 Node `zlib.gzipSync` 기본 수준(6)으로 잰다
(`scripts/lib/release-candidate.ts`). 호스팅이 brotli로 보내면 전송 크기는 더
작다. 예산은 gzip 기준 그대로 둔다.
- Node·pnpm·runner 이미지는 `artifacts/performance/bundle.json`의 `context`에
기록된다.
예산을 올릴 때는 이 표의 기준선과 새 측정값, 이유를 같은 변경에 적는다.
lab 측정(`scripts/test-performance.ts`, FE-GATE-026)은 local 프로필 build를
`vite preview`로 띄워 한 번만 잰다. named interaction 시간은 Node의
`performance.now()`로 Playwright 클릭부터 heading 대기까지 재므로 Playwright
왕복 시간이 들어간다. 한 번 측정한 값은 흔들린다. 경계 근처 값으로 판단할
때는 여러 번 돌려 중앙값을 본다.
The field minimum eligible-sample threshold is intentionally unresolved until
a privacy-approved telemetry baseline exists. Therefore the field command
fails closed with `FAIL_UNVERIFIED` when run against the example input. Provide
+47 -6
View File
@@ -12,6 +12,32 @@ cache action, and repeats the smoke checks. Rebuilding an old commit, replacing
HTML alone, or declaring recovery from cache-purge completion is prohibited.
Recovery is established by old/new reachability probes.
Before deploying a promoted release later, or rolling back to one, re-verify
its promoted bundle (the five files uploaded by the `promotion` job) with the
archived mode (review 13-04). Provider evidence expires two hours after issue,
so the normal mode refuses any release promoted before that. The archived mode
still checks signatures, digests and the exact five members, and judges
freshness at the release's recorded promotion time
(`promotion-verification.json` `verifiedAt`, which may not lie in the future).
New promotion never uses it (`scripts/lib/exact-promotion-bundle.ts`).
```bash
VULNERABILITY_PUBLIC_KEY_PATH=... VULNERABILITY_KEY_ID=... \
PROVENANCE_PUBLIC_KEY_PATH=... PROVENANCE_KEY_ID=... \
EXPECTED_PROMOTION_RUN_ID=<run id> EXPECTED_PROMOTION_RUN_ATTEMPT=<attempt> \
EXPECTED_PROMOTION_SOURCE_REVISION=<commit> \
EXPECTED_PROMOTION_ARCHIVE_SHA256=<archive sha256> \
corepack pnpm verify:promotion -- --root <promoted bundle directory> --archived
mkdir <release dir> && tar -xzf <promoted bundle directory>/release-candidate.tar.gz -C <release dir>
corepack pnpm drill:runbook -- FE-RB-005 --release-root <release dir>
```
The expected values come from the release record, not from the bundle. The
drill then checks that release's build/config/manifest tuple and its assets,
not the local build. It ends `UNVERIFIED` until the provider switch and smoke
are recorded, because those happen outside this repository.
The provider-independent cache defaults are:
- hashed assets: `public, max-age=31536000, immutable`
@@ -26,9 +52,24 @@ HTML, JSON config/manifest, and hashed JavaScript MIME types are also compared
to the declared allowlist; a cache-correct response with a mismatched
`Content-Type` still fails the hosting gate.
`corepack pnpm verify:hosting-headers` uses a deterministic fixture locally.
Set `HOSTING_BASE_URL` to probe deployed responses; production promotion
requires the artifact to report `mode: "live"`. The live target must be its
canonical, non-loopback HTTPS root URL. Each required surface must return HTTP
200 without leaving that origin before its cache, content-type, and security
headers can count as deployment evidence.
`corepack pnpm verify:hosting-headers` compares the declared headers with a
deterministic fixture when `HOSTING_BASE_URL` is unset. That only shows the
declarations agree with each other, so its result is `UNVERIFIED` (exit 3), not
`PASS` (review 13-05, `scripts/lib/hosting-probe.ts` `hostingVerdict`). Only
`mode: "live"` can pass. The live target must be its canonical, non-loopback
HTTPS root URL. Each required surface must return HTTP 200 without leaving that
origin before its cache, content-type, and security headers can count as
deployment evidence. The hashed asset it requests is the entry script named by
the served `index.html`, so it checks the release that is actually deployed.
FE-GATE-019 is therefore a production-stage gate (`production_gate` job,
`PROD_PROMOTION_READY`). It runs after `promotion` and after the project has
deployed the promoted release. This repository's workflow stops at promotion:
uploading the release, switching the active pointer, and the post-switch smoke
are the project's provider adapter, chosen with the hosting provider.
Keep a retired release's hashed assets reachable while any open tab may still
request them. The minimum is the previous release while the next one is
active (the rolling window modeled in `tests/release/release-fixture.ts`).
Size it to the longest session the product supports; a tab older than that
depends on the reload-once recovery (FE-RB-002).
+5
View File
@@ -11,3 +11,8 @@ Close only when compatibility and release-coherence gates pass, critical smoke
passes, repeated `DEPLOY_MISMATCH` is absent, and the incident timeline records
the restored release ID. Pointer-switch or cache-purge completion alone is not
recovery evidence.
Verify the prior release before switching to it: `verify:promotion -- --root
<bundle> --archived` and `drill:runbook -- FE-RB-005 --release-root <extracted
archive>`. The commands and inputs are in
[`docs/operations/release-cache-rollback.md`](../operations/release-cache-rollback.md).
+17 -1
View File
@@ -7,7 +7,23 @@ maps are prohibited defaults.
`config/hosting/security-headers.json` is the declared header set. Hosting
verification compares that declaration with live responses. CSP deliberately
omits `unsafe-inline` and `unsafe-eval`; production code and built assets must
remain compatible with that baseline.
remain compatible with that baseline. `tests/e2e/production-csp.spec.ts` (part of
`test:e2e`, FE-GATE-008) serves the build with these headers and fails on a
`securitypolicyviolation` event or console error (review 13-08). One
violation is known: zod probes `Function("")` on its first object schema and
the policy refuses it. Parsing still works, but the default build reports the
violation on every boot until zod is configured `jitless` before the first
schema is built. `z.config` in the entry module is too late, because the
bundler evaluates the shared chunks that build schemas first. The smoke sets
zod's global config before page scripts run so it can catch every other
violation; the spec comment names when to remove that. Features that are off by
default need CSP additions when a project selects them; see step 9 in
[optional adapter recipes](../architecture/optional-adapter-recipes.md).
`connect-src 'self' https:` lets script reach any HTTPS origin. Narrowing it to
the runtime config's `API_BASE_URL` and `TELEMETRY_ENDPOINT` origins needs a
header generated per environment at deploy time, because those values are set
per deployment (`scripts/generate-runtime-config.ts`). That generator does not
exist yet; a project that deploys should add it with its provider adapter.
Route guards are UX hints and client validation does not replace backend
authorization or validation.
+69
View File
@@ -39,6 +39,75 @@ Changing it requires `DEPENDENCY_BASELINE_OWNER` and
`DEPENDENCY_BASELINE_REASON`; editing the digest or hardcoding an empty diff is
rejected.
## 무엇을 증명하고 무엇을 증명하지 않는가
리뷰 13-12. 산출물마다 증명 범위가 다르다. 아래 "증명하지 못하는 것"을 증명된
것으로 읽지 않는다.
| 산출물 | 증명하는 것 | 증명하지 못하는 것 |
|---|---|---|
| SBOM(`artifacts/release/sbom.cdx.json`) | lockfile에 고정된 설치 그래프(`pnpm list --depth Infinity`, `scripts/generate-supply-chain.ts`)와 각 패키지의 sha512 integrity, license | 배포물에 실제로 들어간 부분 집합, 취약점 없음 |
| 번들 패키지 목록(`artifacts/quality/vite-module-inventory.json`의 `packages`) | 배포 번들에 모듈이 하나 이상 들어간 패키지의 `name@version`. Vite가 번들에 넣은 모듈에서 바로 만든다(`scripts/lib/vite-module-inventory.ts`) | 패키지 안의 어떤 코드가 실행되는지, 취약점 없음 |
| local provenance(`artifacts/release/provenance.json`) | dist digest, lockfile, source set, SBOM digest가 서로 맞음 | 빌드 과정이 변조되지 않았음, 빌드한 주체. 서명이 없는 자기 보고다(`builder.id`가 `local:`, `invocationId`가 `LOCAL_UNSIGNED`). `predicateType`이 SLSA provenance v1이어도 SLSA 수준을 뜻하지 않는다 |
| 외부 provenance 서명 | 지정 키 보유자가 이 run, source revision, 후보 digest를 보고 서명함 | 빌드 job 자체의 격리, provider가 성실히 검사했음 |
| 외부 vulnerability 서명 | provider가 이 lockfile·dist에 대해 결과를 주장함 | 오프라인 DB의 최신성, 누락 없음 |
번들 패키지 목록은 SBOM의 production 항목에 모두 들어 있어야 한다. 2026-09-25
기준으로 한 건이 어긋난다. `scheduler@0.27.0`은 `react-dom`의 의존성이라 번들에
들어가지만, SBOM과 `config/security/dependency-baseline.json`은 이것을
`development`로 분류한다. `pnpm list` JSON이 production 트리 아래에서 이 패키지를
다시 보여 주지 않고, 그래서 `scripts/lib/supply-chain.ts`의 순회가 development
경로에서만 이것을 만난다. 분류를 고치면 dependency baseline을 다시 승인해야 하므로
(`update:dependency-baseline`) 이 문서에 알려진 차이로 남긴다.
## 최소 구성과 전체 구성
리뷰 13-13. 승격 단계까지 쓰려면 이 문서 아래의 runner 조건(bwrap, prlimit,
systemd-run, systemd user manager 254 이상, cgroup v2 위임)과 오프라인 데이터로
Ed25519 서명 보고서를 내는 provider 두 개가 필요하다. 이 repo는 그 환경에서
workflow 전체를 한 번도 돌리지 않았다. 그래서 두 구성을 나눠 적는다.
| 구성 | 켜는 것 | 보장하는 것 | 보장하지 않는 것 |
|---|---|---|---|
| 최소 구성(provider 없음) | merge·release stage 게이트, `immutable_build`(FE-GATE-015·027). provider 변수는 비워 둔다 | lockfile 무결성과 설치 스크립트 차단, SBOM과 local provenance의 digest 정합, secret scan, 재현 빌드, 후보 archive의 exact member와 digest, release 대상 환경 승인(FE-GATE-027) | 외부 취약점 검사, 서명된 provenance. provider job은 명령과 키가 없어 실패하고, `promotion` job은 두 provider job의 성공을 요구하므로 돌지 않는다. 승격은 사람이 결정한다 |
| 전체 구성 | 위 전부와 `vulnerability_provider`·`provenance_provider`·`promotion` job, 아래 runner 조건과 provider 키 | 위 전부와, 지정 키 보유자가 이 후보 digest·run·source에 서명했다는 것, 승격된 exact-five bundle(`verify:promotion`) | provider가 성실히 검사했는지, 빌드 job 격리(위 "무엇을 증명하고" 표 참고) |
최소 구성으로 운영할 때 승격은 수동 승인이다. 승인자는 `immutable_build`가
올린 후보 archive의 SHA-256(job output `archive_sha256`)과 local evidence를
기록하고, 그 archive를 그대로 배포한다. 다시 빌드하지 않는다. `production_gate`는
`promotion` 뒤에만 돌므로 이 구성의 workflow에서는 실행되지 않는다. 운영
게이트(FE-GATE-019, 021~025)는 배포한 release를 대상으로
`corepack pnpm ci:gate -- FE-GATE-0xx`로 따로 돌려 기록한다.
### provider 신뢰 키 교체와 폐기
신뢰 키는 repo 변수 `VULNERABILITY_PUBLIC_KEY_PATH`·`VULNERABILITY_KEY_ID`,
`PROVENANCE_PUBLIC_KEY_PATH`·`PROVENANCE_KEY_ID`가 가리키는 공개 키 파일이다
(`scripts/lib/provider-trust.ts`). 두 provider는 서로 다른 키를 써야 한다
(`assertDistinctProviderTrust`). 승격 기록은 키 ID·지문과 trust policy
SHA-256을 남긴다.
교체 순서:
1. provider가 새 키 쌍을 만들고 공개 키만 넘긴다.
2. 새 공개 키 파일을 runner가 읽을 수 있는 경로에 두고, 두 변수를 새 경로와 새
key ID로 한꺼번에 바꾼다. 키 ID는 새 값을 쓴다. 이전 ID를 재사용하면 기록만
보고 어느 키였는지 구분할 수 없다.
3. provider 쪽 서명 키를 새 키로 바꾼 뒤 release를 한 번 돌려 `promotion`이
통과하는지 확인한다.
4. 이전 공개 키 파일은 지우지 않고 보관한다. 이전 키로 승격된 release를 나중에
배포하거나 그 release로 롤백할 때 `verify:promotion -- --archived`가 그 키를
요구한다(`docs/operations/release-cache-rollback.md`).
폐기 순서(키 유출 등):
1. 해당 변수에서 그 키를 즉시 뺀다. 그 키로 서명된 새 승격은 이때부터 실패한다.
2. 보관 중인 이전 공개 키 파일도 지운다. 그 키로만 서명된 과거 release는
`verify:promotion -- --archived`를 통과하지 못한다.
3. 그런 release를 다시 써야 하면 새 키로 provider 검증을 다시 받는다. 같은 후보
archive를 대상으로 한 새 provider 실행이 필요하고, 다시 빌드하지 않는다. 이
repo에는 이 재검증 전용 job이 없다. 필요한 프로젝트가 만든다.
## External promotion controls
Promotion reads the provider files named by `VULNERABILITY_REPORT_PATH` and
@@ -1103,8 +1103,11 @@ validate한다.
외부 배포 주소나 28일 field evidence가 없는 skeleton 개발 단계에서는 해당 gate가
실제 프로젝트가 채울 계약으로 남는다. 이를 fake data로 통과시키지 않는다.
현재 `FE-GATE-009`의 signed manual accessibility review는 merge gate다. 이
문서는 이를 production/field gate로 이동시키지 않는다.
signed manual accessibility review는 release gate `FE-GATE-028`이다
(`config/ci/gates.json`, 리뷰 08-06). 사람의 서명은 릴리스 후보 하나에 대해
하므로 merge마다 요구할 수 없다. merge gate `FE-GATE-009`는 자동 axe 검사와
기록 형식 검사(`review:a11y-manual -- --format-only`,
`scripts/lib/manual-a11y-evidence.ts`의 `validateManualA11yRecordFormat`)만 한다.
### 16.4 병렬화와 shard
+75 -43
View File
@@ -6,6 +6,10 @@ import type { Rule } from "eslint";
const sourceExtensions = "{ts,tsx,mts,cts}";
// 12-09. Editor-time aid only: these patterns show a layer violation while
// typing. The layer rules themselves live in .dependency-cruiser.json and are
// enforced by check:architecture, which resolves every import. Change a rule
// there first; these lists cover a subset and may lag behind it.
const layerPatterns = {
domain: [
"**/application/**",
@@ -33,8 +37,21 @@ const layerPatterns = {
adapters: ["**/presentation/**", "**/bootstrap/**"],
};
function restrictedImports(patterns: readonly string[]) {
return ["error", { patterns }];
// 12-11. Each pattern group carries the reason and the way out; the default
// message only named the pattern.
const layerMessages = {
domain:
"domain stays framework-neutral (.dependency-cruiser.json domain-is-framework-neutral). Move the code to application or pass the value in.",
application:
"application declares ports and never imports UI, adapters or bootstrap (application-does-not-know-concrete-runtime). Add a port under application/ports; bootstrap passes the adapter.",
presentation:
"presentation reaches the runtime through the application API (presentation-does-not-know-adapters). Use the application facade; bootstrap composes adapters.",
adapters:
"an adapter implements an application port and never imports UI or bootstrap (adapters-do-not-know-presentation). Pass what it needs through the port.",
} as const;
function restrictedImports(patterns: readonly string[], message: string) {
return ["error", { patterns: [{ group: [...patterns], message }] }];
}
const restrictedBrowserDataProperties = [
@@ -539,7 +556,7 @@ export default [
{
files: [`src/domain/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports(layerPatterns.domain),
"no-restricted-imports": restrictedImports(layerPatterns.domain, layerMessages.domain),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -564,7 +581,7 @@ export default [
{
files: [`src/application/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports(layerPatterns.application),
"no-restricted-imports": restrictedImports(layerPatterns.application, layerMessages.application),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -589,7 +606,7 @@ export default [
{
files: [`src/presentation/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports(layerPatterns.presentation),
"no-restricted-imports": restrictedImports(layerPatterns.presentation, layerMessages.presentation),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -613,24 +630,30 @@ export default [
`src/presentation/adapters/query/**/*.${sourceExtensions}`,
],
rules: {
"no-restricted-imports": restrictedImports([
"**/adapters/http/**",
"**/adapters/storage/**",
"**/adapters/auth/**",
"**/bootstrap/**",
"**/application/ports/out/**",
]),
"no-restricted-imports": restrictedImports(
[
"**/adapters/http/**",
"**/adapters/storage/**",
"**/adapters/auth/**",
"**/bootstrap/**",
"**/application/ports/out/**",
],
"the TanStack Query binding may import @tanstack only; reach adapters through application ports (presentation-does-not-know-adapters).",
),
},
},
{
files: [`src/presentation/templates/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports([
"**/application/**",
"**/adapters/**",
"**/bootstrap/**",
"@tanstack/**",
]),
"no-restricted-imports": restrictedImports(
[
"**/application/**",
"**/adapters/**",
"**/bootstrap/**",
"@tanstack/**",
],
"page templates own layout only (page-templates-own-layout-only). Take data and actions as props from the page.",
),
},
},
{
@@ -659,7 +682,7 @@ export default [
{
files: [`src/adapters/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports(layerPatterns.adapters),
"no-restricted-imports": restrictedImports(layerPatterns.adapters, layerMessages.adapters),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -700,7 +723,7 @@ export default [
{
files: [`src/features/*/domain/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports(layerPatterns.domain),
"no-restricted-imports": restrictedImports(layerPatterns.domain, layerMessages.domain),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -725,7 +748,7 @@ export default [
{
files: [`src/features/*/application/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports(layerPatterns.application),
"no-restricted-imports": restrictedImports(layerPatterns.application, layerMessages.application),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -750,15 +773,18 @@ export default [
{
files: [`src/features/*/presentation/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports([
"**/features/*/adapters/**",
"**/adapters/http/**",
"**/adapters/storage/**",
"**/adapters/auth/**",
"**/bootstrap/**",
"**/application/ports/out/**",
"@tanstack/**",
]),
"no-restricted-imports": restrictedImports(
[
"**/features/*/adapters/**",
"**/adapters/http/**",
"**/adapters/storage/**",
"**/adapters/auth/**",
"**/bootstrap/**",
"**/application/ports/out/**",
"@tanstack/**",
],
"feature presentation calls its application API (feature-presentation-does-not-know-outbound-adapters). Bootstrap wires the adapters.",
),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -780,11 +806,14 @@ export default [
{
files: [`src/features/*/adapters/**/*.${sourceExtensions}`],
rules: {
"no-restricted-imports": restrictedImports([
"**/presentation/**",
"**/bootstrap/**",
"@tanstack/**",
]),
"no-restricted-imports": restrictedImports(
[
"**/presentation/**",
"**/bootstrap/**",
"@tanstack/**",
],
"a feature adapter implements the feature's ports and never imports UI or bootstrap (feature-adapters-do-not-know-presentation).",
),
"no-restricted-properties": restrictedBrowserDataProperties,
"no-restricted-globals": [
"error",
@@ -823,14 +852,17 @@ export default [
`tests/fixtures/architecture/forbidden/**/*.${sourceExtensions}`,
],
rules: {
"no-restricted-imports": restrictedImports([
"**/adapters/**",
"**/application/ports/out/**",
"@tanstack/**",
"react",
"react-dom",
"**/application/**",
]),
"no-restricted-imports": restrictedImports(
[
"**/adapters/**",
"**/application/ports/out/**",
"@tanstack/**",
"react",
"react-dom",
"**/application/**",
],
"forbidden architecture fixture: this import must be rejected.",
),
"no-restricted-globals": [
"error",
"fetch",
+10
View File
@@ -1,6 +1,16 @@
# 13-09. pnpm 11 ignores these keys in .npmrc (`pnpm config list` did not show
# them), so an unsupported Node version installed and new dependencies were
# saved with a ^ range. pnpm 11 reads its settings from this file.
engineStrict: true
saveExact: true
allowBuilds:
esbuild: true
msw: true
# 12-07. These exact pins were added on 2026-07-25 (946cf40, f3e105f) while
# they were younger than pnpm's minimum release age. An exclusion covers that
# exact version only, so a later version is checked again. Owner:
# frontend-platform. Revisit: remove an entry when its version is bumped or is
# older than the configured minimum release age.
minimumReleaseAgeExclude:
- '@playwright/test@1.62.0'
- playwright-core@1.62.0
+10 -5
View File
@@ -3,6 +3,7 @@ import { rm } from "node:fs/promises";
import process from "node:process";
import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtime-capabilities.ts";
import { makeDistFilesPublic } from "./lib/dist-permissions.ts";
/**
* §17.2.2. Deterministic two-pass build.
@@ -17,15 +18,16 @@ import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtim
* 5. scan app dist and generate the static asset source
* 6. ACTIVE only: Vite Service Worker build (emptyOutDir = false)
* 7. generate Release Manifest V2 and the build manifest
* 8. make every dist file readable by other users (13-02)
*
* Steps 5 and 6 are skipped for `REMOVE_REGISTRATION`, `PURGE_OWNED_RESOURCES`
* and `null`: those modes never run an active worker build.
*
* Step 4 has to follow the Vite build and precede the asset scan. Vite copies
* `public/` verbatim, so without it every build — including a production one —
* ships the local runtime document; and the Service Worker hashes the emitted
* `config.json`, so the profile must be in place before that inventory is
* taken.
* Step 4 has to follow the Vite build. Vite copies `public/` verbatim, so
* without it every build — including a production one — ships the local
* runtime document. The Service Worker asset scan excludes `config.json`
* (`scripts/generate-service-worker-assets.ts`), so the order against step 5
* is not what keeps the profile out of the worker cache (13-15).
*/
const selection = INSTALLED_RUNTIME_CAPABILITIES.serviceWorker;
@@ -68,3 +70,6 @@ if (buildsActiveWorker) {
// 6. release + build manifest
run("node", ["scripts/generate-build-manifest.ts"]);
// 8. publishable permissions: the validated writer creates 0600 files
await makeDistFilesPublic("dist");
+114 -51
View File
@@ -6,11 +6,13 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { createRequire } from "node:module";
import { architectureDependencyReportArtifactSchema } from "./contracts/release-artifacts.ts";
import { formatArchitectureViolation } from "./lib/architecture-violation-message.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type PathRule = Readonly<{ path?: string; pathNot?: string }>;
type ArchitectureRule = Readonly<{
name: string;
comment?: string;
severity?: string;
from?: PathRule;
to?: PathRule & Readonly<{ circular?: boolean }>;
@@ -53,7 +55,6 @@ type GraphFixtureResult = Readonly<{
failures: string[];
}>;
type DependencyResolution = Readonly<{ path?: string; reason: string }>;
type DependencyCruiserReport = Record<string, unknown>;
type TypeScriptOnlyPolicy = Readonly<{
checkedRoots: readonly string[];
exceptionsAllowed: false;
@@ -111,27 +112,15 @@ function runPnpm(arguments_: string[]) {
});
}
// Keep dependency-cruiser's report and checks. The second graph is authoritative
// for TypeScript 7 coverage because dependency-cruiser 18 cannot parse TS 7 yet.
const dependencyCruiser = runPnpm([
"exec",
"depcruise",
"src",
"--config",
".dependency-cruiser.json",
"--output-type",
"json",
]);
// 12-05 (D-11): this graph is the only architecture checker. dependency-cruiser
// 18 cannot parse TypeScript 7, so it cruised zero modules and still passed.
// .dependency-cruiser.json keeps its name and is read here as the rule file.
const sourceGraph = await analyzeSourceGraph(sourceRoot, "src");
const typeScriptOnlyPolicy = await inspectTypeScriptOnlyPolicy();
const graphFixtureResult = await runGraphFixtureChecks();
const dependencyReport = parseDependencyCruiserReport(dependencyCruiser.stdout);
const graphErrors = blockingViolations(sourceGraph);
const dependencyCruiserReportValid = !(
"dependencyCruiserOutput" in dependencyReport
);
dependencyReport.staticImportGraph = {
const staticImportGraph = {
analyzer: "babel-parser-node-resolver",
modules: sourceGraph.modules,
dependencies: sourceGraph.dependencies,
@@ -162,25 +151,11 @@ dependencyReport.staticImportGraph = {
await writeValidatedJsonArtifact({
path: qualityArtifact,
schema: architectureDependencyReportArtifactSchema,
value: dependencyReport,
value: { staticImportGraph },
});
let architectureFailed = false;
if (!dependencyCruiserReportValid) {
architectureFailed = true;
process.stderr.write("dependency-cruiser returned an invalid JSON report\n");
}
if (dependencyCruiser.status !== 0) {
architectureFailed = true;
process.stderr.write(
(dependencyCruiser.error?.message ?? dependencyCruiser.stderr) ||
dependencyCruiser.stdout ||
"dependency-cruiser failed\n",
);
}
for (const failure of sourceGraph.parseFailures) {
architectureFailed = true;
process.stderr.write(
@@ -197,11 +172,16 @@ for (const dependency of sourceGraph.unresolved) {
for (const violation of graphErrors) {
architectureFailed = true;
const cycle = violation.cycle
? ` (cycle group: ${violation.cycle.join(", ")})`
: "";
process.stderr.write(
`Architecture violation [${violation.rule}]: ${violation.source} -> ${violation.target}${cycle}\n`,
formatArchitectureViolation(
violation,
violation.cycle
? []
: sourceGraph.dependencies
.filter(({ source, target }) => source === violation.source && target === violation.target)
.map(({ specifier }) => specifier),
architectureRules.find(({ name }) => name === violation.rule)?.comment,
),
);
}
@@ -443,7 +423,7 @@ async function importSpecifiers(sourceFile: string): Promise<string[]> {
visitSyntaxNode(syntaxTree, specifiers, nonLiteralModuleLoads);
if (nonLiteralModuleLoads.size > 0) {
throw new Error(
`module loading must use string literals: ${[...nonLiteralModuleLoads].join(", ")}`,
`module loading must name one module with a string literal: ${[...nonLiteralModuleLoads].join(", ")}`,
);
}
for (const comment of syntaxTree.comments ?? []) {
@@ -503,6 +483,17 @@ function visitSyntaxNode(
if (!addStringLiteral(arguments_[0], specifiers)) {
nonLiteralModuleLoads.add("require()");
}
} else if (
nodeType === "CallExpression" &&
syntaxNodeType(node.callee) === "MemberExpression" &&
syntaxNodeType(syntaxNodeProperty(node.callee, "object")) === "MetaProperty" &&
/^glob(?:Eager)?$/u.test(
String(syntaxNodeProperty(syntaxNodeProperty(node.callee, "property"), "name")),
)
) {
// 12-06: a glob pulls in every matching module without naming one, so no
// edge rule can see it. Refuse it like a non-literal import().
nonLiteralModuleLoads.add("import.meta.glob()");
} else if (nodeType === "TSExternalModuleReference") {
addStringLiteral(node.expression, specifiers);
} else if (nodeType === "TSImportType") {
@@ -831,6 +822,7 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
cycleGraph,
barrelGraph,
crossBoundaryGraph,
importBoundaryGraph,
] = await Promise.all([
analyzeSourceGraph(allowedRoot, "src"),
analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"),
@@ -838,6 +830,7 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "cross-boundary"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "import-boundaries"), "src"),
]);
const allowedFiles = new Set(await listFiles(allowedRoot));
const allowedSourceFile = resolve(
@@ -876,6 +869,66 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
target === "src/contexts/admin/value.ts",
),
},
{
name: "feature root re-export of a concrete adapter is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "feature-and-app-roots-do-not-reach-adapters" &&
source === "src/features/alpha/telemetry.ts" &&
target === "src/adapters/telemetry/index.ts",
),
},
{
name: "context re-export of a concrete adapter is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "feature-and-app-roots-do-not-reach-adapters" &&
source === "src/contexts/customer/telemetry.ts" &&
target === "src/adapters/telemetry/index.ts",
),
},
{
name: "presentation import of a context is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "presentation-does-not-import-apps-or-contexts" &&
source === "src/presentation/read-context.ts" &&
target === "src/contexts/customer/telemetry.ts",
),
},
// 12-08 / 12-10: these import rules used to be regular expressions in
// check-design-system.ts and realtime-boundaries.ts beside the graph.
{
name: "design-system deep import is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source }) =>
rule === "design-system-is-reached-through-its-index" &&
source === "src/presentation/pages/deep-import.ts",
),
},
{
name: "design-system index and named facades are accepted",
passed: !blockingViolations(importBoundaryGraph).some(({ source }) =>
["src/presentation/pages/public-import.ts", "src/presentation/components/ui/button.ts"].includes(source),
),
},
{
name: "direct icon vendor import is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source, target }) =>
rule === "icon-vendor-is-facade-only" &&
source === "src/presentation/pages/direct-icon.ts" &&
target === "lucide-react",
),
},
{
name: "unselected realtime runtime composition is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source }) =>
rule === "unselected-realtime-runtime-is-not-composed" &&
source === "src/bootstrap/compose-realtime.ts",
),
},
{
name: "deep adapter import from outside the group is rejected",
passed: blockingViolations(barrelGraph).some(
@@ -885,6 +938,21 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
target === "src/adapters/http/client.ts",
),
},
{
name: "second-level index import from outside the group is rejected",
passed: blockingViolations(barrelGraph).some(
({ rule, source, target }) =>
rule === "adapter-groups-are-reached-through-their-barrel" &&
source === "src/bootstrap/compose-sub-barrel.ts" &&
target === "src/adapters/http/internals/index.ts",
),
},
{
name: "storage runtime sub-barrel import is accepted",
passed: !blockingViolations(barrelGraph).some(
({ source }) => source === "src/bootstrap/compose-storage-sub-barrel.ts",
),
},
{
name: "barrel import from outside the group is accepted",
passed: !blockingViolations(barrelGraph).some(
@@ -954,6 +1022,14 @@ async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
reason.includes("import()"),
),
},
{
name: "import.meta.glob module loads are rejected",
passed: unresolvedGraph.parseFailures.some(
({ source, reason }) =>
source === "src/application/glob-value.ts" &&
reason.includes("import.meta.glob"),
),
},
{
name: "non-literal CommonJS imports are rejected",
passed: unresolvedGraph.parseFailures.some(
@@ -1099,6 +1175,7 @@ function parseArchitectureConfig(value: unknown): ArchitectureConfig {
function isArchitectureRule(value: unknown): value is ArchitectureRule {
if (!isRecord(value) || typeof value.name !== "string") return false;
if (value.comment !== undefined && typeof value.comment !== "string") return false;
if (value.severity !== undefined && typeof value.severity !== "string") {
return false;
}
@@ -1124,17 +1201,3 @@ function isPathRule(value: unknown, allowCircular: boolean): value is PathRule {
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function parseDependencyCruiserReport(
output: string,
): DependencyCruiserReport {
try {
const report: unknown = JSON.parse(output);
if (!report || typeof report !== "object" || Array.isArray(report)) {
throw new Error("dependency-cruiser report must be a JSON object");
}
return report as DependencyCruiserReport;
} catch {
return { summary: { errors: 1 }, dependencyCruiserOutput: output };
}
}
+3 -5
View File
@@ -8,6 +8,7 @@ import {
type GateResult,
} from "./lib/promotion-readiness.ts";
import {
CANONICAL_GATE_IDS,
loadCiGateContract,
indexCiGateContract,
} from "./contracts/ci-gates.ts";
@@ -104,10 +105,7 @@ if (!architecture?.evidenceArtifactIds.some((id) => index.artifacts.get(id)?.pat
failures.push("FE-GATE-010 must publish the typed CI contract report");
}
const expectedGateIds = Array.from(
{ length: 27 },
(_, index) => `FE-GATE-${String(index + 1).padStart(3, "0")}`,
);
const expectedGateIds = CANONICAL_GATE_IDS;
const passingResults: Record<string, GateResult> = Object.fromEntries(
expectedGateIds.map((gateId) => [gateId, "PASS"]),
);
@@ -168,4 +166,4 @@ if (failures.length > 0) {
process.stderr.write(`CI contract failed:\n${failures.join("\n")}\n`);
process.exit(1);
}
process.stdout.write("CI contract: 27 gates, strict v2 graph and generated workflow model PASS\n");
process.stdout.write(`CI contract: ${CANONICAL_GATE_IDS.length} gates, strict v2 graph and generated workflow model PASS\n`);
+4 -12
View File
@@ -97,22 +97,14 @@ const sources = fixtureMode
: await listSourceFiles("src");
for (const file of sources) {
const source = await readFile(file, "utf8");
const vendorFacade =
file === "src/presentation/design-system/icons/vendors/lucide.tsx";
if (!vendorFacade && /from\s+["']lucide-react["']/.test(source)) {
failures.push(`direct icon vendor import in ${file}`);
}
// Icon vendor and design-system deep imports are graph rules in
// .dependency-cruiser.json (check:architecture), which also sees relative,
// dynamic and type imports (12-08, 12-10).
if (
/from\s+["'](?:react-aria-components|@radix-ui\/[^"']+)["']/.test(source)
) {
failures.push(`direct headless vendor import in ${file}`);
}
if (
!file.includes("src/presentation/design-system/") &&
/presentation\/design-system\/(?!index(?:\.tsx?)?["'])/.test(source)
) {
failures.push(`design-system deep import in ${file}`);
}
if (
!file.includes("src/presentation/design-system/tokens/") &&
/(?:#[0-9a-f]{3,8}\b|oklch\(|rgba?\()/i.test(source)
@@ -151,5 +143,5 @@ if (failures.length > 0) {
process.exit(1);
}
process.stdout.write(
`Design system contract: ${report.checkedTokenCount} tokens and vendor boundaries PASS\n`,
`Design system contract: ${report.checkedTokenCount} tokens and headless vendor boundary PASS\n`,
);
@@ -13,7 +13,6 @@ const forbiddenOutput = `${forbidden.stdout}${forbidden.stderr}`;
const expectedRules = [
"NATIVE_REALTIME_API_OUTSIDE_ADAPTER",
"PRESENTATION_INTERVAL_OWNER",
"UNSELECTED_REALTIME_RUNTIME_COMPOSED",
] as const;
if (
@@ -249,6 +249,31 @@ try {
},
nowEpochMs: () => now,
} as const;
// 13-04: the same bundle three hours later. Current freshness refuses the
// expired provider evidence; archived freshness accepts it at the recorded
// promotion time, and still refuses a tampered archive.
const threeHoursLater = now + 3 * 60 * 60 * 1_000;
const archivedAfterWindow = await captureRejection(async () => {
await verifyExactPromotionBundle(exactFiles, {
...bundleTrust,
nowEpochMs: () => threeHoursLater,
freshness: "archived",
});
});
const currentAfterWindow = await captureRejection(async () => {
await verifyExactPromotionBundle(exactFiles, {
...bundleTrust,
nowEpochMs: () => threeHoursLater,
});
});
const tamperedArchive = Buffer.from(exactFiles["release-candidate.tar.gz"]);
tamperedArchive[tamperedArchive.length - 1] ^= 0xff;
const archivedTampered = await captureRejection(async () => {
await verifyExactPromotionBundle(
{ ...exactFiles, "release-candidate.tar.gz": tamperedArchive },
{ ...bundleTrust, nowEpochMs: () => threeHoursLater, freshness: "archived" },
);
});
const absentFiles = { ...exactFiles } as Partial<typeof exactFiles>;
delete absentFiles["provider-verification.json"];
const absent = await captureRejection(async () => {
@@ -282,7 +307,8 @@ try {
await captureCiCandidateArchive({ archivePath, expectedSha256: "0".repeat(64) });
});
const passed =
validImmutable && absent.rejected && invalidTar.rejected && wrongDigest.rejected;
validImmutable && absent.rejected && invalidTar.rejected && wrongDigest.rejected &&
!archivedAfterWindow.rejected && currentAfterWindow.rejected && archivedTampered.rejected;
await cleanupFinalizedPromotion({
runnerTempRoot,
stagingRoot: finalized.stagingRoot,
@@ -314,12 +340,24 @@ try {
status: invalidTar.rejected ? "FAIL_UNVERIFIED" : "PASS",
failures: [invalidTar.failure],
},
archivedAfterWindow: {
status: archivedAfterWindow.rejected ? "FAIL_UNVERIFIED" : "PASS",
failures: archivedAfterWindow.rejected ? [archivedAfterWindow.failure] : [],
},
currentAfterWindow: {
status: currentAfterWindow.rejected ? "FAIL_UNVERIFIED" : "PASS",
failures: [currentAfterWindow.failure],
},
archivedTampered: {
status: archivedTampered.rejected ? "FAIL_UNVERIFIED" : "PASS",
failures: [archivedTampered.failure],
},
},
externalTreeCanary: {
status: validImmutable ? "PASS" : "FAIL_UNVERIFIED",
failures: validImmutable ? [] : ["external tree canary influenced captured archive"],
},
passingFixtureCount: validImmutable ? 1 : 0,
passingFixtureCount: (validImmutable ? 1 : 0) + (archivedAfterWindow.rejected ? 0 : 1),
status: passed ? "PASS" : "FAIL",
},
});
+21 -9
View File
@@ -438,6 +438,19 @@ export type CiGateContractIndex = Readonly<{
jobs: ReadonlyMap<string, CiWorkflowJob>;
retentionClasses: ReadonlyMap<string, CiGateContract["retention"]["classes"][number]>;
}>;
/**
* D-14. FE-GATE-016 (rollback-drill) ran the same FE-RB-005 drill as
* FE-GATE-025 and counted it twice toward production readiness. Its id stays
* retired so no later gate reuses it with a different meaning.
*/
export const RETIRED_GATE_IDS: readonly string[] = Object.freeze(["FE-GATE-016"]);
export const CANONICAL_GATE_IDS: readonly string[] = Object.freeze(
Array.from({ length: 28 }, (_, index) => `FE-GATE-${String(index + 1).padStart(3, "0")}`)
.filter((gateId) => !RETIRED_GATE_IDS.includes(gateId)),
);
/**
* D-13. The contract's size and gate shape are a reviewed baseline, not code
* constants: a project that removes a sample or adds a gate records the new
@@ -789,12 +802,9 @@ function validateContractSemantics(
issue(`stage dependency cycle: ${cycle.join(" -> ")}`);
}
const expectedGateIds = Array.from(
{ length: 27 },
(_, index) => `FE-GATE-${String(index + 1).padStart(3, "0")}`,
);
const expectedGateIds = CANONICAL_GATE_IDS;
if (JSON.stringify(contract.gates.map(({ id }) => id)) !== JSON.stringify(expectedGateIds)) {
issue("gate registry must contain FE-GATE-001..027 in canonical order");
issue(`gate registry must contain FE-GATE-001..028 without retired ${RETIRED_GATE_IDS.join(", ")} in canonical order`);
}
const expectedStages: ReadonlyArray<readonly [string, string, readonly string[], readonly string[]]> = [
["merge", "MERGE_READY", [], PROMOTION_FORMULA.MERGE_READY],
@@ -864,12 +874,12 @@ function validateContractSemantics(
}
const expectedJobOwnership: Readonly<Record<string, readonly string[]>> = {
merge_gate: ["FE-GATE-001", "FE-GATE-002", "FE-GATE-003", "FE-GATE-004", "FE-GATE-005", "FE-GATE-006", "FE-GATE-007", "FE-GATE-008", "FE-GATE-009", "FE-GATE-010", "FE-GATE-011", "FE-GATE-013", "FE-GATE-020"],
release_gate: ["FE-GATE-012", "FE-GATE-014", "FE-GATE-019", "FE-GATE-026"],
release_gate: ["FE-GATE-012", "FE-GATE-014", "FE-GATE-026", "FE-GATE-028"],
immutable_build: ["FE-GATE-015", "FE-GATE-027"],
vulnerability_provider: [],
provenance_provider: [],
promotion: [],
production_gate: ["FE-GATE-016", "FE-GATE-021", "FE-GATE-022", "FE-GATE-023", "FE-GATE-024", "FE-GATE-025"],
production_gate: ["FE-GATE-019", "FE-GATE-021", "FE-GATE-022", "FE-GATE-023", "FE-GATE-024", "FE-GATE-025"],
field_gate: ["FE-GATE-018"],
documentation_gate: ["FE-GATE-017"],
};
@@ -918,7 +928,7 @@ function validateContractSemantics(
}
const expectedEnvironmentBindings: Readonly<Record<string, readonly Readonly<{ name: string; value: string }> []>> = {
merge_gate: [],
release_gate: [{ name: "HOSTING_BASE_URL", value: "${{ vars.HOSTING_BASE_URL }}" }],
release_gate: [],
immutable_build: [
// FE-GATE-027 admits the built artifact to a named environment, so both
// the profile it was built from and the destination it is claimed for are
@@ -964,7 +974,9 @@ function validateContractSemantics(
{ name: "VULNERABILITY_INVOCATION_NONCE", value: "${{ needs.vulnerability_provider.outputs.invocation_nonce }}" },
{ name: "PROVENANCE_INVOCATION_NONCE", value: "${{ needs.provenance_provider.outputs.invocation_nonce }}" },
],
production_gate: [],
// 13-05: FE-GATE-019 probes the promoted release after the provider has
// deployed it, so the live base URL belongs to the production stage.
production_gate: [{ name: "HOSTING_BASE_URL", value: "${{ vars.HOSTING_BASE_URL }}" }],
field_gate: [
{ name: "FIELD_WEB_VITALS_INPUT", value: "${{ vars.FIELD_WEB_VITALS_INPUT }}" },
{ name: "MIN_ELIGIBLE_SAMPLES", value: "${{ vars.MIN_ELIGIBLE_SAMPLES }}" },
+76 -40
View File
@@ -152,6 +152,8 @@ export const moduleInventoryArtifactSchema = z
})
.strict(),
),
// 13-12: `name@version` of every package with a module in the bundle.
packages: z.array(z.string().regex(/^(?:@[^/@]+\/)?[^/@]+@[^/@]+$/u)),
})
.strict();
@@ -723,31 +725,67 @@ export const releaseVerificationArtifactSchema = z
})
.strict();
// 11-01 / 13-03 (D-14): each verdict is PASS or FAIL only when observed on the
// local build; anything that needs a boot, live traffic or the provider is
// UNVERIFIED, and so is a drill with provider scope.
const drillVerdict = z.enum(["PASS", "FAIL", "UNVERIFIED"]);
export type DrillVerdict = z.infer<typeof drillVerdict>;
/** FAIL beats UNVERIFIED beats PASS; provider scope alone keeps a drill UNVERIFIED. */
export function combineDrillVerdicts(
verdicts: readonly DrillVerdict[],
providerVerificationRequired: boolean,
): DrillVerdict {
if (verdicts.includes("FAIL")) return "FAIL";
if (verdicts.includes("UNVERIFIED") || providerVerificationRequired) return "UNVERIFIED";
return "PASS";
}
export const runbookRecordArtifactSchema = z
.object({
schemaVersion: z.literal(1),
schemaVersion: z.literal(2),
runbookId: z.string().regex(/^FE-RB-00[1-5]$/u),
releaseId: nonEmptyString,
drillTimestamp: timestamp,
triggerInjected: nonEmptyString,
triggerAsserted: z.boolean(),
containmentAsserted: z.boolean(),
escalationPathAsserted: z.boolean(),
triggerAsserted: drillVerdict,
containmentAsserted: drillVerdict,
escalationPathAsserted: drillVerdict,
recoveryAssertions: z.array(
z
.object({
assertion: nonEmptyString,
evidence: nonEmptyString,
passed: z.boolean(),
result: drillVerdict,
})
.strict(),
),
negativeFixtureFailedAsExpected: z.boolean(),
negativeFixtureFailedAsExpected: drillVerdict,
windowObservedBucket: nonEmptyString,
providerVerificationRequired: z.boolean(),
passed: z.boolean(),
result: drillVerdict,
})
.strict();
.strict()
.superRefine((record, context) => {
const expected = combineDrillVerdicts(
[
record.triggerAsserted,
record.containmentAsserted,
record.escalationPathAsserted,
...record.recoveryAssertions.map(({ result }) => result),
record.negativeFixtureFailedAsExpected,
],
record.providerVerificationRequired,
);
if (record.result !== expected) {
context.addIssue({
code: "custom",
path: ["result"],
message: `result must be ${expected} for these verdicts`,
});
}
});
const failureList = z.array(nonEmptyString).max(4_096);
const sourceOrFixtureMode = z.enum(["source", "negative-fixture"]);
@@ -948,33 +986,11 @@ const staticImportGraphSchema = z
context.addIssue({ code: "custom", path: ["typeScriptOnlySourcePolicy", "passed"], message: "must agree with violations and summary" });
}
});
const dependencyCruiserSummarySchema = z
.object({
violations: z.array(jsonObject),
error: z.int().nonnegative(),
warn: z.int().nonnegative(),
info: z.int().nonnegative(),
ignore: z.int().nonnegative(),
totalCruised: z.int().nonnegative(),
totalDependenciesCruised: z.int().nonnegative(),
})
.catchall(z.json());
export const architectureDependencyReportArtifactSchema = z.union([
z
.object({
modules: z.array(jsonObject),
summary: dependencyCruiserSummarySchema,
staticImportGraph: staticImportGraphSchema,
})
.strict(),
z
.object({
summary: z.object({ errors: z.literal(1) }).strict(),
dependencyCruiserOutput: z.string(),
staticImportGraph: staticImportGraphSchema,
})
.strict(),
]);
// 12-05 (D-11): dependency-cruiser checked zero modules under TypeScript 7 and
// no longer runs; the report carries the import graph that enforces the rules.
export const architectureDependencyReportArtifactSchema = z
.object({ staticImportGraph: staticImportGraphSchema })
.strict();
export const designSystemReportArtifactSchema = z
.object({
@@ -1023,7 +1039,6 @@ export const realtimeBoundariesArtifactSchema = z
ruleId: z.enum([
"NATIVE_REALTIME_API_OUTSIDE_ADAPTER",
"PRESENTATION_INTERVAL_OWNER",
"UNSELECTED_REALTIME_RUNTIME_COMPOSED",
]),
file: nonEmptyString,
line: z.int().positive(),
@@ -1289,6 +1304,10 @@ export const supplyChainProviderFixturesArtifactSchema = z
validImmutable: providerFixtureResultSchema,
wrongDigest: providerFixtureResultSchema,
invalidTar: providerFixtureResultSchema,
// 13-04: archived re-verification of the same bundle three hours on.
archivedAfterWindow: providerFixtureResultSchema,
currentAfterWindow: providerFixtureResultSchema,
archivedTampered: providerFixtureResultSchema,
})
.strict(),
externalTreeCanary: providerFixtureResultSchema,
@@ -1300,11 +1319,19 @@ export const supplyChainProviderFixturesArtifactSchema = z
const expectedPass =
artifact.actualDefaultVerifier.status === "PASS" &&
artifact.fixtures.validImmutable.status === "PASS" &&
artifact.fixtures.archivedAfterWindow.status === "PASS" &&
artifact.externalTreeCanary.status === "PASS" &&
[artifact.fixtures.absent, artifact.fixtures.wrongDigest, artifact.fixtures.invalidTar]
.every(({ status }) => status === "FAIL_UNVERIFIED");
if (artifact.passingFixtureCount !== (artifact.fixtures.validImmutable.status === "PASS" ? 1 : 0)) {
context.addIssue({ code: "custom", path: ["passingFixtureCount"], message: "must count the passing immutable fixture" });
[
artifact.fixtures.absent,
artifact.fixtures.wrongDigest,
artifact.fixtures.invalidTar,
artifact.fixtures.currentAfterWindow,
artifact.fixtures.archivedTampered,
].every(({ status }) => status === "FAIL_UNVERIFIED");
const passing = [artifact.fixtures.validImmutable, artifact.fixtures.archivedAfterWindow]
.filter(({ status }) => status === "PASS").length;
if (artifact.passingFixtureCount !== passing) {
context.addIssue({ code: "custom", path: ["passingFixtureCount"], message: "must count the passing fixtures" });
}
if ((artifact.status === "PASS") !== expectedPass) {
context.addIssue({ code: "custom", path: ["status"], message: "must agree with required fixture outcomes" });
@@ -1369,6 +1396,8 @@ export const documentationReviewArtifactSchema = z
.strict(),
).min(1),
routeScopeDocumented: z.boolean(),
// 13-15: build and deploy variables README.md does not name.
missingRuntimeVariables: z.array(nonEmptyString),
results: z.array(
z
.object({
@@ -1407,6 +1436,7 @@ export const documentationReviewArtifactSchema = z
artifact.passed !==
(artifact.reportDigestValid &&
artifact.routeScopeDocumented &&
artifact.missingRuntimeVariables.length === 0 &&
artifact.results.every(({ passed }) => passed))
) {
context.addIssue({ code: "custom", path: ["passed"], message: "must agree with report digest, documented scope and review results" });
@@ -1433,9 +1463,15 @@ export const hostingHeadersArtifactSchema = z
.strict(),
).min(1),
passed: z.boolean(),
// 13-05 (D-14): only a live probe can PASS; the fixture is UNVERIFIED.
status: z.enum(["PASS", "FAIL", "UNVERIFIED"]),
})
.strict()
.superRefine((artifact, context) => {
const expectedStatus = !artifact.passed ? "FAIL" : artifact.mode === "live" ? "PASS" : "UNVERIFIED";
if (artifact.status !== expectedStatus) {
context.addIssue({ code: "custom", path: ["status"], message: `must be ${expectedStatus} for this mode and result` });
}
const keys = artifact.results.map(({ surface, header }) => `${surface}\0${header}`);
addUniqueStringIssues(keys, ["results"], context);
const requiredKeys = [
+228 -205
View File
@@ -1,4 +1,5 @@
import { access, mkdir, readFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { shouldRetry } from "../src/adapters/http/retry-policy.ts";
@@ -15,21 +16,30 @@ import {
} from "../src/contracts/release-artifacts.ts";
import { projectTelemetryEvent } from "../src/contracts/telemetry.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contract-contributions.ts";
import { runbookRecordArtifactSchema } from "./contracts/release-artifacts.ts";
import {
combineDrillVerdicts,
runbookRecordArtifactSchema,
type DrillVerdict,
} from "./contracts/release-artifacts.ts";
import { verifyReleaseRuntimeCoherence } from "./lib/release-runtime-coherence.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
// 11-01 / 13-03 (D-14). A verdict is PASS or FAIL only when the drill observed
// it on the local build. What needs a browser boot, live traffic or the hosting
// provider is UNVERIFIED, and so is every drill whose runbook needs provider
// verification: a local drill never claims the release can be recovered.
type RecoveryAssertion = Readonly<{
assertion: string;
evidence: string;
passed: boolean;
result: DrillVerdict;
}>;
type DrillResult = Readonly<{
triggerAsserted: boolean;
containmentAsserted: boolean;
triggerAsserted: DrillVerdict;
containmentAsserted: DrillVerdict;
recoveryAssertions: RecoveryAssertion[];
negativeFixtureFailedAsExpected: boolean;
negativeFixtureFailedAsExpected: DrillVerdict;
providerVerificationRequired: boolean;
}>;
@@ -51,10 +61,8 @@ type RunbookDocument = Readonly<{
export type JsonArtifactReader = (path: string) => Promise<unknown>;
export type RollbackArtifactPaths = Readonly<{
primaryRelease: string;
fallbackRelease: string;
primaryRuntime: string;
fallbackRuntime: string;
release: string;
runtime: string;
}>;
export type RollbackCoherenceOptions = Readonly<{
@@ -63,27 +71,41 @@ export type RollbackCoherenceOptions = Readonly<{
paths?: RollbackArtifactPaths;
}>;
export type DrillOptions = Readonly<{
/**
* Directory holding the release's `dist/`. Defaults to the cwd (the local
* build). 13-04: pass an extracted candidate or promoted archive to drill
* the release that is actually deployed or rolled back to.
*/
releaseRoot?: string;
contractPackages?: readonly InstalledContractPackageIdentity[];
}>;
type DrillContext = Readonly<{
root: string;
contractPackages: readonly InstalledContractPackageIdentity[];
}>;
// 13-03: the drill reads the built release only. It used to fall back to the
// placeholders in public/, so it passed without any build at all.
const DEFAULT_ROLLBACK_PATHS = Object.freeze({
primaryRelease: "dist/release-manifest.json",
fallbackRelease: "public/release-manifest.json",
primaryRuntime: "dist/config.json",
fallbackRuntime: "public/config.json",
release: "dist/release-manifest.json",
runtime: "dist/config.json",
});
async function readJsonArtifact(path: string): Promise<unknown> {
return JSON.parse(await readFile(path, "utf8"));
try {
return JSON.parse(await readFile(path, "utf8"));
} catch (error) {
if (hasErrorCode(error, "ENOENT")) {
throw new Error(`${path} is missing; build the release before running the drill`, { cause: error });
}
throw error;
}
}
async function releaseManifest(
readArtifact: JsonArtifactReader = readJsonArtifact,
paths: RollbackArtifactPaths = DEFAULT_ROLLBACK_PATHS,
): Promise<ReleaseArtifact> {
const value = await readPrimaryOrFallback(
readArtifact,
paths.primaryRelease,
paths.fallbackRelease,
);
return parseReleaseArtifact(value);
function rootedReader(root: string): JsonArtifactReader {
return (file) => readJsonArtifact(path.join(root, file));
}
const validConfig = {
@@ -100,12 +122,48 @@ const validConfig = {
RELEASE_ID: "local-release",
};
function verdict(passed: boolean): DrillVerdict {
return passed ? "PASS" : "FAIL";
}
function assertion(
assertion: string,
evidence: string,
passed: boolean,
result: DrillVerdict,
): RecoveryAssertion {
return { assertion, evidence, passed };
return { assertion, evidence, result };
}
/** An assertion the local drill cannot observe; `needs` names what can. */
function notObserved(name: string, needs: string): RecoveryAssertion {
return assertion(name, `not observed locally; needs ${needs}`, "UNVERIFIED");
}
/**
* Every file the Vite manifest names (entries, lazy chunks, CSS, assets) exists
* in the local dist. Hosting reachability still needs the provider smoke.
*/
async function builtAssetsPresent(root: string): Promise<boolean> {
const manifest = await readJsonArtifact(path.join(root, "dist/.vite/manifest.json"));
if (!manifest || typeof manifest !== "object") return false;
const files = new Set<string>();
for (const chunk of Object.values(manifest as Record<string, Record<string, unknown>>)) {
for (const key of ["file", "css", "assets"] as const) {
const value = chunk[key];
for (const file of Array.isArray(value) ? value : [value]) {
if (typeof file === "string") files.add(file);
}
}
}
if (![...files].some((file) => file.endsWith(".js"))) return false;
try {
await Promise.all(
["index.html", ...files].map((file) => access(path.join(root, "dist", file))),
);
return true;
} catch {
return false;
}
}
async function drillBoot(): Promise<DrillResult> {
@@ -115,19 +173,22 @@ async function drillBoot(): Promise<DrillResult> {
API_BASE_URL: "http://insecure.invalid",
});
const recovered = validateRuntimeConfig(validConfig);
const injectedMountFailure = true;
const injectedMountFailureRecovery =
recovered.success && !injectedMountFailure;
return {
triggerAsserted: !invalid.success,
containmentAsserted: !invalid.success,
triggerAsserted: verdict(!invalid.success),
containmentAsserted: verdict(!invalid.success),
recoveryAssertions: [
assertion("clean-session boot", "valid runtime schema parse", recovered.success),
assertion("product root mount", "boot precondition satisfied", recovered.success),
assertion("config validation", "invalid fixture rejected", !invalid.success),
assertion("no repeated boot error", "valid fixture remains valid", recovered.success),
notObserved("clean-session boot", "a browser boot of the promoted release"),
notObserved("product root mount", "a browser boot of the promoted release"),
assertion(
"config validation",
"invalid fixture rejected, valid fixture accepted",
verdict(!invalid.success && recovered.success),
),
notObserved("no repeated boot error", "boot telemetry from the promoted release"),
],
negativeFixtureFailedAsExpected: !injectedMountFailureRecovery,
// The runbook's negative fixture injects a mount failure after a valid
// config; that needs a mounted app, which a Node drill does not have.
negativeFixtureFailedAsExpected: "UNVERIFIED",
providerVerificationRequired: false,
};
}
@@ -144,7 +205,7 @@ function memoryStorage(): StoragePort {
};
}
async function drillChunkMismatch(): Promise<DrillResult> {
async function drillChunkMismatch(context: DrillContext): Promise<DrillResult> {
const storage = memoryStorage();
const input: Parameters<typeof decideChunkRecovery>[0] = {
failureKind: "DEPLOY_MISMATCH",
@@ -157,29 +218,26 @@ async function drillChunkMismatch(): Promise<DrillResult> {
};
const first = decideChunkRecovery(input);
const second = decideChunkRecovery(input);
const manifest = await releaseManifest();
let assetsReachable = true;
try {
await access("dist/index.html");
await access("dist/.vite/manifest.json");
} catch {
assetsReachable = false;
}
const { coherence } = await verifyRollbackReleaseCoherence({
readArtifact: rootedReader(context.root),
contractPackages: context.contractPackages,
});
return {
triggerAsserted: first.action === "reload-once",
containmentAsserted:
triggerAsserted: verdict(first.action === "reload-once"),
containmentAsserted: verdict(
first.action === "reload-once" && second.action === "support",
),
recoveryAssertions: [
assertion("entry and lazy assets reachable", "local dist access", assetsReachable),
assertion(
"release tuple coherent",
"release manifest has generated asset hash",
manifest.assetManifestHash !== "generated-during-build",
"entry and lazy assets reachable",
"every Vite manifest file exists in the local dist",
verdict(await builtAssetsPresent(context.root)),
),
assertion("second reload blocked", "reload guard decision", second.action === "support"),
assertion("critical route smoke", "built index available", assetsReachable),
assertion("release tuple coherent", "build/config/manifest tuple", verdict(coherence.compatible)),
assertion("second reload blocked", "reload guard decision", verdict(second.action === "support")),
notObserved("critical route smoke", "a browser smoke against the hosted release"),
],
negativeFixtureFailedAsExpected: second.action !== "reload-once",
negativeFixtureFailedAsExpected: verdict(second.action !== "reload-once"),
providerVerificationRequired: true,
};
}
@@ -196,15 +254,20 @@ async function drillApiDegradation(): Promise<DrillResult> {
0,
);
return {
triggerAsserted: true,
containmentAsserted: !unkeyedRetry,
// The trigger is a failure rate over live traffic.
triggerAsserted: "UNVERIFIED",
containmentAsserted: verdict(!unkeyedRetry && safeRetry),
recoveryAssertions: [
assertion("failure rate at baseline", "deterministic recovery window", true),
assertion("no retry amplification", "unkeyed retry policy", !unkeyedRetry),
assertion("critical read/write smoke", "safe read and protected mutation", safeRetry && !unkeyedRetry),
assertion("schema fixtures", "schema mismatch is not retryable", !shouldRetry({ idempotency: "safe" }, { kind: "SCHEMA_MISMATCH" }, 0)),
notObserved("terminal failure rate at baseline", "API failure telemetry from the promoted release"),
assertion("no retry amplification", "unkeyed retry policy", verdict(!unkeyedRetry)),
notObserved("critical read/write smoke", "a read and a write against the live API"),
assertion(
"schema fixtures",
"schema mismatch is not retryable",
verdict(!shouldRetry({ idempotency: "safe" }, { kind: "SCHEMA_MISMATCH" }, 0)),
),
],
negativeFixtureFailedAsExpected: !unkeyedRetry,
negativeFixtureFailedAsExpected: verdict(!unkeyedRetry),
providerVerificationRequired: true,
};
}
@@ -224,7 +287,10 @@ async function drillTelemetry(): Promise<DrillResult> {
attempt_count_bucket: "1",
route_id: "APP_HOME",
});
await adapter.flush();
const flushResolved = await adapter.flush().then(
() => true,
() => false,
);
const projected = projectTelemetryEvent("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: "5xx",
@@ -235,22 +301,25 @@ async function drillTelemetry(): Promise<DrillResult> {
const redacted =
projected.success && !JSON.stringify(projected).includes("raw_url");
return {
triggerAsserted: adapter.droppedCount() === 1,
containmentAsserted: adapter.pendingCount() === 0,
triggerAsserted: verdict(adapter.droppedCount() === 1),
containmentAsserted: verdict(adapter.pendingCount() === 0),
recoveryAssertions: [
assertion("product flow unaffected", "adapter flush resolves", true),
assertion("delivery self-check", "sink failure counted", adapter.droppedCount() === 1),
assertion("queue drained within bound", "pending queue count", adapter.pendingCount() === 0),
assertion("forbidden attributes absent", "default-deny projection", redacted),
assertion("product flow unaffected", "adapter flush resolves despite the sink failure", verdict(flushResolved)),
assertion("delivery self-check", "sink failure counted", verdict(adapter.droppedCount() === 1)),
assertion("queue drained within bound", "pending queue count", verdict(adapter.pendingCount() === 0)),
assertion("forbidden attributes absent", "default-deny projection", verdict(redacted)),
],
negativeFixtureFailedAsExpected: redacted,
negativeFixtureFailedAsExpected: verdict(redacted),
providerVerificationRequired: true,
};
}
async function drillRollback(): Promise<DrillResult> {
const verified = await verifyRollbackReleaseCoherence();
const { release, coherence: coherent } = verified;
async function drillRollback(context: DrillContext): Promise<DrillResult> {
const { release, coherence: coherent } = await verifyRollbackReleaseCoherence({
readArtifact: rootedReader(context.root),
contractPackages: context.contractPackages,
});
const assetsPresent = await builtAssetsPresent(context.root);
const mixed = verifyCompatibilityTuple({
frontend: {
buildId: "build-a",
@@ -268,20 +337,25 @@ async function drillRollback(): Promise<DrillResult> {
},
});
return {
triggerAsserted: true,
containmentAsserted: coherent.compatible,
// A release-blocking defect is declared by a person during an incident.
triggerAsserted: "UNVERIFIED",
containmentAsserted: verdict(coherent.compatible && assetsPresent),
recoveryAssertions: [
assertion("compatibility gate", "typed version comparison", coherent.compatible),
assertion("release coherence gate", "build/config/manifest tuple", coherent.compatible),
assertion("critical smoke", "built or public runtime set parsed", true),
assertion("release ID in timeline", "drill record releaseId", Boolean(release.releaseId)),
assertion("compatibility gate", "typed version comparison", verdict(coherent.compatible)),
assertion(
"release coherence gate",
"build/config/manifest tuple and every Vite manifest file in the local dist",
verdict(coherent.compatible && assetsPresent),
),
notObserved("critical smoke", "a browser smoke after the provider switches to the prior release"),
assertion("release ID in timeline", "drill record releaseId", verdict(Boolean(release.releaseId))),
],
negativeFixtureFailedAsExpected: !mixed.compatible,
negativeFixtureFailedAsExpected: verdict(!mixed.compatible),
providerVerificationRequired: true,
};
}
const drillById: Record<string, () => Promise<DrillResult>> = {
const drillById: Record<string, (context: DrillContext) => Promise<DrillResult>> = {
"FE-RB-001": drillBoot,
"FE-RB-002": drillChunkMismatch,
"FE-RB-003": drillApiDegradation,
@@ -294,12 +368,12 @@ export async function verifyRollbackReleaseCoherence(
) {
const readArtifact = options.readArtifact ?? readJsonArtifact;
const paths = options.paths ?? DEFAULT_ROLLBACK_PATHS;
const artifactPair = await selectRollbackArtifactPair(
readArtifact,
paths,
);
const release = parseReleaseArtifact(artifactPair.release);
const runtimeArtifact = parseRuntimeConfigArtifact(artifactPair.runtime);
const [releaseValue, runtimeValue] = await Promise.all([
readArtifact(paths.release),
readArtifact(paths.runtime),
]);
const release = parseReleaseArtifact(releaseValue);
const runtimeArtifact = parseRuntimeConfigArtifact(runtimeValue);
const runtime = {
...runtimeArtifact,
BUILD_ID: requireIdentity(runtimeArtifact.BUILD_ID, "runtime BUILD_ID"),
@@ -317,43 +391,64 @@ export async function verifyRollbackReleaseCoherence(
return Object.freeze({ release, runtime, coherence });
}
export async function runRunbookDrill(runbookId: string, options: DrillOptions = {}) {
const context: DrillContext = {
root: options.releaseRoot ?? process.cwd(),
contractPackages: options.contractPackages ?? EXPECTED_CONTRACT_SET_PACKAGES,
};
const document = JSON.parse(
await readFile("config/runbooks/runbooks.json", "utf8"),
) as RunbookDocument;
const specification = document.runbooks[runbookId];
const drill = drillById[runbookId];
if (!specification || !drill) throw new RangeError(`unknown runbook: ${runbookId}`);
const release = parseReleaseArtifact(
await rootedReader(context.root)(DEFAULT_ROLLBACK_PATHS.release),
);
const result = await drill(context);
const escalationPathAsserted = verdict(specification.escalation.length >= 2);
return {
schemaVersion: 2 as const,
runbookId,
gateId: specification.gateId,
releaseId: release.releaseId,
drillTimestamp: new Date().toISOString(),
triggerInjected: specification.triggerKinds[0] ?? "",
triggerAsserted: result.triggerAsserted,
containmentAsserted: result.containmentAsserted,
escalationPathAsserted,
recoveryAssertions: result.recoveryAssertions,
negativeFixtureFailedAsExpected: result.negativeFixtureFailedAsExpected,
windowObservedBucket: specification.window,
providerVerificationRequired: result.providerVerificationRequired,
result: combineDrillVerdicts(
[
result.triggerAsserted,
result.containmentAsserted,
escalationPathAsserted,
...result.recoveryAssertions.map((item) => item.result),
result.negativeFixtureFailedAsExpected,
],
result.providerVerificationRequired,
),
};
}
async function main(): Promise<void> {
const runbookId = process.argv
.slice(2)
.find((argument) => /^FE-RB-00[1-5]$/.test(argument));
const document = JSON.parse(
await readFile("config/runbooks/runbooks.json", "utf8"),
) as RunbookDocument;
const specification = runbookId ? document.runbooks[runbookId] : undefined;
if (!runbookId || !specification) {
process.stderr.write("Usage: drill:runbook -- FE-RB-001..FE-RB-005\n");
const releaseRootFlag = process.argv.indexOf("--release-root");
const releaseRoot = releaseRootFlag >= 0 ? process.argv[releaseRootFlag + 1] : undefined;
if (!runbookId || (releaseRootFlag >= 0 && !releaseRoot)) {
process.stderr.write(
"Usage: drill:runbook -- FE-RB-001..FE-RB-005 [--release-root <extracted release archive>]\n",
);
process.exit(2);
}
const drill = await drillById[runbookId]();
const escalationPathAsserted = specification.escalation.length >= 2;
const passed =
drill.triggerAsserted &&
drill.containmentAsserted &&
escalationPathAsserted &&
drill.recoveryAssertions.every((item) => item.passed) &&
drill.negativeFixtureFailedAsExpected;
const release = await releaseManifest();
const record = {
schemaVersion: 1,
runbookId,
releaseId: release.releaseId,
drillTimestamp: new Date().toISOString(),
triggerInjected: specification.triggerKinds[0],
triggerAsserted: drill.triggerAsserted,
containmentAsserted: drill.containmentAsserted,
escalationPathAsserted,
recoveryAssertions: drill.recoveryAssertions,
negativeFixtureFailedAsExpected: drill.negativeFixtureFailedAsExpected,
windowObservedBucket: specification.window,
providerVerificationRequired: drill.providerVerificationRequired,
passed,
};
const { gateId, ...record } = await runRunbookDrill(runbookId, releaseRoot ? { releaseRoot } : {});
const artifactDirectory = `artifacts/runbooks/${runbookId}`;
await mkdir(artifactDirectory, { recursive: true });
await writeValidatedJsonArtifact({
@@ -361,15 +456,25 @@ async function main(): Promise<void> {
schema: runbookRecordArtifactSchema,
value: record,
});
if (!passed) {
process.stderr.write(`${runbookId} drill failed.\n`);
if (record.result === "FAIL") {
process.stderr.write(`${runbookId} drill: FAIL (${gateId})\n`);
process.exit(1);
}
process.stdout.write(
`${runbookId} drill: PASS (${specification.gateId}; provider verification ${
drill.providerVerificationRequired ? "still required" : "not required"
})\n`,
);
if (record.result === "UNVERIFIED") {
// Not a pass: the gate stays red until provider evidence exists (D-14).
const open = [
["trigger", record.triggerAsserted],
["containment", record.containmentAsserted],
...record.recoveryAssertions.map((item) => [item.assertion, item.result] as const),
["negative fixture", record.negativeFixtureFailedAsExpected],
["provider verification", record.providerVerificationRequired ? "UNVERIFIED" : "PASS"],
].filter(([, result]) => result === "UNVERIFIED").map(([name]) => name);
process.stderr.write(
`${runbookId} drill: UNVERIFIED (${gateId}; no local check failed; not observed locally: ${open.join(", ")})\n`,
);
process.exit(3);
}
process.stdout.write(`${runbookId} drill: PASS (${gateId})\n`);
}
function requireIdentity(value: string | undefined, label: string): string {
@@ -379,88 +484,6 @@ function requireIdentity(value: string | undefined, label: string): string {
return value;
}
async function selectRollbackArtifactPair(
readArtifact: JsonArtifactReader,
paths: RollbackArtifactPaths,
): Promise<Readonly<{ release: unknown; runtime: unknown }>> {
const primary = await readArtifactPair(
readArtifact,
paths.primaryRelease,
paths.primaryRuntime,
);
if (
primary.release.status === "fulfilled" &&
primary.runtime.status === "fulfilled"
) {
return Object.freeze({
release: primary.release.value,
runtime: primary.runtime.value,
});
}
const releaseMissing =
primary.release.status === "rejected" &&
hasErrorCode(primary.release.reason, "ENOENT");
const runtimeMissing =
primary.runtime.status === "rejected" &&
hasErrorCode(primary.runtime.reason, "ENOENT");
if (releaseMissing && runtimeMissing) {
const fallback = await readArtifactPair(
readArtifact,
paths.fallbackRelease,
paths.fallbackRuntime,
);
if (fallback.release.status === "rejected") {
throw fallback.release.reason;
}
if (fallback.runtime.status === "rejected") {
throw fallback.runtime.reason;
}
return Object.freeze({
release: fallback.release.value,
runtime: fallback.runtime.value,
});
}
if (primary.release.status === "rejected" && !releaseMissing) {
throw primary.release.reason;
}
if (primary.runtime.status === "rejected" && !runtimeMissing) {
throw primary.runtime.reason;
}
throw new Error("primary rollback artifact pair is incomplete");
}
async function readArtifactPair(
readArtifact: JsonArtifactReader,
releasePath: string,
runtimePath: string,
): Promise<
Readonly<{
release: PromiseSettledResult<unknown>;
runtime: PromiseSettledResult<unknown>;
}>
> {
const [release, runtime] = await Promise.allSettled([
Promise.resolve().then(() => readArtifact(releasePath)),
Promise.resolve().then(() => readArtifact(runtimePath)),
]);
return Object.freeze({ release, runtime });
}
async function readPrimaryOrFallback(
readArtifact: JsonArtifactReader,
primary: string,
fallback: string,
): Promise<unknown> {
try {
return await readArtifact(primary);
} catch (error) {
if (!hasErrorCode(error, "ENOENT")) throw error;
return readArtifact(fallback);
}
}
function hasErrorCode(error: unknown, code: string): boolean {
return Boolean(
error &&
+2 -2
View File
@@ -29,7 +29,7 @@ const OUTPUT_PATH = "dist/config.json";
* Deployment-supplied values. Everything else is fixed by the profile so a
* deployment cannot quietly widen what was reviewed.
*/
const OVERRIDES = Object.freeze({
export const RUNTIME_OVERRIDES = Object.freeze({
API_BASE_URL: "RUNTIME_API_BASE_URL",
TELEMETRY_ENDPOINT: "RUNTIME_TELEMETRY_ENDPOINT",
} as const);
@@ -49,7 +49,7 @@ export async function generateRuntimeConfig(
`${profilePath}: declares APP_ENV ${String(draft["APP_ENV"])}, expected ${target}`,
);
}
for (const [field, variable] of Object.entries(OVERRIDES)) {
for (const [field, variable] of Object.entries(RUNTIME_OVERRIDES)) {
const supplied = environment[variable];
if (supplied !== undefined && supplied !== "") draft[field] = supplied;
}
@@ -0,0 +1,17 @@
/**
* 12-11. One violation line names the rule, the edge and the import specifier
* as written, then the rule's `comment` from .dependency-cruiser.json: why the
* edge is forbidden and where the code should go instead.
*/
export function formatArchitectureViolation(
violation: Readonly<{ rule: string; source: string; target: string; cycle?: readonly string[] }>,
specifiers: readonly string[],
comment: string | undefined,
): string {
const imports = specifiers.length > 0
? ` (import ${specifiers.map((specifier) => JSON.stringify(specifier)).join(", ")})`
: "";
const cycle = violation.cycle ? ` (cycle group: ${violation.cycle.join(", ")})` : "";
const why = comment ? ` why: ${comment}\n` : "";
return `Architecture violation [${violation.rule}]: ${violation.source} -> ${violation.target}${imports}${cycle}\n${why}`;
}
+18
View File
@@ -0,0 +1,18 @@
import { chmod, readdir, stat } from "node:fs/promises";
import path from "node:path";
/**
* 13-02. dist is published as-is to a web server that may run as another OS
* user, so every file in it must be readable by others. The validated JSON
* writer creates files 0600 on purpose (evidence under artifacts/ stays
* private); the build adds read bits to what it publishes instead of loosening
* that writer.
*/
export async function makeDistFilesPublic(directory: string): Promise<void> {
for (const entry of await readdir(directory, { recursive: true, withFileTypes: true })) {
if (!entry.isFile()) continue;
const file = path.join(entry.parentPath, entry.name);
const { mode } = await stat(file);
if ((mode & 0o004) === 0) await chmod(file, (mode & 0o7777) | 0o444);
}
}
+31 -1
View File
@@ -9,6 +9,7 @@ import {
import {
PROMOTION_VERIFIER_ID,
PROMOTION_VERIFIER_VERSION,
PROVIDER_FUTURE_SKEW_MS,
assertDistinctProviderTrust,
evaluatePromotionEvidence,
providerVerificationArtifactSchema,
@@ -35,6 +36,29 @@ export type ExactPromotionExpectedContext = Readonly<{
lockfileSha256?: string;
}>;
/**
* 13-04. `current` checks provider evidence against the clock, as a new
* promotion must. `archived` re-verifies a release promoted earlier (deploying
* it later, or rolling back to it): signatures, digests and members are checked
* the same way, but freshness is judged at the promotion's recorded
* `verifiedAt`, which may not lie in the future. Promotion itself
* (promotion-stager.ts) never passes `archived`.
*/
export type PromotionFreshness = "current" | "archived";
export function promotionEvidenceTime(
freshness: PromotionFreshness,
verifiedAt: string,
now: number,
): number {
if (freshness === "current") return now;
const verified = Date.parse(verifiedAt);
if (!Number.isFinite(verified) || verified > now + PROVIDER_FUTURE_SKEW_MS) {
throw new Error("archived promotion verifiedAt is in the future or invalid");
}
return verified;
}
export async function verifyExactPromotionBundle(
files: ExactPromotionBundle,
options: Readonly<{
@@ -42,6 +66,7 @@ export async function verifyExactPromotionBundle(
provenanceTrust: ProviderTrust;
expected: ExactPromotionExpectedContext;
nowEpochMs?: () => number;
freshness?: PromotionFreshness;
}>,
): Promise<Readonly<{ status: "PASS" }>> {
assertDistinctProviderTrust(options);
@@ -286,7 +311,12 @@ export async function verifyExactPromotionBundle(
provenanceAttestation: provenance,
vulnerabilityTrust: options.vulnerabilityTrust,
provenanceTrust: options.provenanceTrust,
nowEpochMs: options.nowEpochMs,
nowEpochMs: () =>
promotionEvidenceTime(
options.freshness ?? "current",
promotion.verifiedAt,
(options.nowEpochMs ?? Date.now)(),
),
});
if (
reevaluated.status !== "PASS" ||
+27
View File
@@ -1,6 +1,33 @@
import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts";
const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/;
export type HostingMode = "live" | "invalid-live" | "fixture";
export type HostingVerdict = "PASS" | "FAIL" | "UNVERIFIED";
/**
* 13-05 (D-14). The fixture compares the declared headers with a copy of
* themselves, so it can only find a contradiction, never prove hosting. Only a
* live probe of the deployed release can PASS.
*/
export function hostingVerdict(mode: HostingMode, passed: boolean): HostingVerdict {
if (!passed) return "FAIL";
return mode === "live" ? "PASS" : "UNVERIFIED";
}
/**
* 13-05. The live probe requests the entry script the served index.html names,
* so it checks the release that is deployed rather than the first asset of a
* local build, which the deployed release may not contain.
*/
export function servedEntryScript(indexHtml: string): string | null {
for (const tag of indexHtml.match(/<script\b[^>]*>/gu) ?? []) {
if (!/\btype=["']module["']/u.test(tag)) continue;
const source = /\bsrc=["']([^"']+\.js)["']/u.exec(tag)?.[1];
if (source) return source;
}
return null;
}
const PUBLIC_SERVICE_WORKER = /(?:^|\/)(?:service-worker|sw)(?:[.-][^/]*)?\.js$/i;
/**
+46 -3
View File
@@ -15,8 +15,20 @@ const REVIEW_FIELDS = Object.freeze([
"Screen reader",
]);
export function validateManualA11yEvidence(content: string) {
const fields = Object.fromEntries(
const IDENTITY_FIELDS = Object.freeze([
"Status",
"Route ID",
"Release ID",
"Reviewer",
"Reviewed at",
"Signature",
"Attestation",
]);
const NOT_APPLICABLE = /^not-applicable \(.+\)$/;
function parseRecordFields(content: string): Record<string, string> {
return Object.fromEntries(
content
.split(/\r?\n/)
.map((line) => /^([^:]+):\s*(.*)$/.exec(line))
@@ -26,6 +38,37 @@ export function validateManualA11yEvidence(content: string) {
match[2].trim(),
]),
);
}
/**
* 08-06. The merge-stage check: the record for `routeId` keeps the template's
* fields and vocabulary, whether or not a human has reviewed it yet. A record
* that claims `reviewed` must also be complete. Returns the offending fields.
*/
export function validateManualA11yRecordFormat(content: string, routeId: string): string[] {
const fields = parseRecordFields(content);
const failures = [...IDENTITY_FIELDS, ...REVIEW_FIELDS].filter(
(field) => !(field in fields),
);
if (fields.Status !== undefined && !["pending-manual-review", "reviewed"].includes(fields.Status)) {
failures.push("Status");
}
if (fields["Route ID"] !== undefined && fields["Route ID"] !== routeId) failures.push("Route ID");
if (fields.Attestation !== undefined && !["pending", "accepted"].includes(fields.Attestation)) {
failures.push("Attestation");
}
for (const field of REVIEW_FIELDS) {
const verdict = fields[field];
if (verdict !== undefined && verdict !== "pass" && verdict !== "pending" && !NOT_APPLICABLE.test(verdict)) {
failures.push(field);
}
}
if (fields.Status === "reviewed") failures.push(...validateManualA11yEvidence(content).failures);
return [...new Set(failures)];
}
export function validateManualA11yEvidence(content: string) {
const fields = parseRecordFields(content);
const failures: string[] = [];
if (fields.Status !== "reviewed") failures.push("Status");
if (!fields["Route ID"]) failures.push("Route ID");
@@ -44,7 +87,7 @@ export function validateManualA11yEvidence(content: string) {
const result = fields[field];
if (
result !== "pass" &&
!/^not-applicable \(.+\)$/.test(result ?? "")
!NOT_APPLICABLE.test(result ?? "")
) {
failures.push(field);
}
+15
View File
@@ -1,3 +1,18 @@
/**
* Package-script graph for the CI contract (D-12, 12-10). Kept after checking
* whether `--ignore-scripts` on the workflow install and `allowBuilds` in
* pnpm-workspace.yaml already close the same risks. They do not:
*
* - Gate commands run installs themselves (`verify:lockfile`, removal
* fixtures). `allowBuilds` limits dependency build scripts under pnpm only;
* the root project's own install hooks and npm/yarn installs still run
* unless the command says `--ignore-scripts`.
* - A gate names a root package script. `--prefix`, `--filter`, `-C`, npm
* pre/post hooks and `npm_config_*` scope variables can make that name run a
* different manifest's script, which no install flag affects.
* - `reachablePackageScripts` is also how the ungated-test check (12-04) finds
* which Vitest paths a gate runs.
*/
type PackageManager = "pnpm" | "npm" | "yarn";
type ManagerParseResult = Readonly<{
+7 -2
View File
@@ -18,14 +18,19 @@ export const PROMOTION_FORMULA = Object.freeze({
"FE-GATE-012",
"FE-GATE-014",
"FE-GATE-015",
"FE-GATE-019",
"FE-GATE-026",
// FE-GATE-027. A candidate is only release-ready once it has been admitted
// to a named environment; coherence alone never proved it belonged there.
"FE-GATE-027",
// FE-GATE-028 (08-06). The signed human accessibility review belongs to a
// release candidate, so it gates release; merge checks the record format.
"FE-GATE-028",
]),
PROD_PROMOTION_READY: Object.freeze([
"FE-GATE-016",
// FE-GATE-019 (13-05, D-14). Live hosting headers of the deployed promoted
// release; the declared-header fixture alone is UNVERIFIED, not PASS.
"FE-GATE-019",
// FE-GATE-016 is retired (D-14): it repeated FE-GATE-025's FE-RB-005 drill.
"FE-GATE-021",
"FE-GATE-022",
"FE-GATE-023",
+4 -12
View File
@@ -1,10 +1,12 @@
import { readFile, readdir } from "node:fs/promises";
import path from "node:path";
// Importing the realtime or Web Push adapter from the composition root is the
// graph rule unselected-realtime-runtime-is-not-composed (12-10). This scan
// keeps what an import graph cannot see: native API calls and timers.
export type RealtimeBoundaryRuleId =
| "NATIVE_REALTIME_API_OUTSIDE_ADAPTER"
| "PRESENTATION_INTERVAL_OWNER"
| "UNSELECTED_REALTIME_RUNTIME_COMPOSED";
| "PRESENTATION_INTERVAL_OWNER";
export type RealtimeBoundaryViolation = Readonly<{
ruleId: RealtimeBoundaryRuleId;
@@ -17,8 +19,6 @@ const OWNED_NATIVE_ROOTS = [
"src/adapters/realtime/",
"src/adapters/web-push/",
] as const;
const REALTIME_ADAPTER_IMPORT =
/(?:from\s*|import\s*\()\s*["'][^"']*\/adapters\/(?:realtime|web-push)(?:\/[^"']*)?["']/gu;
const NATIVE_REALTIME_PATTERNS = [
/\bnew\s+(?:WebSocket|EventSource|Notification)\s*\(/gu,
/\bNotification\s*\.\s*requestPermission\s*\(/gu,
@@ -62,9 +62,6 @@ function inspectFile(
const presentationOwned =
logicalFile.startsWith("src/presentation/") ||
/^src\/features\/[^/]+\/presentation\//u.test(logicalFile);
const compositionBoundary =
logicalFile.startsWith("src/bootstrap/") ||
/^src\/features\/installed-feature-/u.test(logicalFile);
const report = (
ruleId: RealtimeBoundaryRuleId,
@@ -92,11 +89,6 @@ function inspectFile(
report("PRESENTATION_INTERVAL_OWNER", match.index);
}
}
if (compositionBoundary) {
for (const match of source.matchAll(REALTIME_ADAPTER_IMPORT)) {
report("UNSELECTED_REALTIME_RUNTIME_COMPOSED", match.index);
}
}
}
async function collectSourceFiles(
+16 -9
View File
@@ -3,12 +3,14 @@ import path from "node:path";
import { z } from "zod";
import { SCALE_TIERS, type ScaleTier } from "../scale/run-scale-profile.ts";
import { reachablePackageScripts } from "./package-script-graph.ts";
/**
* 12-04. A test file protects nothing unless a CI gate runs it. The gated set
* is read from the package scripts the CI contract's commands reach: Vitest
* path filters (`run-vitest.ts run <paths>`) and Playwright config `testDir`s.
* path filters (`run-vitest.ts run <paths>`), the Vitest steps of a scale tier
* (`run-scale-profile.ts <tier>`) and Playwright config `testDir`s.
* A test outside that set needs a reasoned entry in config/ci/ungated-tests.json.
*/
export const UNGATED_TESTS_PATH = "config/ci/ungated-tests.json";
@@ -53,17 +55,22 @@ export function gatedTestPaths(
readConfig: (file: string) => string,
): string[] {
const paths = new Set<string>();
const addVitestPaths = (tokens: readonly string[]) => {
const vitestRun = tokens.findIndex(
(token, index) => token === "run" && /(?:run-vitest\.ts|vitest)$/u.test(tokens[index - 1] ?? ""),
);
if (vitestRun < 0) return;
for (const token of tokens.slice(vitestRun + 1)) {
if (!token.startsWith("-")) paths.add(token.replace(/\/$/u, ""));
}
};
for (const script of reachablePackageScripts(scripts, entryScripts)) {
for (const segment of scripts[script]!.split("&&")) {
const tokens = segment.trim().split(/\s+/u);
const vitestRun = tokens.findIndex(
(token, index) => token === "run" && /(?:run-vitest\.ts|vitest)$/u.test(tokens[index - 1] ?? ""),
);
if (vitestRun >= 0) {
for (const token of tokens.slice(vitestRun + 1)) {
if (token.startsWith("-")) break;
paths.add(token.replace(/\/$/u, ""));
}
addVitestPaths(tokens);
const scaleProfile = tokens.findIndex((token) => /run-scale-profile\.ts$/u.test(token));
if (scaleProfile >= 0) {
for (const step of SCALE_TIERS[tokens[scaleProfile + 1] as ScaleTier] ?? []) addVitestPaths(step.command);
}
const playwrightTest = tokens.findIndex(
(token, index) => token === "test" && tokens[index - 1] === "playwright",
+49 -1
View File
@@ -1,3 +1,4 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import type { Plugin } from "vite";
@@ -39,6 +40,7 @@ export function viteModuleInventoryPlugin(
{
schemaVersion: 1,
chunks,
packages: bundledPackages(chunks),
},
null,
2,
@@ -48,7 +50,41 @@ export function viteModuleInventoryPlugin(
};
}
function normalizeModuleId(
/**
* 13-12. The `name@version` of every package with at least one module in the
* emitted bundle: what the public release actually ships, as opposed to the
* SBOM, which lists the whole installed graph.
*/
export function bundledPackages(chunks: readonly ModuleInventoryChunk[]): string[] {
const packages = new Set<string>();
for (const chunk of chunks) {
for (const module of chunk.modules) {
const match = /^npm:((?:@[^/]+\/)?[^/@]+@[^/]+)\//u.exec(module);
if (match?.[1]) packages.add(match[1]);
}
}
return [...packages].sort();
}
const packageManifests = new Map<string, Readonly<{ name: string; version: string }>>();
function installedPackage(directory: string): Readonly<{ name: string; version: string }> {
let manifest = packageManifests.get(directory);
if (!manifest) {
const parsed = JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")) as {
name?: unknown;
version?: unknown;
};
if (typeof parsed.name !== "string" || typeof parsed.version !== "string") {
throw new TypeError(`bundled package has no name/version: ${directory}`);
}
manifest = Object.freeze({ name: parsed.name, version: parsed.version });
packageManifests.set(directory, manifest);
}
return manifest;
}
export function normalizeModuleId(
moduleId: string,
repositoryRoot: string,
): string {
@@ -56,6 +92,18 @@ function normalizeModuleId(
if (!path.isAbsolute(withoutQuery)) {
return withoutQuery.replaceAll("\\", "/");
}
// 13-12: a dependency module keeps its package identity, read from the
// package.json of the directory it was resolved into.
const file = withoutQuery.replaceAll("\\", "/");
const marker = "/node_modules/";
const at = file.lastIndexOf(marker);
if (at >= 0) {
const segments = file.slice(at + marker.length).split("/");
const nameLength = segments[0]?.startsWith("@") ? 2 : 1;
const directory = file.slice(0, at + marker.length) + segments.slice(0, nameLength).join("/");
const { name, version } = installedPackage(directory);
return `npm:${name}@${version}/${segments.slice(nameLength).join("/")}`;
}
const relative = path.relative(repositoryRoot, withoutQuery);
return relative.startsWith("..")
? `external:${path.basename(withoutQuery)}`
+15 -10
View File
@@ -3,14 +3,21 @@ import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
/**
* Spec §47. CI execution tiers for the scale/chaos/soak program.
* Spec §47. Execution tiers for the scale/chaos/soak program.
*
* pr S0/S1 architecture, composition and traffic invariants
* main pr + S2 composition, TypeScript diagnostics and the stored
* baseline regression gate (config/scale/benchmark-baseline.json)
* pr architecture and traffic invariants, S0-S2 composition growth
* main pr + TypeScript diagnostics and the stored baseline regression
* gate (config/scale/benchmark-baseline.json)
* nightly main + S3/S4 topology, telemetry storm, session cycles, browser soak
* release release-coherence matrix + the stable main/nightly subset
*
* Only `pr` runs in CI (merge gate FE-GATE-005, 11-03). Its checks are counts,
* bounds and growth shape, so they hold on any CPU; the composition timings it
* writes are advisory. `main`, `nightly` and `release` include
* `baseline-regression`, which compares timings only on the CPU model that
* recorded config/scale/benchmark-baseline.json and is `incomplete` elsewhere,
* so no CI job runs them; they are local commands for that machine.
*
* Every step's output goes to artifacts/scale/<tier>/<step>.log and the tier
* writes one machine-readable summary.json. A step that could not run (e.g. a
* browser soak without a build or browser) is `skipped`, and a tier with any
@@ -49,18 +56,16 @@ const PR_STEPS: readonly Step[] = [
"tests/scale/traffic",
],
},
// 11-03: S2 is included because below it every workload stays under the
// noise floor, so a quadratic accumulation passed S0/S1 unnoticed.
{
id: "composition-s0-s1",
command: ["scripts/scale/run-composition-scale.ts", "--profiles=S0,S1"],
id: "composition-s0-s2",
command: ["scripts/scale/run-composition-scale.ts", "--profiles=S0,S1,S2"],
},
];
const MAIN_STEPS: readonly Step[] = [
...PR_STEPS,
{
id: "composition-s0-s2",
command: ["scripts/scale/run-composition-scale.ts", "--profiles=S0,S1,S2"],
},
{
id: "composition-scale-suite",
command: [...VITEST, "tests/scale/composition-scale.test.ts", "tests/scale/tsc-diagnostics-parser.test.ts"],
+22
View File
@@ -4,6 +4,7 @@ import { manualA11yReportArtifactSchema } from "./contracts/release-artifacts.ts
import {
MANUAL_A11Y_ROUTE_IDS,
validateManualA11yEvidence,
validateManualA11yRecordFormat,
} from "./lib/manual-a11y-evidence.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
@@ -17,6 +18,27 @@ type ManualA11yResult = Readonly<{
passed: boolean;
}>;
// 08-06: the signed review is a release-stage gate (FE-GATE-028). The merge
// stage (FE-GATE-009) runs `--format-only`: every route has a record in the
// template's shape, reviewed or not.
if (process.argv.includes("--format-only")) {
const failures: string[] = [];
for (const routeId of MANUAL_A11Y_ROUTE_IDS) {
const path = `artifacts/tests/a11y-manual/${routeId}.md`;
const record = await readFile(path, "utf8").catch(() => null);
const invalid = record === null ? ["missing record"] : validateManualA11yRecordFormat(record, routeId);
if (invalid.length > 0) failures.push(`${path}: ${invalid.join(", ")}`);
}
if (failures.length > 0) {
process.stderr.write(`Manual accessibility record format is invalid:\n${failures.join("\n")}\n`);
process.exit(1);
}
process.stdout.write(
`Manual accessibility record format: PASS (${MANUAL_A11Y_ROUTE_IDS.length} routes; signed review runs in FE-GATE-028)\n`,
);
process.exit(0);
}
const results: ManualA11yResult[] = [];
for (const routeId of MANUAL_A11Y_ROUTE_IDS) {
const path = `artifacts/tests/a11y-manual/${routeId}.md`;
+21
View File
@@ -2,6 +2,7 @@ import { access, mkdir, readFile } from "node:fs/promises";
import { ROUTE_REGISTRY } from "../src/features/installed-feature-contracts.ts";
import { documentationReviewArtifactSchema } from "./contracts/release-artifacts.ts";
import { RUNTIME_OVERRIDES } from "./generate-runtime-config.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
/**
@@ -96,9 +97,25 @@ for (const path of ROUTE_SCOPE_DOCUMENTS) {
}
const routeScopeDocumented = routeScope.every((entry) => entry.documented);
// 13-15. README is where a project learns how to build for production. It
// named none of the variables the build and admission read, so each one is
// required here, taken from the code that reads it where possible.
const RUNTIME_VARIABLES = Object.freeze([
"APP_PROFILE",
"RELEASE_TARGET",
"VITE_BUILD_ID",
"RELEASE_ID",
...Object.values(RUNTIME_OVERRIDES),
]);
const readme = await readFile("README.md", "utf8").catch(() => "");
const missingRuntimeVariables = RUNTIME_VARIABLES.filter(
(variable) => !readme.includes(`\`${variable}\``),
);
const passed =
reportDigestValid &&
routeScopeDocumented &&
missingRuntimeVariables.length === 0 &&
results.length === 2 &&
results.every((result) => result.passed);
await mkdir("artifacts/quality", { recursive: true });
@@ -115,11 +132,15 @@ await writeValidatedJsonArtifact({
reportDigestValid,
routeScope,
routeScopeDocumented,
missingRuntimeVariables,
results,
passed,
},
});
if (!passed) {
if (missingRuntimeVariables.length > 0) {
process.stderr.write(`README.md does not name: ${missingRuntimeVariables.join(", ")}\n`);
}
process.stderr.write(
"Documentation readiness: FAIL_UNVERIFIED (canonical scoped-review evidence is incomplete)\n",
);
+5 -1
View File
@@ -55,9 +55,13 @@ const files = Object.fromEntries(
] as const),
),
);
// 13-04: `--archived` re-verifies a release promoted earlier (deploy later or
// roll back to it); freshness is judged at its recorded promotion time.
const freshness = process.argv.includes("--archived") ? "archived" : "current";
await verifyExactPromotionBundle(files, {
vulnerabilityTrust,
provenanceTrust,
freshness,
expected: {
run: {
id: required("EXPECTED_PROMOTION_RUN_ID"),
@@ -71,7 +75,7 @@ await verifyExactPromotionBundle(files, {
...optionalDigest("lockfileSha256", "EXPECTED_PROMOTION_LOCKFILE_SHA256"),
},
});
process.stdout.write("Exact promotion bundle verification: PASS\n");
process.stdout.write(`Exact promotion bundle verification (${freshness}): PASS\n`);
function asciiCompare(left: string, right: string): number {
return left < right ? -1 : left > right ? 1 : 0;
+34 -17
View File
@@ -5,12 +5,14 @@ import { hostingHeadersArtifactSchema } from "./contracts/release-artifacts.ts";
import {
checkPublicServiceWorkers,
classifyLiveHostingBaseUrl,
hostingVerdict,
servedEntryScript,
type HostingMode,
} from "./lib/hosting-probe.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type Document = Record<string, unknown>;
type ResponseHeaders = Record<string, Record<string, string>>;
type HostingMode = "live" | "invalid-live" | "fixture";
type ProbeResult = Readonly<{
surface: string;
header: string;
@@ -74,16 +76,9 @@ const probeResults: ProbeResult[] = [];
if (liveTarget?.passed) {
mode = "live";
const assets = await readdir("dist/assets");
const hashedJavaScript = assets.find((file) => file.endsWith(".js"));
if (!hashedJavaScript) throw new Error("No built hashed JavaScript found.");
const paths = {
index: "/",
runtimeConfig: "/config.json",
releaseManifest: "/release-manifest.json",
hashedAsset: `/assets/${hashedJavaScript}`,
};
for (const [surface, pathname] of Object.entries(paths)) {
// 13-05: FE-GATE-019 runs after the promoted release is deployed, and the
// hashed asset it probes is the entry script that release's index.html names.
const probe = async (surface: string, pathname: string): Promise<string | null> => {
const requestedUrl = new URL(pathname, liveTarget.url);
try {
const response = await fetch(requestedUrl, { redirect: "follow" });
@@ -110,6 +105,7 @@ if (liveTarget?.passed) {
value,
]),
);
return await response.text();
} catch (error: unknown) {
probeResults.push({
surface,
@@ -118,7 +114,23 @@ if (liveTarget?.passed) {
observed: error instanceof Error ? error.name : "UnknownError",
passed: false,
});
return null;
}
};
const indexHtml = await probe("index", "/");
await probe("runtimeConfig", "/config.json");
await probe("releaseManifest", "/release-manifest.json");
const entryScript = indexHtml === null ? null : servedEntryScript(indexHtml);
if (entryScript) {
await probe("hashedAsset", entryScript);
} else {
probeResults.push({
surface: "hashedAsset",
header: "entry-script",
expected: "a module script named by the served index.html",
observed: null,
passed: false,
});
}
} else if (liveTarget) {
mode = "invalid-live";
@@ -193,6 +205,7 @@ results.push(
);
const passed = results.every((result) => result.passed);
const status = hostingVerdict(mode, passed);
await mkdir("artifacts/release", { recursive: true });
await writeValidatedJsonArtifact({
path: "artifacts/release/hosting-headers.json",
@@ -205,17 +218,21 @@ await writeValidatedJsonArtifact({
providerVerificationRequired: mode !== "live",
results,
passed,
status,
},
});
if (!passed) {
if (status === "FAIL") {
process.stderr.write(
"Hosting cache/content-type/security header verification failed.\n",
);
process.exit(1);
}
process.stdout.write(
`Hosting header contract: PASS (${mode}; live verification ${
mode === "live" ? "complete" : "required before promotion"
})\n`,
);
if (status === "UNVERIFIED") {
// Not a pass (D-14): set HOSTING_BASE_URL to the deployed release.
process.stderr.write(
"Hosting header contract: UNVERIFIED (fixture: declared headers are consistent; set HOSTING_BASE_URL to probe the deployed release)\n",
);
process.exit(3);
}
process.stdout.write("Hosting header contract: PASS (live)\n");
+84
View File
@@ -0,0 +1,84 @@
import { readFileSync } from "node:fs";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
// 13-08. The Content-Security-Policy in config/hosting/security-headers.json was
// declared but never applied in a browser: `vite preview` sends no security
// headers. This smoke serves the build with the production headers attached
// and fails on any securitypolicyviolation event or console error.
const { headers: declaredHeaders } = JSON.parse(
readFileSync("config/hosting/security-headers.json", "utf8"),
) as { headers: Record<string, string> };
// The preview server is plain HTTP on loopback. `upgrade-insecure-requests` is a
// no-op for an HTTPS origin, but WebKit applies it to loopback and rewrites
// every same-origin request to https, which this server cannot answer. Every
// other directive is served exactly as declared.
const securityHeaders = {
...declaredHeaders,
"Content-Security-Policy": declaredHeaders["Content-Security-Policy"]!
.split(";")
.map((directive) => directive.trim())
.filter((directive) => directive !== "upgrade-insecure-requests")
.join("; "),
};
/**
* Known violation, not accepted behavior. Zod probes `Function("")` when it
* builds its first object schema, to decide whether it may compile parsers.
* The policy has no 'unsafe-eval', so the probe is refused (zod catches it and
* parses without compiling) and reported on every boot of the default build.
* `z.config({ jitless: true })` removes the probe, but it must run before the
* first schema is built, and the bundler evaluates the shared chunks that
* build schemas before the entry module body. Until the app does that, this
* smoke sets zod's shared global config (`globalThis.__zod_globalConfig`, read
* by zod/v4/core when it loads) before any page script runs, so
* every other violation is still caught. Owner: frontend-platform. Remove the
* init script below when the app configures zod itself.
*/
test.beforeEach(async ({ page, baseURL }) => {
const origin = new URL(baseURL ?? "http://127.0.0.1:4173").origin;
await page.route(
(url) => url.origin === origin,
async (route) => {
const response = await route.fetch();
await route.fulfill({
response,
headers: { ...response.headers(), ...securityHeaders },
});
},
);
await page.addInitScript(() => {
(globalThis as { __zod_globalConfig?: object }).__zod_globalConfig = { jitless: true };
});
await page.addInitScript(() => {
const violations: string[] = [];
Object.defineProperty(window, "__cspViolations", { value: violations });
document.addEventListener("securitypolicyviolation", (event) => {
violations.push(`${event.effectiveDirective} ${event.blockedURI}`);
});
});
});
async function cspViolations(page: Page): Promise<string[]> {
return page.evaluate(() => (window as unknown as { __cspViolations: string[] }).__cspViolations);
}
test("boots and changes route under the production security headers", async ({ page }) => {
const response = await page.goto("/");
expect(response?.headers()["content-security-policy"]).toBe(
securityHeaders["Content-Security-Policy"],
);
await expect(page.getByRole("heading", { level: 1 })).toHaveText(
"Clean Architecture Frontend",
);
await page
.getByRole("navigation", { name: "주요 탐색" })
.getByRole("link", { name: "화면 상태" })
.click();
await expect(
page.getByRole("heading", { level: 1, name: "화면 상태" }),
).toBeFocused();
expect(await cspViolations(page)).toEqual([]);
});
@@ -0,0 +1 @@
export { createFixtureHttpClient as createInternalClient } from "../client.ts";
@@ -0,0 +1 @@
export const openFixtureDatabase = (): string => "indexeddb";
@@ -0,0 +1,4 @@
// storage/indexeddb is a runtime of the browser-file-storage bundle; its index.ts is its public boundary.
import { openFixtureDatabase } from "../adapters/storage/indexeddb/index.ts";
export const storageComposition = openFixtureDatabase;
@@ -0,0 +1,4 @@
// 12-07 P3b: a second-level index.ts is not a public barrel.
import { createInternalClient } from "../adapters/http/internals/index.ts";
export const subBarrelComposition = createInternalClient;
@@ -0,0 +1 @@
export const telemetryAdapter = 1;
@@ -0,0 +1,2 @@
// 12-03 P4b: a context module re-exporting a concrete adapter.
export * from "../../adapters/telemetry/index.ts";
@@ -0,0 +1,2 @@
// 12-03 P4a: a feature root file re-exporting a concrete adapter.
export * from "../../adapters/telemetry/index.ts";
@@ -0,0 +1 @@
export { telemetryAdapter as contextTelemetry } from "../contexts/customer/telemetry.ts";
@@ -0,0 +1 @@
export { telemetryAdapter } from "../features/alpha/telemetry.ts";
@@ -0,0 +1 @@
export const connectRealtime = (): undefined => undefined;
@@ -0,0 +1,4 @@
// The realtime runtime is not selected, so the composition root does not build it.
import { connectRealtime } from "../adapters/realtime/index.ts";
export const composedRealtime = connectRealtime;
@@ -0,0 +1,2 @@
// A named facade that re-exports a primitive under its pre-VD-05 path.
export { Button } from "../../design-system/primitives/core.ts";
@@ -0,0 +1 @@
export { Button } from "./primitives/core.ts";
@@ -0,0 +1 @@
export const Button = "button";
@@ -0,0 +1,4 @@
// 12-08 P6: a deep import past the design-system index.
import { Button } from "../design-system/primitives/core.ts";
export const DeepImport = Button;
@@ -1,3 +1,4 @@
// VD-05: lucide-react is imported only by the icon vendor facade.
import { Menu } from "lucide-react";
export const DirectIcon = Menu;
@@ -0,0 +1,3 @@
import { Button } from "../design-system/index.ts";
export const PublicImport = Button;
@@ -0,0 +1,2 @@
// 12-06 P1d: import.meta.glob loads modules the graph cannot list, so it is refused.
export const valueModules = import.meta.glob("../domain/*.ts");
@@ -1,3 +0,0 @@
import { Button } from "../../../../src/presentation/design-system/primitives/core.tsx";
export const DeepImport = Button;
@@ -1,3 +0,0 @@
import { createWebSocketConnection } from "../../../adapters/realtime/websocket/websocket-connection.ts";
export const incorrectlyComposed = createWebSocketConnection;
@@ -86,16 +86,14 @@ jobs:
if: \${{ startsWith(gitea.ref, 'refs/tags/v') || (gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'release' || inputs.stage == 'production' || inputs.stage == 'field')) }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
HOSTING_BASE_URL: "\${{ vars.HOSTING_BASE_URL }}"
strategy:
fail-fast: false
matrix:
include:
- { gate: FE-GATE-012, name: bundle, browser: false }
- { gate: FE-GATE-014, name: config-compatibility, browser: false }
- { gate: FE-GATE-019, name: hosting-header, browser: false }
- { gate: FE-GATE-026, name: lab-performance, browser: true }
- { gate: FE-GATE-028, name: manual-accessibility-review, browser: false }
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
@@ -377,11 +375,13 @@ jobs:
if: \${{ gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'production' || inputs.stage == 'field') }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
HOSTING_BASE_URL: "\${{ vars.HOSTING_BASE_URL }}"
strategy:
fail-fast: false
matrix:
include:
- { gate: FE-GATE-016, name: rollback-drill }
- { gate: FE-GATE-019, name: hosting-header }
- { gate: FE-GATE-021, name: runbook-boot-config }
- { gate: FE-GATE-022, name: runbook-chunk-mismatch }
- { gate: FE-GATE-023, name: runbook-api-degradation }
+68
View File
@@ -0,0 +1,68 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { architectureDependencyReportArtifactSchema } from "../../scripts/contracts/release-artifacts.ts";
// 12-05 (D-11). dependency-cruiser cannot parse TypeScript 7, so it checked
// zero modules and passed while its report claimed a result. The import graph
// in check-architecture.ts is the only checker; the report carries only it.
const staticImportGraph = {
analyzer: "babel-parser-node-resolver",
modules: [],
dependencies: [],
unresolved: [],
parseFailures: [],
cycles: [],
violations: [],
summary: {
modules: 0,
typescriptModules: 0,
dependencies: 0,
localDependencies: 0,
unresolved: 0,
parseFailures: 0,
cycles: 0,
errors: 0,
typeScriptOnlyPolicyPassed: true,
nonTypeScriptExecutableSources: 0,
},
fixtureChecks: { passed: true, checks: [], failures: [] },
typeScriptOnlySourcePolicy: {
checkedRoots: ["src"],
exceptionsAllowed: false,
violations: [],
passed: true,
},
};
describe("architecture dependency report", () => {
it("carries the import graph only", () => {
expect(architectureDependencyReportArtifactSchema.parse({ staticImportGraph })).toEqual({
staticImportGraph,
});
});
it("rejects a dependency-cruiser section", () => {
const cruiserSummary = {
violations: [],
error: 0,
warn: 0,
info: 0,
ignore: 0,
totalCruised: 0,
totalDependenciesCruised: 0,
};
expect(
architectureDependencyReportArtifactSchema.safeParse({
modules: [],
summary: cruiserSummary,
staticImportGraph,
}).success,
).toBe(false);
});
it("does not run dependency-cruiser", async () => {
expect(await readFile("scripts/check-architecture.ts", "utf8")).not.toMatch(/depcruise/u);
});
});
@@ -0,0 +1,35 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { formatArchitectureViolation } from "../../scripts/lib/architecture-violation-message.ts";
// 12-11. A violation used to print only the rule name and the file pair; the
// reason and the way out were in .dependency-cruiser.json.
describe("architecture violation message", () => {
it("names the import and says why and where to go", () => {
expect(
formatArchitectureViolation(
{
rule: "concrete-adapters-compose-only-in-bootstrap",
source: "src/presentation/pages/probe.tsx",
target: "src/adapters/http/index.ts",
},
["../../adapters/http/index.ts"],
"Only src/bootstrap constructs concrete adapters.",
),
).toBe(
"Architecture violation [concrete-adapters-compose-only-in-bootstrap]: " +
"src/presentation/pages/probe.tsx -> src/adapters/http/index.ts " +
'(import "../../adapters/http/index.ts")\n' +
" why: Only src/bootstrap constructs concrete adapters.\n",
);
});
it("gives every rule a reason to print", async () => {
const config = JSON.parse(await readFile(".dependency-cruiser.json", "utf8")) as {
forbidden: { name: string; comment?: string }[];
};
expect(config.forbidden.filter(({ comment }) => !comment?.trim()).map(({ name }) => name)).toEqual([]);
});
});
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { promotionEvidenceTime } from "../../scripts/lib/exact-promotion-bundle.ts";
import { evaluatePromotionEvidence } from "../../scripts/lib/provider-evidence.ts";
import { syntheticSignedPromotionBundle } from "./security-followup-fixture.ts";
// 13-04. Provider evidence lives two hours at most, so a promoted release could
// not be re-verified the next day, which the rollback runbook requires. The
// archived mode checks freshness at the recorded promotion time instead.
const promotedAt = Date.parse("2026-08-02T01:00:00.000Z");
const threeHoursLater = promotedAt + 3 * 60 * 60 * 1_000;
function evidenceAt(freshness: "current" | "archived", now: number) {
const fixture = syntheticSignedPromotionBundle();
const provider = JSON.parse(fixture.files["provider-verification.json"].toString("utf8"));
return evaluatePromotionEvidence({
expected: {
run: provider.run,
source: provider.source,
candidate: provider.candidate,
vulnerabilityInvocationNonce: provider.providerEvidence.vulnerabilityInvocationNonce,
provenanceInvocationNonce: provider.providerEvidence.provenanceInvocationNonce,
secretScanAttestation: provider.providerEvidence.secretScanAttestation,
},
localStatus: "PASS",
vulnerabilityReport: JSON.parse(fixture.files["vulnerability-report.json"].toString("utf8")),
provenanceAttestation: JSON.parse(fixture.files["provenance-attestation.json"].toString("utf8")),
vulnerabilityTrust: fixture.verification.vulnerabilityTrust,
provenanceTrust: fixture.verification.provenanceTrust,
nowEpochMs: () => promotionEvidenceTime(freshness, provider.verifiedAt, now),
});
}
describe("archived promotion re-verification", () => {
it("accepts evidence three hours after promotion in archived mode only", () => {
expect(evidenceAt("archived", threeHoursLater).status).toBe("PASS");
expect(evidenceAt("current", threeHoursLater)).toMatchObject({
status: "FAIL_UNVERIFIED",
failures: expect.arrayContaining(["vulnerability report is expired"]),
});
});
it("refuses a promotion time recorded in the future", () => {
expect(() =>
promotionEvidenceTime("archived", "2026-08-02T05:00:00.000Z", promotedAt),
).toThrow(/verifiedAt is in the future/u);
});
});
+40 -4
View File
@@ -189,15 +189,15 @@ describe("CI gate contract", () => {
const index = indexCiGateContract(contract);
expect(contract.schemaVersion).toBe(2);
expect(contract.gates.map(({ id }) => id)).toEqual(
Array.from({ length: 27 }, (_, index) =>
Array.from({ length: 28 }, (_, index) =>
`FE-GATE-${String(index + 1).padStart(3, "0")}`,
),
).filter((gateId) => gateId !== "FE-GATE-016"),
);
expect(contract.jobs).toHaveLength(9);
expect(contract.commands).toHaveLength(93);
expect(contract.commands).toHaveLength(95);
expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(105);
expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(31);
expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(88);
expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(87);
expect(contract.artifacts).toHaveLength(109);
expect(contract.stages).toHaveLength(5);
expect(contract.retention.classes).toHaveLength(5);
@@ -205,6 +205,42 @@ describe("CI gate contract", () => {
expect(index.gates.get("FE-GATE-020")?.name).toBe("removability");
});
it("runs the signed manual accessibility review at release, not merge (08-06)", async () => {
const contract = await loadCiGateContract(process.cwd());
const index = indexCiGateContract(contract);
const scriptsOf = (gateId: string) =>
(index.gates.get(gateId)?.commandIds ?? []).map((id) => {
const command = index.commands.get(id);
return [command?.script, ...(command?.args ?? [])].join(" ");
});
const stageOf = (gateId: string) =>
contract.stages.find(({ gateIds }) => gateIds.includes(gateId))?.id;
expect(scriptsOf("FE-GATE-009")).toEqual(["test:a11y", "review:a11y-manual -- --format-only"]);
expect(scriptsOf("FE-GATE-028")).toEqual(["review:a11y-manual"]);
expect(stageOf("FE-GATE-009")).toBe("merge");
expect(stageOf("FE-GATE-028")).toBe("release");
});
it("runs the CPU-independent scale PR tier in a merge gate (11-03)", async () => {
const contract = await loadCiGateContract(process.cwd());
const index = indexCiGateContract(contract);
const scripts = index.gates.get("FE-GATE-005")?.commandIds.map((id) => index.commands.get(id)?.script);
expect(scripts).toContain("check:scale:pr");
expect(contract.stages.find(({ id }) => id === "merge")?.gateIds).toContain("FE-GATE-005");
});
it("probes live hosting headers after promotion, not before the release is built (13-05)", async () => {
const contract = await loadCiGateContract(process.cwd());
expect(contract.stages.find(({ id }) => id === "production")?.gateIds).toContain("FE-GATE-019");
expect(contract.stages.find(({ id }) => id === "release")?.gateIds).not.toContain("FE-GATE-019");
const productionGate = contract.jobs.find(({ id }) => id === "production_gate");
expect(productionGate?.gateIds).toContain("FE-GATE-019");
expect(productionGate?.environment).toContainEqual({
name: "HOSTING_BASE_URL",
value: "${{ vars.HOSTING_BASE_URL }}",
});
});
it("keeps the action registry recursively immutable and resolves only known actions", () => {
expect(Object.isFrozen(CI_ACTION_REGISTRY)).toBe(true);
expect(Object.values(CI_ACTION_REGISTRY).every((action) => Object.isFrozen(action))).toBe(true);
+38
View File
@@ -0,0 +1,38 @@
import { chmod, mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { makeDistFilesPublic } from "../../scripts/lib/dist-permissions.ts";
// 13-02. The validated JSON writer publishes with mode 0600, so dist/config.json
// and dist/release-manifest.json reached the release archive unreadable to a web
// server running as another user, and every boot failed with 403.
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
describe("dist file permissions", () => {
it("makes every dist file readable by other users and keeps other bits", async () => {
const root = await mkdtemp(path.join(tmpdir(), "dist-permissions-"));
roots.push(root);
await mkdir(path.join(root, ".vite"), { recursive: true });
const files = {
"config.json": 0o600,
".vite/manifest.json": 0o600,
"index.html": 0o664,
} as const;
for (const [file, mode] of Object.entries(files)) {
await writeFile(path.join(root, file), "{}");
await chmod(path.join(root, file), mode);
}
await makeDistFilesPublic(root);
expect((await stat(path.join(root, "config.json"))).mode & 0o777).toBe(0o644);
expect((await stat(path.join(root, ".vite/manifest.json"))).mode & 0o777).toBe(0o644);
expect((await stat(path.join(root, "index.html"))).mode & 0o777).toBe(0o664);
});
});
+23
View File
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
import {
checkPublicServiceWorkers,
classifyLiveHostingBaseUrl,
hostingVerdict,
servedEntryScript,
} from "../../scripts/lib/hosting-probe.ts";
describe("public service worker in dist", () => {
@@ -64,3 +66,24 @@ describe("live hosting evidence target", () => {
});
});
});
// 13-05 (D-14). The declared-header fixture proves nothing about hosting, so it
// is UNVERIFIED, and a live probe checks the release actually served.
describe("hosting header verdict", () => {
it("passes only a live probe of the deployed release", () => {
expect(hostingVerdict("live", true)).toBe("PASS");
expect(hostingVerdict("fixture", true)).toBe("UNVERIFIED");
expect(hostingVerdict("fixture", false)).toBe("FAIL");
expect(hostingVerdict("invalid-live", false)).toBe("FAIL");
expect(hostingVerdict("live", false)).toBe("FAIL");
});
it("probes the entry script named by the served index.html", () => {
expect(
servedEntryScript(
'<head><link rel="modulepreload" href="/assets/a-1.js"><script type="module" crossorigin src="/app/assets/index-Dpjd89Th.js"></script></head>',
),
).toBe("/app/assets/index-Dpjd89Th.js");
expect(servedEntryScript("<html><body>maintenance</body></html>")).toBeNull();
});
});
+38
View File
@@ -1,8 +1,11 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import {
MANUAL_A11Y_ROUTE_IDS,
validateManualA11yEvidence,
validateManualA11yRecordFormat,
} from "../../scripts/lib/manual-a11y-evidence.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
@@ -64,4 +67,39 @@ describe("manual accessibility evidence", () => {
passed: false,
});
});
// 08-06: the merge stage checks only that each record keeps the template's
// shape; the signed review itself is a release-stage gate (FE-GATE-028).
describe("record format", () => {
const pending = reviewed
.replace("Status: reviewed", "Status: pending-manual-review")
.replace("Release ID: release-1", "Release ID:")
.replace("Reviewer: reviewer@example.test", "Reviewer:")
.replace("Reviewed at: 2026-07-25T12:00:00Z", "Reviewed at:")
.replace("Signature: review-record-1", "Signature:")
.replace("Attestation: accepted", "Attestation: pending")
.replace("M1 Keyboard: pass", "M1 Keyboard: pending");
it("accepts a pending template and a signed record", () => {
expect(validateManualA11yRecordFormat(pending, "APP_HOME")).toEqual([]);
expect(validateManualA11yRecordFormat(reviewed, "APP_HOME")).toEqual([]);
});
it("accepts every checked-in route record", () => {
for (const routeId of MANUAL_A11Y_ROUTE_IDS) {
const record = readFileSync(`artifacts/tests/a11y-manual/${routeId}.md`, "utf8");
expect(validateManualA11yRecordFormat(record, routeId), routeId).toEqual([]);
}
});
it.each([
["a missing field", pending.replace("Signature:\n", ""), "APP_HOME", "Signature"],
["an unknown status", pending.replace("Status: pending-manual-review", "Status: done"), "APP_HOME", "Status"],
["an unknown verdict", pending.replace("M1 Keyboard: pending", "M1 Keyboard: ok"), "APP_HOME", "M1 Keyboard"],
["another route's record", pending, "NOT_FOUND", "Route ID"],
["a reviewed record that is not complete", reviewed.replace("Signature: review-record-1", "Signature:"), "APP_HOME", "Signature"],
])("rejects %s", (_name, record, routeId, field) => {
expect(validateManualA11yRecordFormat(record, routeId)).toContain(field);
});
});
});
+1 -1
View File
@@ -25,7 +25,7 @@ describe("promotion readiness formula", () => {
it.each([
["FE-GATE-001", "MERGE_READY"],
["FE-GATE-012", "RELEASE_READY"],
["FE-GATE-016", "PROD_PROMOTION_READY"],
["FE-GATE-021", "PROD_PROMOTION_READY"],
["FE-GATE-018", "FIELD_SLO_READY"],
["FE-GATE-017", "DOCUMENTATION_READY"],
] as const)("fails closed when %s fails", (failedGate, readiness) => {
+3 -3
View File
@@ -63,7 +63,7 @@ const buildManifest = {
describe("release artifact contracts", () => {
it("verifies confined build outputs and the raw module inventory bytes", async () => {
const moduleInventoryBytes = Buffer.from(
'{"schemaVersion":1,"chunks":[]}\n',
'{"schemaVersion":1,"chunks":[],"packages":[]}\n',
);
const files = new Map<string, Buffer>([
["/repo/dist/.vite/manifest.json", Buffer.from("{}\n")],
@@ -158,7 +158,7 @@ describe("release artifact contracts", () => {
it("rejects a nested symlink that resolves inside the repository but outside dist", async () => {
const moduleInventoryBytes = Buffer.from(
'{"schemaVersion":1,"chunks":[]}\n',
'{"schemaVersion":1,"chunks":[],"packages":[]}\n',
);
const mismatches = await verifyBuildManifestOutputs(
{
@@ -183,7 +183,7 @@ describe("release artifact contracts", () => {
it("allows a legal dist child whose name begins with two dots", async () => {
const moduleInventoryBytes = Buffer.from(
'{"schemaVersion":1,"chunks":[]}\n',
'{"schemaVersion":1,"chunks":[],"packages":[]}\n',
);
const files = new Map<string, Buffer>([
["/repo/dist/.vite/manifest.json", Buffer.from("{}\n")],
+14 -64
View File
@@ -281,32 +281,32 @@ describe("release coherence", () => {
}
});
it("falls back to public rollback artifacts only when primary dist is absent", async () => {
// 13-03: the rollback drill checks the built release only. Reading the
// public/ placeholders when dist was absent let it pass without any build.
it("reads only the built dist pair and never falls back to public placeholders", async () => {
const exactV2 = await releaseV2With(contractPackages);
const tamperedPrimary = await releaseV2With(contractPackages.slice(0, 1));
const validPublic = {
"public/release-manifest.json": exactV2,
"public/config.json": runtimeV2,
};
const unavailablePrimary = [
new SyntaxError("invalid primary JSON"),
Object.assign(new Error("unreadable primary"), { code: "EACCES" }),
{ ...exactV2, unexpected: "tampered" },
];
for (const primaryFailure of unavailablePrimary) {
for (const primary of [
{},
{ "dist/config.json": runtimeV2 },
{ "dist/release-manifest.json": exactV2 },
{ "dist/release-manifest.json": new SyntaxError("invalid primary JSON"), "dist/config.json": runtimeV2 },
{ "dist/release-manifest.json": { ...exactV2, unexpected: "tampered" }, "dist/config.json": runtimeV2 },
]) {
const reads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader({
"dist/release-manifest.json": primaryFailure,
"dist/config.json": runtimeV2,
...validPublic,
}),
readArtifact: artifactReader({ ...primary, ...validPublic }, reads),
contractPackages,
}),
).rejects.toBeDefined();
expect(reads.some((read) => read.startsWith("public/"))).toBe(false);
}
const tamperedPrimary = await releaseV2With(contractPackages.slice(0, 1));
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader({
@@ -317,55 +317,5 @@ describe("release coherence", () => {
contractPackages,
}),
).resolves.toMatchObject({ coherence: { compatible: false } });
const releaseOnlyMissingReads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader(
{
"dist/config.json": runtimeV2,
...validPublic,
},
releaseOnlyMissingReads,
),
contractPackages,
}),
).rejects.toThrow("primary rollback artifact pair");
expect(releaseOnlyMissingReads).toEqual([
"dist/release-manifest.json",
"dist/config.json",
]);
const runtimeOnlyMissingReads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader(
{
"dist/release-manifest.json": exactV2,
...validPublic,
},
runtimeOnlyMissingReads,
),
contractPackages,
}),
).rejects.toThrow("primary rollback artifact pair");
expect(runtimeOnlyMissingReads).toEqual([
"dist/release-manifest.json",
"dist/config.json",
]);
const missingPairReads: string[] = [];
await expect(
verifyRollbackReleaseCoherence({
readArtifact: artifactReader(validPublic, missingPairReads),
contractPackages,
}),
).resolves.toMatchObject({ coherence: { compatible: true } });
expect(missingPairReads).toEqual([
"dist/release-manifest.json",
"dist/config.json",
"public/release-manifest.json",
"public/config.json",
]);
});
});
+129
View File
@@ -0,0 +1,129 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { runRunbookDrill } from "../../scripts/drill-runbook.ts";
import { computeContractSetDigest } from "../../src/contracts/contract-set-canonical.ts";
import type { InstalledContractPackageIdentity } from "../../src/contracts/external-contract-runtime.ts";
// 11-01 / 13-03 (D-14). A drill reports PASS only for what it observed on the
// local build. Boot, live traffic, smoke and the provider switch are not
// observable here, so a drill with provider scope ends UNVERIFIED, never PASS.
const contractPackages = [
{
packageId: "@example/accounts",
version: "1.2.3",
digest: `sha256:${"1".repeat(64)}`,
runtimeProtocolVersion: 1,
sourceRevision: "a".repeat(40),
},
] as const satisfies readonly InstalledContractPackageIdentity[];
const RUNBOOK_IDS = ["FE-RB-001", "FE-RB-002", "FE-RB-003", "FE-RB-004", "FE-RB-005"] as const;
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
async function builtDist(options: Readonly<{ withoutJs?: boolean; withoutDist?: boolean }> = {}) {
const root = await mkdtemp(path.join(tmpdir(), "runbook-drill-"));
roots.push(root);
if (options.withoutDist) return root;
const write = async (file: string, content: string) => {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
};
await write("dist/index.html", "<!doctype html><script type=module src=/assets/index-a.js></script>");
await write(
"dist/.vite/manifest.json",
JSON.stringify({
"index.html": { file: "assets/index-a.js", isEntry: true, css: ["assets/index-a.css"], imports: ["_shared-b.js"] },
"_shared-b.js": { file: "assets/shared-b.js" },
"src/pages/lazy.tsx": { file: "assets/lazy-c.js", isDynamicEntry: true },
}),
);
await write("dist/assets/index-a.css", "body{}");
if (!options.withoutJs) {
for (const file of ["assets/index-a.js", "assets/shared-b.js", "assets/lazy-c.js"]) {
await write(`dist/${file}`, "export {};");
}
}
await write(
"dist/release-manifest.json",
JSON.stringify({
schemaVersion: 2,
appVersion: "1.0.0",
buildId: "build-a",
commitSha: "abc1234",
configSchemaVersion: "2.0",
assetManifestHash: "assets-a",
releaseId: "release-a",
builtAt: "2026-08-01T00:00:00.000Z",
routeChunks: {},
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: await computeContractSetDigest(contractPackages),
packages: [...contractPackages],
},
}),
);
await write(
"dist/config.json",
JSON.stringify({
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080/",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 2,
TELEMETRY_ENABLED: false,
AUTH_MODE: "external",
CONFIG_SCHEMA_VERSION: "2.0",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "build-a",
RELEASE_ID: "release-a",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
}),
);
return root;
}
describe("runbook drill verdicts", () => {
it.each(RUNBOOK_IDS)("%s on a complete local build is UNVERIFIED, not PASS", async (runbookId) => {
const record = await runRunbookDrill(runbookId, { releaseRoot: await builtDist(), contractPackages });
expect(record.result).toBe("UNVERIFIED");
expect(record.recoveryAssertions.some(({ result }) => result === "FAIL")).toBe(false);
});
it.each(["FE-RB-002", "FE-RB-005"] as const)(
"%s fails when the build lost its JavaScript assets",
async (runbookId) => {
const record = await runRunbookDrill(runbookId, {
releaseRoot: await builtDist({ withoutJs: true }),
contractPackages,
});
expect(record.result).toBe("FAIL");
},
);
it("FE-RB-005 fails without a build instead of reading public/ placeholders", async () => {
await expect(
runRunbookDrill("FE-RB-005", { releaseRoot: await builtDist({ withoutDist: true }), contractPackages }),
).rejects.toThrow(/dist\/release-manifest\.json/u);
});
it("keeps no constant recovery verdict in the drill source", async () => {
const source = await readFile("scripts/drill-runbook.ts", "utf8");
expect(source).not.toMatch(/assertion\([^;]*,\s*true\s*\)/u);
expect(source).not.toMatch(/Asserted:\s*true\b/u);
expect(source).not.toMatch(/injectedMountFailure\s*=\s*true/u);
});
});
+12
View File
@@ -46,12 +46,24 @@ describe("ungated test files", () => {
"tests/scripts/verify-extreme-scale.test.ts",
"tests/scale/browser-soak.contract.test.ts",
"tests/e2e/app-shell.spec.ts",
// 11-03: the CPU-independent scale PR tier runs in FE-GATE-005.
"tests/scale/growth-regression.test.ts",
"tests/scale/traffic/amplification-metrics.test.ts",
])("gates %s", async (file) => {
const inputs = await repositoryInputs();
expect(ungatedTestFailures({ ...inputs, testFiles: [file] })).toEqual([]);
expect(inputs.exclusions.some(({ path }) => path === file)).toBe(false);
});
it("reads the Vitest paths of a scale tier the gate command runs (11-03)", () => {
expect(
gatedTestPaths({ gate: "node scripts/scale/run-scale-profile.ts pr" }, ["gate"], () => ""),
).toEqual(expect.arrayContaining(["tests/scale/growth-regression.test.ts", "tests/scale/traffic"]));
expect(
gatedTestPaths({ gate: "node scripts/scale/run-scale-profile.ts pr" }, ["gate"], () => ""),
).not.toContain("tests/scale/session");
});
it("rejects a new test directory that no gate runs", async () => {
const inputs = await repositoryInputs();
expect(
+31
View File
@@ -0,0 +1,31 @@
import { readFileSync, realpathSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { bundledPackages, normalizeModuleId } from "../../scripts/lib/vite-module-inventory.ts";
// 13-12. The inventory recorded dependency modules as `external:<file name>`,
// so nothing listed which package versions ship in the public bundle.
describe("vite module inventory", () => {
const root = process.cwd();
const zodCore = realpathSync(path.join(root, "node_modules/zod/v4/core/core.js"));
const zodVersion = (
JSON.parse(readFileSync(path.join(root, "node_modules/zod/package.json"), "utf8")) as { version: string }
).version;
it("names a dependency module by package and version", () => {
expect(normalizeModuleId(zodCore, root)).toBe(`npm:zod@${zodVersion}/v4/core/core.js`);
expect(normalizeModuleId(path.join(root, "src/bootstrap/main.tsx"), root)).toBe("src/bootstrap/main.tsx");
expect(normalizeModuleId("\0vite/preload-helper.js", root)).toBe("vite/preload-helper.js");
});
it("lists each bundled package once", () => {
expect(
bundledPackages([
{ fileName: "a.js", modules: ["npm:zod@4.4.3/v4/core/core.js", "src/a.ts"] },
{ fileName: "b.js", modules: ["npm:@tanstack/query-core@5.0.0/build/a.js", "npm:zod@4.4.3/index.js"] },
]),
).toEqual(["@tanstack/query-core@5.0.0", "zod@4.4.3"]);
});
});