create-cmp-cli 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +72 -11
  2. package/llms.txt +6 -2
  3. package/package.json +1 -1
  4. package/src/commands/upgrade.mjs +8 -1
  5. package/src/lib/adr-seed.mjs +178 -0
  6. package/src/lib/registry.mjs +15 -2
  7. package/src/lib/tabs.mjs +91 -4
  8. package/src/lib/upgrade.mjs +49 -5
  9. package/src/scaffold.mjs +52 -1
  10. package/src/versions/candidates.json +4 -0
  11. package/src/versions/registry.json +88 -0
  12. package/template/.claude/skills/add-feature/SKILL.md +35 -10
  13. package/template/.claude/skills/add-repository/SKILL.md +1 -1
  14. package/template/.claude/skills/add-screen/SKILL.md +13 -7
  15. package/template/.githooks/pre-push +24 -0
  16. package/template/CLAUDE.md +196 -48
  17. package/template/README.md +23 -27
  18. package/template/composeApp/src/androidDebug/kotlin/com/example/app/inspector/CrashRecorder.kt +99 -0
  19. package/template/composeApp/src/androidDebug/kotlin/com/example/app/inspector/DbInspector.kt +144 -0
  20. package/template/composeApp/src/androidDebug/kotlin/com/example/app/inspector/InspectorHttpServer.kt +69 -2
  21. package/template/composeApp/src/androidDebug/kotlin/com/example/app/inspector/InspectorInit.kt +8 -4
  22. package/template/composeApp/src/androidDebug/kotlin/com/example/app/inspector/NavInspector.kt +31 -0
  23. package/template/composeApp/src/commonMain/kotlin/com/example/app/data/AppResultCatching.kt +32 -0
  24. package/template/composeApp/src/commonMain/kotlin/com/example/app/data/remote/ItemRepositoryImpl.kt +9 -2
  25. package/template/composeApp/src/commonMain/kotlin/com/example/app/domain/model/DomainError.kt +21 -0
  26. package/template/composeApp/src/commonMain/kotlin/com/example/app/domain/repository/ItemRepository.kt +4 -1
  27. package/template/composeApp/src/commonMain/kotlin/com/example/app/domain/result/AppResult.kt +23 -0
  28. package/template/composeApp/src/commonMain/kotlin/com/example/app/domain/usecase/GetItemsUseCase.kt +4 -1
  29. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/AppBottomBar.kt +138 -0
  30. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/AppButton.kt +56 -0
  31. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/AppHeader.kt +54 -0
  32. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/BaseScreen.kt +16 -8
  33. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/ContentStateContainer.kt +105 -0
  34. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/ContentUiState.kt +18 -0
  35. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/EmptyState.kt +58 -0
  36. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/ErrorState.kt +52 -0
  37. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/ListItemCard.kt +77 -0
  38. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/ScreenColumn.kt +47 -0
  39. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/Shimmer.kt +90 -0
  40. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/components/TestTagAutomation.kt +9 -9
  41. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/home/DetailScreen.kt +5 -27
  42. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/home/HomeScreen.kt +14 -70
  43. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/home/HomeViewModel.kt +33 -13
  44. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/navigation/AppNavHost.kt +13 -0
  45. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/navigation/AppShell.kt +7 -109
  46. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/navigation/NavInspectionHook.kt +21 -0
  47. package/template/composeApp/src/commonMain/kotlin/com/example/app/presentation/profile/ProfileScreen.kt +4 -27
  48. package/template/composeApp/src/commonTest/kotlin/com/example/app/data/AppResultCatchingTest.kt +52 -0
  49. package/template/composeApp/src/commonTest/kotlin/com/example/app/data/remote/ItemRepositoryImplTest.kt +29 -4
  50. package/template/composeApp/src/commonTest/kotlin/com/example/app/domain/usecase/GetItemsUseCaseTest.kt +8 -6
  51. package/template/composeApp/src/commonTest/kotlin/com/example/app/presentation/home/HomeViewModelTest.kt +39 -27
  52. package/template/composeApp/src/commonTest/kotlin/com/example/app/testing/fakes/FakeItemRepository.kt +10 -6
  53. package/template/composeApp/src/desktopMain/kotlin/com/example/app/inspector/ComponentStories.kt +269 -0
  54. package/template/composeApp/src/desktopMain/kotlin/com/example/app/inspector/PreviewRegistry.kt +37 -1
  55. package/template/composeApp/src/desktopTest/kotlin/com/example/app/conformance/ArchitectureConformanceTest.kt +207 -15
  56. package/template/composeApp/src/desktopTest/kotlin/com/example/app/conformance/ComponentConformanceTest.kt +84 -0
  57. package/template/composeApp/src/desktopTest/kotlin/com/example/app/presentation/home/HomeScreenTest.kt +36 -4
  58. package/template/docs/ARCHITECTURE.md +317 -34
  59. package/template/docs/TESTING.md +6 -5
  60. package/template/docs/adr/0002-maestro-over-appium-for-e2e.md +39 -0
  61. package/template/docs/adr/0003-jvm-desktop-target-is-harness-infrastructure.md +39 -0
  62. package/template/docs/adr/0004-fakes-not-mocks-for-unit-tests.md +48 -0
  63. package/template/qa/approvals.json +42 -0
  64. package/template/qa/approve.mjs +139 -0
  65. package/template/qa/arch-doc.mjs +69 -0
  66. package/template/qa/comment.mjs +76 -0
  67. package/template/qa/comments.json +4 -0
  68. package/template/qa/golden/home.json +3 -3
  69. package/template/qa/lib/approvals.mjs +806 -0
  70. package/template/qa/lib/arch-doc.mjs +451 -0
  71. package/template/qa/lib/comments.mjs +252 -0
  72. package/template/qa/lib/component-stories.mjs +183 -0
  73. package/template/qa/lib/inputs-hash.mjs +5 -1
  74. package/template/qa/scaffold-feature.mjs +184 -67
  75. package/template/qa/setup-hooks.mjs +33 -0
  76. package/template/qa/verify.mjs +118 -9
  77. package/template/specs/app-base.spec.md +44 -7
  78. package/template/specs/home.spec.md +7 -4
  79. package/template/specs/intent.md +50 -0
@@ -0,0 +1,806 @@
1
+ // The hash-bound human-approval data model (VERIFICATION-LAYER-DESIGN.md §2,
2
+ // extended by GENESIS-FLOW-DESIGN.md §1/§2/§3 — the genesis flow's registry,
3
+ // express lane, and reopen mechanics).
4
+ //
5
+ // Reuses ADR-0005's philosophy exactly (docs/adr/0005-evidence-binding-by-inputs-hash.md
6
+ // in the create-cmp repo): an approval is valid iff a stored content hash matches a
7
+ // recompute of the SAME files, right now. No new hashing idea — just applied to a
8
+ // smaller, human-curated surface (one governed artifact) instead of the whole
9
+ // verified tree.
10
+ //
11
+ // Three concerns, kept separable:
12
+ // 1. The REGISTRY (`listGovernedArtifacts`) — artifact id -> resolved file list, in
13
+ // GENESIS-FLOW-DESIGN.md §1 order: intent(0), design-system(1), architecture(2),
14
+ // components(3), exemplar-feature(4), exemplar-spec(5), then one
15
+ // `feature-spec:<name>` (6+) per non-base, non-exemplar spec file present in
16
+ // specs/ right now. The exemplar (feature 4/5) is CONFIGURABLE — see
17
+ // `getExemplarFeature`/`resolveExemplarNames` below — defaulting to `home` so
18
+ // every ledger written before this config key existed keeps meaning what it
19
+ // meant. The registry is recomputed on every call — it reflects the tree as it
20
+ // stands, never a stale snapshot.
21
+ // 2. STATE (`loadApprovals`/`saveApprovals`) — qa/approvals.json, the human's
22
+ // decisions: { artifact, status, hash, approvedAt, mode?, reopenedAt? } plus the
23
+ // top-level `exemplarFeature` config key. Absent or corrupt is TOLERATED
24
+ // (treated as empty / all-unreviewed / default exemplar) — this ledger must
25
+ // never crash the verify lane or the stamper.
26
+ //
27
+ // Ledger migration note (architecture-document-standard.md §4.4): there is no
28
+ // schema-version bump or migration step anywhere in this file today (schema
29
+ // stays `cmp-approvals/1`, additive-only — see GENESIS-FLOW-DESIGN.md §2's
30
+ // express-lane note) — a widened hash BASIS (e.g. the `architecture` artifact
31
+ // growing from spec-only to spec+stripped-doc) is handled the same honest way
32
+ // every other content change is: `resolveArtifactStatus` recomputes on every
33
+ // read and compares against the STORED hash. An approval recorded under the
34
+ // old (narrower) basis simply stops matching the new recompute the first time
35
+ // it's read after this change ships, and correctly reports
36
+ // "changed-since-approval" — never a silent, un-re-earned "approved". This is
37
+ // not a special case: it is the SAME mechanism that already invalidates an
38
+ // approval when the governed files themselves change; widening what counts as
39
+ // "the governed files" for one artifact is just another such change. No
40
+ // separate migration code path exists or is needed.
41
+ // 3. The GATE (`evaluateApprovalsGate`) — combines registry + state into one
42
+ // per-artifact status (unreviewed / approved / changed-since-approval /
43
+ // reopened) and one aggregate verdict (PASS/FAIL/SKIP) for the verify-lane step
44
+ // to report. `reopened` behaves like `unreviewed` for the gate (SKIP-warn,
45
+ // non-blocking) — sanctioned redesign is never drift.
46
+ //
47
+ // Consumers: qa/approve.mjs (the CLI — thin shell over this file), qa/verify.mjs
48
+ // (the `approvals` gate), qa/scaffold-feature.mjs (seeds a new feature's spec as
49
+ // unreviewed, and resolves its clone-FROM exemplar through `resolveExemplarNames`).
50
+ // The console (inspector/mcp/src/lib/approvals-bridge.mjs) calls this same library.
51
+
52
+ import { createHash } from "node:crypto";
53
+ import fs from "node:fs";
54
+ import path from "node:path";
55
+
56
+ import { ARCH_DOC_REL_PATH, stripGeneratedSections } from "./arch-doc.mjs";
57
+
58
+ export const APPROVALS_REL_PATH = "qa/approvals.json";
59
+ export const APPROVALS_SCHEMA = "cmp-approvals/1";
60
+
61
+ // Kotlin source-set roots, relative to project root — mirrors qa/scaffold-feature.mjs's
62
+ // SRC() helper (composeApp/src/<sourceSet>/kotlin/<packageDir>).
63
+ const KOTLIN_SOURCE_SETS = {
64
+ commonMain: "composeApp/src/commonMain/kotlin",
65
+ commonTest: "composeApp/src/commonTest/kotlin",
66
+ desktopTest: "composeApp/src/desktopTest/kotlin",
67
+ };
68
+
69
+ // The canonical 11-file EXEMPLAR SHAPE (10 kotlin files + 1 spec), parametrized by
70
+ // the exemplar's own names — F (PascalCase feature, e.g. "Home"), f (lowercase
71
+ // package segment, e.g. "home"), E (PascalCase entity, e.g. "Item"). This is the
72
+ // SAME shape qa/scaffold-feature.mjs's ALL_FILES clones FROM (GENESIS-FLOW-DESIGN.md
73
+ // §1's "configurable exemplar") — the stamper imports this exact function so the
74
+ // clone-source list and the governed-artifact list can never drift from each other
75
+ // (single source of truth, not a parallel copy to keep in sync by hand).
76
+ // @param {string} F PascalCase feature name (e.g. "Home", "Favorites")
77
+ // @param {string} f lowercase package-segment name (e.g. "home", "favorites")
78
+ // @param {string} E PascalCase entity name (e.g. "Item", "Favorite")
79
+ // @returns {Array<{sourceSet: string, rel: string}>}
80
+ export function exemplarKotlinFileSet(F, f, E) {
81
+ return [
82
+ { sourceSet: "commonMain", rel: `domain/model/${E}.kt` },
83
+ { sourceSet: "commonMain", rel: `domain/repository/${E}Repository.kt` },
84
+ { sourceSet: "commonMain", rel: `domain/usecase/Get${E}sUseCase.kt` },
85
+ { sourceSet: "commonMain", rel: `data/remote/${E}RepositoryImpl.kt` },
86
+ { sourceSet: "commonTest", rel: `testing/fakes/Fake${E}Repository.kt` },
87
+ { sourceSet: "commonMain", rel: `presentation/${f}/${F}Screen.kt` },
88
+ { sourceSet: "commonMain", rel: `presentation/${f}/${F}ViewModel.kt` },
89
+ { sourceSet: "commonTest", rel: `presentation/${f}/${F}ViewModelTest.kt` },
90
+ { sourceSet: "desktopTest", rel: `presentation/${f}/${F}ScreenTest.kt` },
91
+ { sourceSet: "desktopTest", rel: `presentation/${f}/${F}GoldenTreeTest.kt` },
92
+ ];
93
+ }
94
+
95
+ // Naive de-pluralization, shared verbatim with qa/scaffold-feature.mjs's own
96
+ // entity-name default (a feature stamped without `--entity` gets this exact
97
+ // guess). Exported so both the stamper (deriving a NEW feature's entity) and this
98
+ // registry (guessing a CONFIGURED exemplar's entity from its feature name alone —
99
+ // see resolveExemplarNames) apply the identical heuristic. Unreliable for
100
+ // irregular nouns by design (the skill surfaces the guess for human override at
101
+ // stamp time); a wrong guess here simply fails to resolve files, which is refused
102
+ // (never fabricated), not silently wrong.
103
+ export function defaultEntityName(feature) {
104
+ if (feature.endsWith("ies") && feature.length > 3) return `${feature.slice(0, -3)}y`;
105
+ if (feature.endsWith("s") && !feature.endsWith("ss")) return feature.slice(0, -1);
106
+ return feature;
107
+ }
108
+
109
+ function toPascalCase(f) {
110
+ return f.charAt(0).toUpperCase() + f.slice(1);
111
+ }
112
+
113
+ function toUpperSnake(F) {
114
+ return F.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
115
+ }
116
+
117
+ /**
118
+ * Resolve the CONFIGURED exemplar's names — the ones the exemplar-feature/
119
+ * exemplar-spec governed artifacts (and qa/scaffold-feature.mjs's clone source)
120
+ * are built from.
121
+ *
122
+ * `home` (the default, and the only exemplar that predates configurability) is a
123
+ * hardcoded exception: its entity is `Item`, not derivable from `Home` by
124
+ * `defaultEntityName` (which would naively guess `Home`). Every OTHER exemplar is
125
+ * itself a feature that was stamped by qa/scaffold-feature.mjs, so its entity
126
+ * followed defaultEntityName(F) UNLESS it was stamped with an explicit `--entity`
127
+ * override — a choice this config key cannot see. In that mismatch case the guess
128
+ * is wrong and the file set simply fails to resolve (0 or partial files), which
129
+ * `resolveArtifactStatus`/`approveArtifact` already refuse rather than fabricate —
130
+ * the correct failure mode, not a special case to add here.
131
+ * @param {string} root
132
+ * @returns {{f: string, F: string, F_UPPER: string, E: string}}
133
+ */
134
+ export function resolveExemplarNames(root) {
135
+ const f = getExemplarFeature(root);
136
+ const F = toPascalCase(f);
137
+ const F_UPPER = toUpperSnake(F);
138
+ const E = f === "home" ? "Item" : defaultEntityName(F);
139
+ return { f, F, F_UPPER, E };
140
+ }
141
+
142
+ // Backward-compatible constants for the DEFAULT (`home`) exemplar — kept exported
143
+ // because they describe the shipped template's own exemplar shape independent of
144
+ // any project's configuration, and because they're the fixture the "stamping from
145
+ // home must be byte-identical" pin (test/genesis-flow.test.mjs) anchors to.
146
+ export const EXEMPLAR_FEATURE_KOTLIN_FILES = exemplarKotlinFileSet("Home", "home", "Item");
147
+ export const EXEMPLAR_SPEC_REL = "specs/home.spec.md";
148
+ export const ARCHITECTURE_SPEC_REL = "specs/app-base.spec.md";
149
+ export const INTENT_REL = "specs/intent.md";
150
+
151
+ // ── Package resolution ───────────────────────────────────────────────────────
152
+ // Mirrors qa/scaffold-feature.mjs's resolvePackage() primary path (the
153
+ // composeApp/build.gradle.kts namespace). Unlike the stamper, this NEVER dies —
154
+ // an unresolved package means the kotlin-rooted artifacts resolve to zero files.
155
+ // Zero resolution never CRASHES anything (the lane and the stamper stay up),
156
+ // but it is NOT benign for decisions: an approval over zero files would be the
157
+ // empty-input sha256 attesting nothing — a silent vacuous PASS, the exact
158
+ // failure mode this harness exists to kill (evidence must attest execution).
159
+ // So: approveArtifact REFUSES zero-file artifacts, and an already-approved
160
+ // artifact whose files stop resolving goes to changed-since-approval (FAIL),
161
+ // never PASS.
162
+ //
163
+ // IMPORTANT: detect "unresolved" by TOKEN SHAPE (`/^__[A-Z_]+__$/`), never by
164
+ // comparing against the literal string "__PACKAGE__". This file ships through
165
+ // the SAME scaffold pipeline that resolves that token — a literal comparison
166
+ // string is itself blindly text-substituted at stamp time (`replaceContents`
167
+ // does a global `"__PACKAGE__" -> config.package` replace over every template
168
+ // file's content, this one included), which would silently rewrite the
169
+ // sentinel into the real package and make the check always fail. A shape
170
+ // regex never spells the token out, so the pipeline has nothing to match.
171
+ const UNRESOLVED_TOKEN_RE = /^__[A-Z_]+__$/;
172
+
173
+ function resolvePackageDir(root) {
174
+ const gradleFile = path.join(root, "composeApp", "build.gradle.kts");
175
+ if (!fs.existsSync(gradleFile)) return null;
176
+ let contents;
177
+ try {
178
+ contents = fs.readFileSync(gradleFile, "utf8");
179
+ } catch {
180
+ return null;
181
+ }
182
+ const m = contents.match(/namespace\s*=\s*"([^"]+)"/);
183
+ if (!m || UNRESOLVED_TOKEN_RE.test(m[1])) return null;
184
+ return m[1].split(".").join("/");
185
+ }
186
+
187
+ function kotlinFile(root, sourceSet, rel) {
188
+ const packageDir = resolvePackageDir(root);
189
+ if (!packageDir) return null;
190
+ return path.posix.join(KOTLIN_SOURCE_SETS[sourceSet], packageDir, rel);
191
+ }
192
+
193
+ /**
194
+ * Is the project's package resolvable at all? False in the raw template (the
195
+ * namespace is still a placeholder token) and in any pre-stamp tree — the tell
196
+ * that this is not a generated project. The approve CLI refuses to WRITE
197
+ * approvals in such a tree (recording decisions against a template pollutes
198
+ * the template itself); read-only status remains available.
199
+ * @param {string} root
200
+ * @returns {boolean}
201
+ */
202
+ export function isPackageResolvable(root) {
203
+ return resolvePackageDir(root) !== null;
204
+ }
205
+
206
+ // ── Components glob ─────────────────────────────────────────────────────────
207
+
208
+ /**
209
+ * Sorted list of `presentation/components/*.kt` files under the resolved
210
+ * package, non-recursive (GENESIS-FLOW-DESIGN.md §1's `components` artifact — the
211
+ * component vocabulary conversation 3 approves). Package-unresolvable or a
212
+ * missing/empty directory both yield `[]` — resolveArtifactStatus/approveArtifact
213
+ * already treat a 0-file artifact as unresolvable ("a components glob matching
214
+ * zero files is unresolvable, not approvable-empty" — §1), so no special-casing
215
+ * is needed here beyond returning the honest (possibly empty) list.
216
+ * @param {string} root
217
+ * @returns {string[]} root-relative paths, sorted
218
+ */
219
+ function listComponentFiles(root) {
220
+ const dirRel = kotlinFile(root, "commonMain", "presentation/components");
221
+ if (!dirRel) return [];
222
+ let entries;
223
+ try {
224
+ entries = fs.readdirSync(path.join(root, dirRel), { withFileTypes: true });
225
+ } catch {
226
+ return [];
227
+ }
228
+ return entries
229
+ .filter((e) => e.isFile() && e.name.endsWith(".kt"))
230
+ .map((e) => path.posix.join(dirRel, e.name))
231
+ .sort((a, b) => a.localeCompare(b));
232
+ }
233
+
234
+ // ── Registry ─────────────────────────────────────────────────────────────────
235
+
236
+ /**
237
+ * The governed-artifact registry, resolved against the project at `root` right
238
+ * now (GENESIS-FLOW-DESIGN.md §1 order: intent(0), design-system(1),
239
+ * architecture(2), components(3), exemplar-feature(4), exemplar-spec(5), then one
240
+ * feature-spec:<name> (6+) per non-base, non-CONFIGURED-exemplar spec present).
241
+ *
242
+ * `complete: false` marks an artifact whose kotlin-rooted files could NOT be
243
+ * resolved (unresolvable package — raw template / pre-stamp tree). Such an
244
+ * artifact's `files` list is empty or partial (spec files only), so hashing it
245
+ * would attest nothing (or only a fraction) of what the artifact governs —
246
+ * approveArtifact refuses it, and the status surfaces treat it as unresolvable.
247
+ * @param {string} root absolute path to the project root
248
+ * @returns {Array<{id: string, label: string, files: string[], complete: boolean}>}
249
+ */
250
+ export function listGovernedArtifacts(root) {
251
+ const artifacts = [];
252
+ const packageResolved = resolvePackageDir(root) !== null;
253
+
254
+ artifacts.push({
255
+ id: "intent",
256
+ label: `Intent brief (${INTENT_REL})`,
257
+ files: [INTENT_REL],
258
+ complete: true,
259
+ });
260
+
261
+ artifacts.push({
262
+ id: "design-system",
263
+ label: "Design system (presentation/theme/Theme.kt, Tokens.kt)",
264
+ files: [
265
+ kotlinFile(root, "commonMain", "presentation/theme/Theme.kt"),
266
+ kotlinFile(root, "commonMain", "presentation/theme/Tokens.kt"),
267
+ ].filter(Boolean),
268
+ complete: packageResolved,
269
+ });
270
+
271
+ artifacts.push({
272
+ id: "architecture",
273
+ label: `Architecture + structure (${ARCHITECTURE_SPEC_REL} + ${ARCH_DOC_REL_PATH}, generated sections stripped)`,
274
+ // Hashed via hashArchitectureArtifact (spec bytes + stripped-doc content),
275
+ // NOT the generic hashArtifactFiles — this list is still the artifact's
276
+ // expected-files surface (missing-file refusal messages, "what governs
277
+ // this" bookkeeping), just not what gets hashed raw. See computeArtifactHash.
278
+ files: [ARCHITECTURE_SPEC_REL, ARCH_DOC_REL_PATH],
279
+ complete: true,
280
+ });
281
+
282
+ artifacts.push({
283
+ id: "components",
284
+ label: "Components (presentation/components/*.kt)",
285
+ files: listComponentFiles(root),
286
+ complete: packageResolved,
287
+ });
288
+
289
+ const { f: exemplarF, F: exemplarF_Pascal, E: exemplarE } = resolveExemplarNames(root);
290
+ const exemplarSpecRel = `specs/${exemplarF}.spec.md`;
291
+ const exemplarKotlinFiles = exemplarKotlinFileSet(exemplarF_Pascal, exemplarF, exemplarE);
292
+
293
+ artifacts.push({
294
+ id: "exemplar-feature",
295
+ label: `Exemplar feature (${exemplarF} — the 11-file set the stamper clones)`,
296
+ files: [
297
+ ...exemplarKotlinFiles.map((f) => kotlinFile(root, f.sourceSet, f.rel)).filter(Boolean),
298
+ exemplarSpecRel,
299
+ ],
300
+ complete: packageResolved,
301
+ });
302
+
303
+ artifacts.push({
304
+ id: "exemplar-spec",
305
+ label: `Exemplar spec (${exemplarSpecRel})`,
306
+ files: [exemplarSpecRel],
307
+ complete: true,
308
+ });
309
+
310
+ const specsDir = path.join(root, "specs");
311
+ if (fs.existsSync(specsDir)) {
312
+ const featureSpecs = fs
313
+ .readdirSync(specsDir)
314
+ .filter((f) => f.endsWith(".spec.md") && f !== "app-base.spec.md" && f !== `${exemplarF}.spec.md`)
315
+ .sort((a, b) => a.localeCompare(b));
316
+ for (const file of featureSpecs) {
317
+ const name = file.slice(0, -".spec.md".length);
318
+ artifacts.push({
319
+ id: `feature-spec:${name}`,
320
+ label: `Feature spec (specs/${file})`,
321
+ files: [`specs/${file}`],
322
+ complete: true,
323
+ });
324
+ }
325
+ }
326
+
327
+ return artifacts;
328
+ }
329
+
330
+ // ── Hashing (mirrors qa/lib/inputs-hash.mjs's computeInputsHash style) ───────
331
+
332
+ /**
333
+ * sha256 over the sorted `(path, sha256(content))` list of `relFiles` that
334
+ * currently exist under `root`. Deterministic; missing files are reported, not
335
+ * fatal — the hash is simply over what's present.
336
+ * @param {string} root
337
+ * @param {string[]} relFiles
338
+ * @returns {{ hash: string, fileCount: number, missing: string[] }}
339
+ */
340
+ export function hashArtifactFiles(root, relFiles) {
341
+ // Code-unit sort (default String sort), NOT localeCompare: the hash depends
342
+ // on iteration order and ICU collation varies with the machine's locale —
343
+ // an approval recorded on one machine must verify on every other.
344
+ const files = [...new Set(relFiles)].sort();
345
+ const present = [];
346
+ const missing = [];
347
+ for (const relPath of files) {
348
+ try {
349
+ if (fs.statSync(path.join(root, relPath)).isFile()) {
350
+ present.push(relPath);
351
+ continue;
352
+ }
353
+ } catch {
354
+ /* fall through to missing */
355
+ }
356
+ missing.push(relPath);
357
+ }
358
+
359
+ const overall = createHash("sha256");
360
+ for (const relPath of present) {
361
+ const bytes = fs.readFileSync(path.join(root, relPath));
362
+ const fileSha = createHash("sha256").update(bytes).digest("hex");
363
+ overall.update(`${relPath}\0${fileSha}\n`);
364
+ }
365
+ return { hash: overall.digest("hex"), fileCount: present.length, missing };
366
+ }
367
+
368
+ /**
369
+ * The `architecture` artifact's hash basis (docs/proposals/architecture-document-
370
+ * standard.md §4.4): `${ARCHITECTURE_SPEC_REL}`'s raw bytes + `${ARCH_DOC_REL_PATH}`
371
+ * with every `cmp:generated` marker's BODY stripped — `arch-doc.mjs`'s
372
+ * `stripGeneratedSections` is the ONE definition of "generated" for that doc,
373
+ * reused here rather than forked, so a new/changed marker id is understood
374
+ * identically by the regenerator and this hash.
375
+ *
376
+ * The doc's content is also normalized `\r\n` -> `\n` before hashing (spec
377
+ * files are hashed as raw bytes like every other artifact — a checkout-induced
378
+ * EOL difference in a Markdown prose doc is exactly the kind of accident that
379
+ * must never read as "authored drift", but the .spec.md files this repo ships
380
+ * are LF already and their exact bytes are what the human actually reviewed).
381
+ *
382
+ * Same row-hash shape as `hashArtifactFiles` (`path\0sha256(bytes)\n`, rows
383
+ * sorted by path) so the two schemes read the same way in a hex dump — this is
384
+ * a SEPARATE function (not a generic `hashArtifactFiles` call) only because the
385
+ * doc's bytes must be transformed (stripped + normalized) before hashing, never
386
+ * hashed raw.
387
+ *
388
+ * Regenerating a marker section (`node qa/arch-doc.mjs`) changes only the
389
+ * stripped-away body, so this hash does not move. Editing authored prose
390
+ * anywhere else in the doc — including adding, removing, or reordering a
391
+ * `cmp:generated` marker itself (structural, not generated content) — changes
392
+ * it, same as editing the spec.
393
+ * @param {string} root
394
+ * @returns {{ hash: string, fileCount: number, missing: string[] }}
395
+ */
396
+ export function hashArchitectureArtifact(root) {
397
+ const rows = [];
398
+ const missing = [];
399
+
400
+ try {
401
+ const specBytes = fs.readFileSync(path.join(root, ARCHITECTURE_SPEC_REL));
402
+ rows.push([ARCHITECTURE_SPEC_REL, createHash("sha256").update(specBytes).digest("hex")]);
403
+ } catch {
404
+ missing.push(ARCHITECTURE_SPEC_REL);
405
+ }
406
+
407
+ try {
408
+ const docRaw = fs.readFileSync(path.join(root, ARCH_DOC_REL_PATH), "utf8");
409
+ // Normalize line endings BEFORE stripping: the marker grammar
410
+ // (`arch-doc.mjs`'s MARKER_BLOCK_RE) matches a literal `\n` right after
411
+ // `-->`, so CRLF content would fail to match at all and nothing would be
412
+ // stripped — normalize first so the strip is EOL-independent, same as the
413
+ // hash itself.
414
+ const docNormalized = docRaw.replace(/\r\n/g, "\n");
415
+ const docStripped = stripGeneratedSections(docNormalized);
416
+ rows.push([ARCH_DOC_REL_PATH, createHash("sha256").update(docStripped, "utf8").digest("hex")]);
417
+ } catch {
418
+ missing.push(ARCH_DOC_REL_PATH);
419
+ }
420
+
421
+ // Code-unit sort for the same reason as hashArtifactFiles: hash order must
422
+ // not depend on the machine's locale.
423
+ rows.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
424
+ const overall = createHash("sha256");
425
+ for (const [relPath, fileSha] of rows) {
426
+ overall.update(`${relPath}\0${fileSha}\n`);
427
+ }
428
+ return { hash: overall.digest("hex"), fileCount: rows.length, missing };
429
+ }
430
+
431
+ /**
432
+ * Recompute one artifact's hash — `hashArchitectureArtifact` for `architecture`
433
+ * (spec + stripped doc, its own basis), `hashArtifactFiles(root, artifact.files)`
434
+ * for every other artifact (raw file bytes). The ONE dispatch point
435
+ * `resolveArtifactStatus`/`approveArtifact` both call, so the two never
436
+ * disagree about what "the architecture artifact's hash" means.
437
+ * @param {string} root
438
+ * @param {{id: string, files: string[]}} artifact
439
+ * @returns {{ hash: string, fileCount: number, missing: string[] }}
440
+ */
441
+ function computeArtifactHash(root, artifact) {
442
+ return artifact.id === "architecture" ? hashArchitectureArtifact(root) : hashArtifactFiles(root, artifact.files);
443
+ }
444
+
445
+ // ── State (qa/approvals.json) ─────────────────────────────────────────────────
446
+
447
+ /**
448
+ * Load qa/approvals.json. Absent or corrupt (unparsable JSON, wrong shape) is
449
+ * TOLERATED — returns the empty state, which resolves every artifact as
450
+ * "unreviewed" and every exemplar lookup to the default (`home`). Never throws.
451
+ *
452
+ * `exemplarFeature` is `undefined` when the key is absent or not a non-empty
453
+ * string — callers resolve the default (`getExemplarFeature`), never this
454
+ * function directly, so every ledger written before this key existed keeps
455
+ * meaning what it meant (GENESIS-FLOW-DESIGN.md §1).
456
+ * @param {string} root
457
+ * @returns {{ schema: string, artifacts: Array<{artifact: string, status: string, hash: (string|null), approvedAt: (string|null), mode?: string, reopenedAt?: string}>, exemplarFeature: (string|undefined) }}
458
+ */
459
+ export function loadApprovals(root) {
460
+ const empty = { schema: APPROVALS_SCHEMA, artifacts: [], exemplarFeature: undefined };
461
+ const p = path.join(root, APPROVALS_REL_PATH);
462
+ let raw;
463
+ try {
464
+ raw = fs.readFileSync(p, "utf8");
465
+ } catch {
466
+ return empty;
467
+ }
468
+ try {
469
+ const parsed = JSON.parse(raw);
470
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.artifacts)) return empty;
471
+ const exemplarFeature =
472
+ typeof parsed.exemplarFeature === "string" && parsed.exemplarFeature.trim() !== ""
473
+ ? parsed.exemplarFeature.trim()
474
+ : undefined;
475
+ return { schema: parsed.schema ?? APPROVALS_SCHEMA, artifacts: parsed.artifacts, exemplarFeature };
476
+ } catch {
477
+ return empty;
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Write qa/approvals.json (deterministic key order, trailing newline).
483
+ * `exemplarFeature` is included only when the caller explicitly passes one
484
+ * (undefined is omitted, never written as a literal `null`/`"undefined"`) — every
485
+ * internal transition (approveArtifact, seedUnreviewed, approveAllDefaults,
486
+ * reopenArtifact) reloads and threads the CURRENT value through so a write never
487
+ * silently drops a previously-configured exemplar.
488
+ * @param {string} root
489
+ * @param {{ artifacts: Array<object>, exemplarFeature?: string }} state
490
+ */
491
+ export function saveApprovals(root, state) {
492
+ const p = path.join(root, APPROVALS_REL_PATH);
493
+ fs.mkdirSync(path.dirname(p), { recursive: true });
494
+ const out = { schema: APPROVALS_SCHEMA, artifacts: state.artifacts };
495
+ if (state.exemplarFeature !== undefined) out.exemplarFeature = state.exemplarFeature;
496
+ fs.writeFileSync(p, `${JSON.stringify(out, null, 2)}\n`);
497
+ }
498
+
499
+ /**
500
+ * The configured exemplar feature's lowercase name (the package-segment form,
501
+ * e.g. `"home"`, `"favorites"`) — `qa/approvals.json`'s top-level
502
+ * `exemplarFeature` key, defaulting to `"home"` when absent (GENESIS-FLOW-DESIGN.md
503
+ * §1). This is the ONE function both `resolveExemplarNames` (registry) and
504
+ * qa/scaffold-feature.mjs (clone-source resolution) call — never read the raw key
505
+ * directly, so the default lives in exactly one place.
506
+ * @param {string} root
507
+ * @returns {string}
508
+ */
509
+ export function getExemplarFeature(root) {
510
+ return loadApprovals(root).exemplarFeature ?? "home";
511
+ }
512
+
513
+ /**
514
+ * Seed one artifact as unreviewed if it isn't already recorded. Idempotent —
515
+ * a second call for the same id is a no-op. Used by qa/scaffold-feature.mjs to
516
+ * seed a new feature's spec (create-if-missing, tolerant when absent — this
517
+ * never throws, so a stamp is never blocked by the approvals ledger).
518
+ * @param {string} root
519
+ * @param {string} artifactId
520
+ * @returns {{ added: boolean }}
521
+ */
522
+ export function seedUnreviewed(root, artifactId) {
523
+ const state = loadApprovals(root);
524
+ if (state.artifacts.some((a) => a.artifact === artifactId)) return { added: false };
525
+ state.artifacts.push({ artifact: artifactId, status: "unreviewed", hash: null, approvedAt: null });
526
+ saveApprovals(root, state);
527
+ return { added: true };
528
+ }
529
+
530
+ // ── Status resolution ─────────────────────────────────────────────────────────
531
+
532
+ function shortHash(hash) {
533
+ return hash ? hash.slice(0, 8) : "none";
534
+ }
535
+
536
+ /**
537
+ * Resolve one artifact's live status: recompute its hash now and compare
538
+ * against the stored record (if any).
539
+ * - no stored record, or stored status !== "approved"/"reopened" -> "unreviewed"
540
+ * - stored status === "reopened" -> "reopened", UNCONDITIONALLY — a reopened
541
+ * artifact never re-derives "changed-since-approval" from further edits (there
542
+ * is no live approval to compare against once reopened; it's fluid again by
543
+ * definition until the next real approveArtifact call). This is the
544
+ * sanctioned-redesign-vs-drift asymmetry the reopen mechanic exists for
545
+ * (GENESIS-FLOW-DESIGN.md §2): only an `approved` artifact can go stale.
546
+ * - approved + hash still matches (over >0 files) -> "approved"
547
+ * - approved + hash no longer matches -> "changed-since-approval"
548
+ * - approved + artifact NOW unresolvable (0 files, or an incomplete kotlin
549
+ * file set) -> "changed-since-approval", UNCONDITIONALLY — even if the
550
+ * stored hash equals the recompute (a hand-written or legacy vacuous
551
+ * approval over the degraded set). An approval that covers none (or only a
552
+ * fraction) of what the artifact governs attests nothing and must never
553
+ * read as PASS.
554
+ * `resolvable` is false when the artifact resolves to 0 files right now OR its
555
+ * file set is incomplete (kotlin roots unresolvable — see listGovernedArtifacts).
556
+ * `mode` (e.g. `"defaults-accepted"`) and `reopenedAt` are surfaced only when the
557
+ * stored record actually carries them — never as an explicit `undefined` key, so
558
+ * structural equality checks against a plain unreviewed/approved status shape
559
+ * still hold.
560
+ * @returns {{id: string, label: string, status: string, hash: string, storedHash: (string|null), approvedAt: (string|null), fileCount: number, missing: string[], resolvable: boolean, mode?: string, reopenedAt?: string}}
561
+ */
562
+ export function resolveArtifactStatus(root, artifact, storedRecord) {
563
+ const recomputed = computeArtifactHash(root, artifact);
564
+ const resolvable = recomputed.fileCount > 0 && artifact.complete !== false;
565
+
566
+ if (storedRecord && storedRecord.status === "reopened") {
567
+ return {
568
+ id: artifact.id,
569
+ label: artifact.label,
570
+ status: "reopened",
571
+ hash: recomputed.hash,
572
+ storedHash: storedRecord.hash ?? null,
573
+ approvedAt: storedRecord.approvedAt ?? null,
574
+ fileCount: recomputed.fileCount,
575
+ missing: recomputed.missing,
576
+ resolvable,
577
+ reopenedAt: storedRecord.reopenedAt,
578
+ };
579
+ }
580
+
581
+ if (!storedRecord || storedRecord.status !== "approved") {
582
+ return {
583
+ id: artifact.id,
584
+ label: artifact.label,
585
+ status: "unreviewed",
586
+ hash: recomputed.hash,
587
+ storedHash: null,
588
+ approvedAt: null,
589
+ fileCount: recomputed.fileCount,
590
+ missing: recomputed.missing,
591
+ resolvable,
592
+ };
593
+ }
594
+ const changed = !resolvable || storedRecord.hash !== recomputed.hash;
595
+ return {
596
+ id: artifact.id,
597
+ label: artifact.label,
598
+ status: changed ? "changed-since-approval" : "approved",
599
+ hash: recomputed.hash,
600
+ storedHash: storedRecord.hash,
601
+ approvedAt: storedRecord.approvedAt,
602
+ fileCount: recomputed.fileCount,
603
+ missing: recomputed.missing,
604
+ resolvable,
605
+ ...(storedRecord.mode ? { mode: storedRecord.mode } : {}),
606
+ };
607
+ }
608
+
609
+ /**
610
+ * Every governed artifact's live status, right now.
611
+ * @param {string} root
612
+ * @returns {Array<ReturnType<typeof resolveArtifactStatus>>}
613
+ */
614
+ export function getApprovalStatuses(root) {
615
+ const registry = listGovernedArtifacts(root);
616
+ const state = loadApprovals(root);
617
+ const byId = new Map(state.artifacts.map((a) => [a.artifact, a]));
618
+ return registry.map((artifact) => resolveArtifactStatus(root, artifact, byId.get(artifact.id)));
619
+ }
620
+
621
+ // ── Transitions ────────────────────────────────────────────────────────────────
622
+
623
+ /**
624
+ * Record an approval: recompute the artifact's hash now, stamp the time,
625
+ * upsert into qa/approvals.json. A fresh record always REPLACES the stored one
626
+ * wholesale (never merges) — so a real approval on a previously
627
+ * defaults-accepted or reopened artifact automatically clears `mode` and
628
+ * `reopenedAt`, with no separate "clear" step needed.
629
+ *
630
+ * REFUSES an unresolvable artifact — one that resolves to 0 files, or whose
631
+ * kotlin-rooted file set could not be resolved at all (`complete: false`). An
632
+ * approval over 0 files would record the empty-input sha256; an approval over
633
+ * a partial set would attest only a fraction of what the artifact governs.
634
+ * Both are silently vacuous — the exact failure mode this harness exists to
635
+ * kill (evidence must attest execution). Refusal cases: the project package is
636
+ * unresolvable (raw template / pre-stamp tree), the artifact's expected files
637
+ * are all missing on disk, or (a dynamic artifact, e.g. `components`) nothing
638
+ * currently matches its pattern.
639
+ * @param {string} root
640
+ * @param {string} artifactId
641
+ * @param {{mode?: string}} [options] `mode` (e.g. `"defaults-accepted"`) is
642
+ * stamped onto the record when the express lane approves a resolvable-but-
643
+ * unshaped artifact (GENESIS-FLOW-DESIGN.md §2). Omitted for a normal/real
644
+ * approval.
645
+ * @returns {{ok: true, artifact: string, hash: string, approvedAt: string, mode?: string} | {ok: false, reason: string}}
646
+ */
647
+ export function approveArtifact(root, artifactId, options = {}) {
648
+ const registry = listGovernedArtifacts(root);
649
+ const artifact = registry.find((a) => a.id === artifactId);
650
+ if (!artifact) {
651
+ const known = registry.map((a) => a.id).join(", ") || "(none — no governed artifacts resolved in this project)";
652
+ return { ok: false, reason: `unknown artifact "${artifactId}" — valid ids: ${known}` };
653
+ }
654
+ const resolved = computeArtifactHash(root, artifact);
655
+ if (artifact.complete === false) {
656
+ return {
657
+ ok: false,
658
+ reason:
659
+ `cannot approve "${artifactId}" — its file set cannot be fully resolved: the kotlin-rooted files are unresolvable because ` +
660
+ "the project package is not resolvable from composeApp/build.gradle.kts (likely the raw template or a pre-stamp tree — " +
661
+ `run this in a generated project); only ${resolved.fileCount} file(s) resolved. ` +
662
+ "A partial or empty approval is vacuous (it attests nothing for the unresolved files) and is refused.",
663
+ };
664
+ }
665
+ if (resolved.fileCount === 0) {
666
+ const reason =
667
+ artifact.files.length === 0
668
+ ? `cannot approve "${artifactId}" — it resolves to 0 files; nothing currently matches this artifact's pattern (nothing to approve yet). An approval over zero files is vacuous (the empty-input hash attests nothing) and is refused.`
669
+ : `cannot approve "${artifactId}" — it resolves to 0 files; its expected files are all missing on disk: ` +
670
+ `${artifact.files.join(", ")}. An approval over zero files is vacuous (the empty-input hash attests nothing) and is refused.`;
671
+ return { ok: false, reason };
672
+ }
673
+ const state = loadApprovals(root);
674
+ const others = state.artifacts.filter((a) => a.artifact !== artifactId);
675
+ const approvedAt = new Date().toISOString();
676
+ const record = { artifact: artifactId, status: "approved", hash: resolved.hash, approvedAt };
677
+ if (options.mode) record.mode = options.mode;
678
+ others.push(record);
679
+ saveApprovals(root, { artifacts: others, exemplarFeature: state.exemplarFeature });
680
+ return { ok: true, artifact: artifactId, hash: resolved.hash, approvedAt, ...(options.mode ? { mode: options.mode } : {}) };
681
+ }
682
+
683
+ /**
684
+ * Express lane (GENESIS-FLOW-DESIGN.md §2): approve every currently-resolvable,
685
+ * not-yet-approved governed artifact in one pass, each stamped
686
+ * `mode: "defaults-accepted"`. An artifact already `"approved"` (real OR a prior
687
+ * defaults-accepted run) is left untouched — the express lane never overwrites a
688
+ * standing approval, shaped or not. Unresolvable artifacts are SKIPPED with the
689
+ * exact refusal `approveArtifact` would have printed (never a silent skip).
690
+ * @param {string} root
691
+ * @returns {{ok: true, approved: string[], skipped: Array<{id: string, reason: string}>}}
692
+ */
693
+ export function approveAllDefaults(root) {
694
+ const registry = listGovernedArtifacts(root);
695
+ const state = loadApprovals(root);
696
+ const byId = new Map(state.artifacts.map((a) => [a.artifact, a]));
697
+ const approved = [];
698
+ const skipped = [];
699
+ for (const artifact of registry) {
700
+ const live = resolveArtifactStatus(root, artifact, byId.get(artifact.id));
701
+ if (live.status === "approved") continue; // already settled — never overwritten by the express lane
702
+ const result = approveArtifact(root, artifact.id, { mode: "defaults-accepted" });
703
+ if (result.ok) approved.push(artifact.id);
704
+ else skipped.push({ id: artifact.id, reason: result.reason });
705
+ }
706
+ return { ok: true, approved, skipped };
707
+ }
708
+
709
+ /**
710
+ * Reopen for redesign (GENESIS-FLOW-DESIGN.md §2): move an `approved` artifact
711
+ * (real or defaults-accepted — both are status `"approved"`) to `"reopened"`,
712
+ * recording `reopenedAt` and clearing any `mode` (a reopened artifact is fluid
713
+ * again, not "the defaults, still"). REFUSES an unknown id, and refuses any
714
+ * artifact whose LIVE status is not `"approved"` — reopening the unreviewed, the
715
+ * already-reopened, or a changed-since-approval artifact is meaningless (there is
716
+ * nothing sanctioned to walk back from).
717
+ * @param {string} root
718
+ * @param {string} artifactId
719
+ * @returns {{ok: true, artifact: string, reopenedAt: string} | {ok: false, reason: string}}
720
+ */
721
+ export function reopenArtifact(root, artifactId) {
722
+ const registry = listGovernedArtifacts(root);
723
+ const artifact = registry.find((a) => a.id === artifactId);
724
+ if (!artifact) {
725
+ const known = registry.map((a) => a.id).join(", ") || "(none — no governed artifacts resolved in this project)";
726
+ return { ok: false, reason: `unknown artifact "${artifactId}" — valid ids: ${known}` };
727
+ }
728
+ const state = loadApprovals(root);
729
+ const stored = state.artifacts.find((a) => a.artifact === artifactId);
730
+ const live = resolveArtifactStatus(root, artifact, stored);
731
+ if (live.status !== "approved") {
732
+ return {
733
+ ok: false,
734
+ reason: `cannot reopen "${artifactId}" — it is "${live.status}", not "approved". Only an approved artifact (shaped or defaults-accepted) can be reopened for redesign.`,
735
+ };
736
+ }
737
+ const others = state.artifacts.filter((a) => a.artifact !== artifactId);
738
+ const reopenedAt = new Date().toISOString();
739
+ const record = { artifact: artifactId, status: "reopened", hash: stored.hash, approvedAt: stored.approvedAt, reopenedAt };
740
+ others.push(record);
741
+ saveApprovals(root, { artifacts: others, exemplarFeature: state.exemplarFeature });
742
+ // `artifact` is the ID STRING — the same convention approveArtifact returns
743
+ // (one library, one shape; the console bridge relies on the symmetry).
744
+ return { ok: true, artifact: artifactId, reopenedAt };
745
+ }
746
+
747
+ // ── The verify-lane gate ─────────────────────────────────────────────────────
748
+
749
+ /**
750
+ * The `approvals` verify-lane gate's pure decision function (qa/verify.mjs
751
+ * wraps this in the step's name/duration bookkeeping — same split as
752
+ * compareTokenDrift/qa/lib/token-drift.mjs).
753
+ *
754
+ * Aggregate verdict:
755
+ * - any artifact "changed-since-approval" -> FAIL (names each + the
756
+ * re-approval command — NEVER names a merely-reopened artifact; see below)
757
+ * - else any artifact "unreviewed"/"reopened" -> SKIP (warns, non-blocking)
758
+ * - else (all approved + matching) -> PASS
759
+ *
760
+ * The sanctioned-redesign-vs-drift asymmetry (GENESIS-FLOW-DESIGN.md §2) lives
761
+ * right here: `reopened` is grouped with `unreviewed` as non-blocking pending
762
+ * work, `changed-since-approval` is checked FIRST and returns immediately — so a
763
+ * run with one reopened artifact and one genuinely drifted (changed-since-
764
+ * approval) artifact FAILs, and the FAIL reason names only the drifted one.
765
+ * @param {string} root
766
+ * @returns {{verdict: "PASS"|"FAIL"|"SKIP", reason: (string|undefined), statuses: Array<object>}}
767
+ */
768
+ export function evaluateApprovalsGate(root) {
769
+ const statuses = getApprovalStatuses(root);
770
+ const mismatched = statuses.filter((s) => s.status === "changed-since-approval");
771
+ const pending = statuses.filter((s) => s.status === "unreviewed" || s.status === "reopened");
772
+
773
+ if (mismatched.length > 0) {
774
+ const lines = ["Approval invalidated — a governed artifact changed after sign-off:"];
775
+ for (const s of mismatched) {
776
+ if (!s.resolvable) {
777
+ lines.push(
778
+ ` [${s.id}] ${s.label} — approved at ${shortHash(s.storedHash)}, but its files no longer fully resolve (${s.fileCount} present — deleted or unresolvable). Restore the files, then re-approve if the change was intended (approval over an unresolved file set is refused).`,
779
+ );
780
+ } else {
781
+ lines.push(
782
+ ` [${s.id}] ${s.label} — approved at ${shortHash(s.storedHash)}, now ${shortHash(s.hash)}. Re-approve: node qa/approve.mjs ${s.id}`,
783
+ );
784
+ }
785
+ }
786
+ return { verdict: "FAIL", reason: lines.join("\n"), statuses };
787
+ }
788
+
789
+ if (pending.length > 0) {
790
+ const lines = ["Governed artifacts awaiting human approval (non-blocking — approve when ready):"];
791
+ for (const s of pending) {
792
+ if (s.status === "reopened") {
793
+ lines.push(
794
+ ` [${s.id}] ${s.label} — reopened for redesign at ${s.reopenedAt} (non-blocking until re-approved). Approve: node qa/approve.mjs ${s.id}`,
795
+ );
796
+ } else if (!s.resolvable) {
797
+ lines.push(` [${s.id}] ${s.label} — unreviewed, currently unresolvable (${s.fileCount} of expected files resolved) — not approvable in this tree.`);
798
+ } else {
799
+ lines.push(` [${s.id}] ${s.label} — unreviewed. Approve: node qa/approve.mjs ${s.id}`);
800
+ }
801
+ }
802
+ return { verdict: "SKIP", reason: lines.join("\n"), statuses };
803
+ }
804
+
805
+ return { verdict: "PASS", reason: undefined, statuses };
806
+ }