rungate 0.4.0 → 0.4.1

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.
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Audit by rehearsal (#398).
3
+ *
4
+ * `rungate scaffold <path>` without `--fix` called itself a preview and
5
+ * reported `0 created, 0 replaced, 0 skipped, 0 refused` on a tree that
6
+ * `--fix` then rewrote — 28 paths on this repo's own fixture, 16 on agentgrit.
7
+ * The cause was structural rather than a missing branch: audit was four
8
+ * `existsSync` checks and fix was twenty-five write steps, two bodies of code
9
+ * sharing nothing. Two implementations of the same question can only agree by
10
+ * someone keeping them in step by hand, and nobody was.
11
+ *
12
+ * `--fix` is the DESTRUCTIVE mode — #370 is `--fix` truncating
13
+ * `.claude/rules/checks-must-be-able-to-fail.md` from 262 lines to 65 — so
14
+ * audit is the one thing standing between a consumer and that damage. A
15
+ * preview that under-reports is worse than no preview at all, because it
16
+ * turns "I checked first" into false confidence.
17
+ *
18
+ * ## So audit does not predict what fix would do. It does it, somewhere else.
19
+ *
20
+ * Clone the tree, run the REAL steps against the clone, report what they say,
21
+ * throw the clone away. The two modes then agree by construction rather than
22
+ * by maintenance, and a step added later cannot forget its audit branch
23
+ * because there is no audit branch to forget.
24
+ *
25
+ * On APFS `cp -Rc` is a copy-on-write clone — measured at 0.2s for this repo —
26
+ * so the cost is bounded by metadata rather than by tree size. Where clonefile
27
+ * is unsupported it falls back to a real copy, which is slower and still
28
+ * correct; `rehearsalCloneCommand` reports which one ran so a slow audit is
29
+ * explicable rather than mysterious.
30
+ *
31
+ * ## The two steps that must not be rehearsed
32
+ *
33
+ * A rehearsal is only safe while every step it runs stays inside the clone.
34
+ * Two do not, and both would do real damage from a mode whose entire promise
35
+ * is that it writes nothing:
36
+ *
37
+ * - `deployHooksToConsumers` resolves `consumer.startsWith("/")` and writes to
38
+ * absolute paths in OTHER repositories (`steps.ts:2222`). Rehearsing it
39
+ * would deploy hooks to every consumer on the machine during a preview.
40
+ * - `postScaffoldCommit` creates a commit. In a clone whose `.git` is a file
41
+ * pointing back at the real repository — which is what a git worktree's is —
42
+ * that commit would land in the original.
43
+ *
44
+ * They are named here rather than skipped inline so the exclusion is one list
45
+ * a test can read, and so each one carries the reason it is on it. An
46
+ * exclusion without a stated reason is indistinguishable from an oversight,
47
+ * and the next person to read it cannot tell whether removing it is safe.
48
+ */
49
+
50
+ import { spawnSync } from "child_process";
51
+ import { mkdtempSync, rmSync, lstatSync, readdirSync, readlinkSync, realpathSync } from "fs";
52
+ import { tmpdir } from "os";
53
+ import { join, resolve, sep } from "path";
54
+
55
+ /**
56
+ * Steps a rehearsal must not run, and why. Keys are the exported function
57
+ * names in `lib/scaffold/steps.ts`; `test/scaffold-audit-agreement.test.ts`
58
+ * asserts each one still exists, so a rename cannot silently empty this list
59
+ * and re-enable the step.
60
+ */
61
+ export const STEPS_NOT_REHEARSED: ReadonlyMap<string, string> = new Map([
62
+ [
63
+ "deployHooksToConsumers",
64
+ "writes to absolute paths in other repositories, which a preview must never touch",
65
+ ],
66
+ [
67
+ "postScaffoldCommit",
68
+ "creates a commit, and a clone's .git may point back at the real repository",
69
+ ],
70
+ ]);
71
+
72
+ /** Directories never worth cloning: huge, regenerable, or another tree entirely. */
73
+ export const REHEARSAL_EXCLUDES: readonly string[] = [
74
+ "node_modules",
75
+ ".claude/worktrees",
76
+ ];
77
+
78
+ export interface Rehearsal {
79
+ /** The clone the steps ran against. Always inside the OS temp directory. */
80
+ dir: string;
81
+ /** The mkdtemp that owns `dir`. Tracked so cleanup never walks `..`. */
82
+ parent: string;
83
+ /** `clone` when copy-on-write was used, `copy` when it fell back. */
84
+ method: "clone" | "copy";
85
+ }
86
+
87
+ /**
88
+ * Symlinks in the clone whose target resolves outside it.
89
+ *
90
+ * **A rehearsal is only a rehearsal while every write lands in the copy, and
91
+ * a symlink is a hole straight through the floor.** `cp -R` preserves
92
+ * symlinks rather than following them, so a clone of a tree containing
93
+ * `AGENTS.md -> /elsewhere/AGENTS.md` carries a link to the ORIGINAL file,
94
+ * and the first step that writes `AGENTS.md` overwrites it. Reproduced
95
+ * directly: write through a cloned symlink, read the original, see the new
96
+ * bytes.
97
+ *
98
+ * That is #370's damage — scaffold destroying a real file — arriving through
99
+ * the preview built to prevent it, and in the one mode whose entire promise
100
+ * is that it writes nothing. Found by the commit security review.
101
+ *
102
+ * Reported rather than deleted. Removing the links would let the audit
103
+ * proceed over a tree that is not the consumer's, so it would answer a
104
+ * question nobody asked; `.claude/rules/config-access.md` is the governing
105
+ * idea — a reading that cannot be taken safely is UNMEASURED, and UNMEASURED
106
+ * is not SKIP.
107
+ */
108
+ export function escapingSymlinks(dir: string): string[] {
109
+ const root = realpathSync(dir);
110
+ const out: string[] = [];
111
+ const walk = (rel: string) => {
112
+ let entries;
113
+ try {
114
+ entries = readdirSync(join(root, rel), { withFileTypes: true });
115
+ } catch (err) {
116
+ // NOT `return`. A directory we cannot read is a directory whose
117
+ // symlinks we did not check, and a check that skips what it cannot
118
+ // see reports the same empty list as a tree with nothing wrong —
119
+ // `.claude/rules/checks-must-be-able-to-fail.md`'s fail-open shape,
120
+ // found by the commit security review. Unreadable counts as
121
+ // escaping, so the audit refuses rather than previewing blind.
122
+ out.push(`${rel || "."} (unreadable: ${(err as Error).message})`);
123
+ return;
124
+ }
125
+ for (const e of entries) {
126
+ const child = rel ? join(rel, e.name) : e.name;
127
+ if (e.isSymbolicLink()) {
128
+ if (linkEscapes(root, child)) out.push(child);
129
+ } else if (e.isDirectory()) {
130
+ walk(child);
131
+ }
132
+ }
133
+ };
134
+ walk("");
135
+ return out.sort();
136
+ }
137
+
138
+ /**
139
+ * Does the link at `root/rel` resolve outside `root`?
140
+ *
141
+ * `realpathSync` is right for a link whose target exists and wrong for one
142
+ * whose target does not: it throws, and the first version treated a throw as
143
+ * "resolves to the link's own path", i.e. inside the root, i.e. safe. A
144
+ * DANGLING link to `/etc/thing` was therefore not flagged — and a step that
145
+ * writes through it creates `/etc/thing`. A dangling link is the more
146
+ * dangerous case, not the less, because writing is exactly what makes the
147
+ * target exist. Found by the commit security review.
148
+ */
149
+ function linkEscapes(root: string, rel: string): boolean {
150
+ const link = join(root, rel);
151
+ try {
152
+ const target = realpathSync(link);
153
+ return target !== root && !target.startsWith(root + sep);
154
+ } catch {
155
+ // Unresolvable: fall back to the literal target, resolved against the
156
+ // link's own directory the way the kernel would.
157
+ try {
158
+ const literal = resolve(join(link, ".."), readlinkSync(link));
159
+ return literal !== root && !literal.startsWith(root + sep);
160
+ } catch {
161
+ // Cannot even read the link. Unknown is not safe.
162
+ return true;
163
+ }
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Copy `root` somewhere disposable.
169
+ *
170
+ * `.git` is copied rather than skipped: five steps shell out to
171
+ * `git -C <root>` for the origin URL, a file's last-commit date and
172
+ * `status --porcelain`, and a clone with no repository would make those steps
173
+ * take different branches than they will under `--fix` — which is the exact
174
+ * disagreement this module exists to remove.
175
+ */
176
+ export function cloneForRehearsal(root: string): Rehearsal {
177
+ const parent = mkdtempSync(join(tmpdir(), "rungate-rehearsal-"));
178
+ const dir = join(parent, "tree");
179
+ const fail = (why: string): never => {
180
+ rmSync(parent, { recursive: true, force: true });
181
+ throw new Error(`audit did NOT run: ${why}`);
182
+ };
183
+
184
+ // `-c` asks for an APFS clonefile. It fails on filesystems that cannot do
185
+ // it, so the fallback is explicit rather than a silent slow path.
186
+ //
187
+ // Both attempts go through `attemptCopy`, which clears the destination
188
+ // first. A failed `cp` may have copied some of the tree before giving up,
189
+ // and falling back on top of that leaves a PARTIAL clone — the steps then
190
+ // run over a tree missing files, report less than `--fix` will do, and
191
+ // look like a clean preview, which is this module's whole subject. The
192
+ // first draft cleared only in the fallback, and the mutation battery
193
+ // scored that guard 0: `cp -Rc` succeeds on every machine the tests run
194
+ // on, so no test could ever reach the second branch. One shared helper
195
+ // removes the ordering rather than testing it.
196
+ let method: Rehearsal["method"] = "clone";
197
+ if (attemptCopy(["-Rc", root, dir], 300_000) !== 0) {
198
+ if (attemptCopy(["-R", root, dir], 600_000) !== 0) {
199
+ return fail("the tree could not be copied");
200
+ }
201
+ method = "copy";
202
+ }
203
+
204
+ // Pruning happens through `rmSync(..., { recursive: true })`, which
205
+ // follows a symlinked PARENT. `.claude/worktrees` in a tree where
206
+ // `.claude -> /real/.claude` therefore resolves outside the clone and
207
+ // deletes the consumer's real worktrees — a destructive path traversal
208
+ // performed by the mode that promises to write nothing. Found by the
209
+ // commit security review.
210
+ //
211
+ // So nothing is deleted through a symlink. Each excluded path is walked
212
+ // component by component; the moment a component is a link, the link
213
+ // itself is unlinked (never followed) and the walk stops. `node_modules`
214
+ // being a symlink is the common case — the pre-push hook makes one — and
215
+ // must stay cheap rather than refusing the audit.
216
+ for (const rel of REHEARSAL_EXCLUDES) {
217
+ prunePathWithoutFollowingLinks(dir, rel);
218
+ }
219
+
220
+ const missing = missingTopLevel(root, dir);
221
+ if (missing.length > 0) {
222
+ return fail(`the copy is incomplete — ${missing.length} top-level entr(ies) missing: ${missing.slice(0, 5).join(", ")}`);
223
+ }
224
+
225
+ const escaping = escapingSymlinks(dir);
226
+ if (escaping.length > 0) {
227
+ return fail(
228
+ `the tree contains ${escaping.length} symlink(s) pointing outside it, and a step writing through one ` +
229
+ `would modify the real file rather than the copy — which is the damage a preview exists to prevent (#370). ` +
230
+ `Offending paths: ${escaping.slice(0, 5).join(", ")}${escaping.length > 5 ? ", …" : ""}. ` +
231
+ `Re-run with --fix if you intend those writes, or replace the symlinks with real files.`,
232
+ );
233
+ }
234
+
235
+ return { dir, parent, method };
236
+ }
237
+
238
+ /**
239
+ * Copy into `dir`, having first removed whatever is there.
240
+ *
241
+ * The clear is unconditional so there is one code path rather than two with
242
+ * an ordering between them. See `cloneForRehearsal` for why.
243
+ */
244
+ function attemptCopy(args: string[], timeout: number): number {
245
+ const dest = args[args.length - 1]!;
246
+ rmSync(dest, { recursive: true, force: true });
247
+ return spawnSync("cp", args, { encoding: "utf-8", timeout }).status ?? 1;
248
+ }
249
+
250
+ /**
251
+ * Top-level entries present in `root` but absent from its copy at `dir`.
252
+ *
253
+ * The copy has to BE the tree, not most of it. Compared at the top level
254
+ * only — a full walk would cost more than the clone did — which is enough to
255
+ * catch a truncated copy that exited 0.
256
+ *
257
+ * **Only a WHOLE top-level exclude is forgiven.** `.claude/worktrees` prunes
258
+ * a child, so `.claude` itself must still be present; matching on the first
259
+ * path component instead excuses a missing `.claude` entirely, which is the
260
+ * under-reporting this module exists to stop. Exported so that reading is one
261
+ * binding a test can feed a genuinely partial copy — the first version of
262
+ * SC-1514 re-implemented this comparison inside the test and therefore never
263
+ * ran the real one, and the mutation battery scored it 0.
264
+ */
265
+ export function missingTopLevel(root: string, dir: string): string[] {
266
+ const forgiven = new Set(REHEARSAL_EXCLUDES.filter(x => !x.includes("/")));
267
+ const got = new Set(readdirSync(dir));
268
+ return readdirSync(root).filter(n => !forgiven.has(n) && !got.has(n));
269
+ }
270
+
271
+ /**
272
+ * Remove `root/rel`, never passing through a symlink on the way.
273
+ *
274
+ * Two different answers, depending on WHERE the link is:
275
+ *
276
+ * - **The link is the path itself** (`node_modules -> /elsewhere/mods`):
277
+ * unlink it. `rmSync` on a link removes the link and leaves the target
278
+ * alone, and an excluded directory is one we did not want in the clone
279
+ * anyway. This is the common case — the pre-push hook makes exactly this
280
+ * link — and it has to stay cheap rather than refusing the audit.
281
+ *
282
+ * - **The link is an ANCESTOR** (`.claude -> /real/.claude`, pruning
283
+ * `.claude/worktrees`): leave it entirely alone. Unlinking it would throw
284
+ * away `.claude` — rules, agents, config — and the steps would then run
285
+ * over a tree missing the directory half of them read, reporting less than
286
+ * `--fix` will do. That is #398 itself, reintroduced by its own fix. It is
287
+ * also invisible to the completeness check, which cannot ask for `.claude`
288
+ * back while `.claude/worktrees` is on the exclude list.
289
+ *
290
+ * Deleting through it is worse still: `rmSync(..., { recursive: true })`
291
+ * follows a symlinked parent, so the consumer's real worktrees go. So
292
+ * neither — the link stays, and `escapingSymlinks` refuses the audit a
293
+ * moment later because an ancestor pointing out of the clone is exactly
294
+ * what it is for. Found by the commit security review.
295
+ */
296
+ function prunePathWithoutFollowingLinks(root: string, rel: string): void {
297
+ let current = root;
298
+ const parts = rel.split("/").filter(Boolean);
299
+ for (let i = 0; i < parts.length; i++) {
300
+ current = join(current, parts[i]!);
301
+ let st;
302
+ try { st = lstatSync(current); } catch { return; } // absent: nothing to prune
303
+ const last = i === parts.length - 1;
304
+ if (st.isSymbolicLink()) {
305
+ if (last) rmSync(current, { force: true });
306
+ return; // an ancestor link: prune nothing, and let the refusal catch it
307
+ }
308
+ if (!last && !st.isDirectory()) return;
309
+ }
310
+ rmSync(current, { recursive: true, force: true });
311
+ }
312
+
313
+ /** Throw the clone away. Safe to call twice. */
314
+ export function discardRehearsal(r: Rehearsal): void {
315
+ // `r.parent`, not `join(r.dir, "..")`. Deriving a deletion target by
316
+ // walking up from a path is how a cleanup ends up removing something it
317
+ // does not own; the owner is recorded at creation instead. Leaving the
318
+ // mkdtemp behind is the leak #437 is about, so it is the parent that goes.
319
+ rmSync(r.parent, { recursive: true, force: true });
320
+ }
321
+
322
+ /**
323
+ * The line audit prints so a reader knows the report was produced by running
324
+ * the real thing, not by predicting it — and knows what it did not run.
325
+ */
326
+ export function rehearsalNotice(r: Rehearsal): string {
327
+ const skipped = [...STEPS_NOT_REHEARSED.keys()].join(", ");
328
+ return `Mode: audit — rehearsed against a ${r.method} of the tree, which was then discarded. ` +
329
+ `Not rehearsed: ${skipped}. Pass --fix to apply.`;
330
+ }
@@ -18,7 +18,8 @@ import { buildAgentMeta, DEFAULT_AGENT_META } from "../create-brief";
18
18
  import { buildDefaultRoles, buildDefaultHooks } from "./defaults";
19
19
  import { mergeManagedWorkflow } from "./managed-workflow";
20
20
  import { PRE_PUSH_MANAGED_MARKER, prePushHookScript } from "./pre-push-hook";
21
- import { tryLoadRungateConfig } from "../config-loader";
21
+ import { loadComplianceConfig, tryLoadRungateConfig } from "../config-loader";
22
+ import { organizeProjectReport } from "../organize";
22
23
  import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute, Category } from "../generators/types";
23
24
  import { tier1Ere } from "../secret-patterns";
24
25
  import { healthPathIn } from "../liveness-contradiction";
@@ -1298,18 +1299,16 @@ function writeDirectoryStructure(
1298
1299
  * so no later scaffold ever corrected it. Running this step last is what makes
1299
1300
  * that skip safe — the content it preserves is now right from run 1.
1300
1301
  */
1301
- export function generateCodeMapStep(root: string, actions: string[], opts?: { fix?: boolean; dryRun?: boolean }): void {
1302
- const fixMode = opts?.fix ?? !opts?.dryRun;
1302
+ export function generateCodeMapStep(root: string, actions: string[]): void {
1303
+ // No dry-run branch. It reported `GAP: CODE-MAP.md missing` and nothing
1304
+ // else — one of the four `existsSync` checks that stood in for twenty-five
1305
+ // write steps and made audit report 0 changes on a tree `--fix` rewrote in
1306
+ // 28 places. #398 replaced prediction with rehearsal: audit runs THIS,
1307
+ // against a throwaway clone, and reports `GENERATED: CODE-MAP.md` because
1308
+ // that is what happened. Reachable from one caller, which has always passed
1309
+ // fix mode, so the branch was dead as well as wrong.
1303
1310
  const codeMapPath = join(root, "CODE-MAP.md");
1304
1311
 
1305
- // In dry-run/non-fix mode, only report gaps
1306
- if (!fixMode) {
1307
- if (!existsSync(codeMapPath)) {
1308
- actions.push("GAP: CODE-MAP.md missing — run with --fix to generate");
1309
- }
1310
- return;
1311
- }
1312
-
1313
1312
  // Check staleness
1314
1313
  if (existsSync(codeMapPath)) {
1315
1314
  const content = readFileSync(codeMapPath, "utf-8");
@@ -2492,6 +2491,56 @@ export function addPaiHarnessDevDep(root: string, actions: string[], version?: s
2492
2491
  actions.push("UPDATED: package.json (rungate devDep)");
2493
2492
  }
2494
2493
 
2494
+ /**
2495
+ * Report what `organizeProject` would adopt, without adopting it (#442).
2496
+ *
2497
+ * `organizeProject` had exactly one caller and it was a human running
2498
+ * `scripts/organize-project.ts`. Nothing in scaffold, ship or any hook
2499
+ * invoked it, so re-scaffolding a project — the thing people expected to
2500
+ * trigger adoption — could not. A feature nothing invokes is a feature that
2501
+ * has never fired, and this one never had.
2502
+ *
2503
+ * DRY-RUN, always. Discovery stops requiring prior knowledge that the
2504
+ * feature exists; adoption stays something a person chooses. The step writes
2505
+ * nothing, which is also why it is safe during rehearsal.
2506
+ */
2507
+ export function reportExternalAdoptionStep(root: string, actions: string[]): void {
2508
+ const config = loadComplianceConfig(root);
2509
+ const sources = config?.organize?.externalSources ?? [];
2510
+
2511
+ if (sources.length === 0) {
2512
+ // SC-5, and the decision is to write the list EMPTY. An external source
2513
+ // is an absolute path on one person's machine; a default would have
2514
+ // scaffold propose adopting documents out of directories the user never
2515
+ // named, in every project it touches. Recorded as a line rather than
2516
+ // left as an absence, so "nobody configured this" is distinguishable
2517
+ // from "this ran and found nothing".
2518
+ actions.push(
2519
+ "SKIP: external adoption (compliance.json declares no organize.externalSources — " +
2520
+ "deliberately empty, an external path is machine-specific and cannot be guessed)",
2521
+ );
2522
+ return;
2523
+ }
2524
+
2525
+ const report = organizeProjectReport(root, { dryRun: true, harnessRoot: root });
2526
+ const external = report.proposals.filter(p => p.source.startsWith("/"));
2527
+
2528
+ for (const path of report.unmeasured) {
2529
+ actions.push(`UNMEASURED: external source ${path} is declared but not on disk`);
2530
+ }
2531
+ for (const path of report.unreadable) {
2532
+ actions.push(`UNMEASURED: external source ${path} could not be read`);
2533
+ }
2534
+ for (const p of external) {
2535
+ actions.push(`PROPOSED: adopt ${p.source} -> ${p.target} (${p.reasoning})`);
2536
+ }
2537
+ if (external.length === 0 && report.unmeasured.length === 0 && report.unreadable.length === 0) {
2538
+ actions.push(
2539
+ `OK: external adoption found nothing (matched against ${report.aliases.join(", ")})`,
2540
+ );
2541
+ }
2542
+ }
2543
+
2495
2544
  export function runAuditSpecsFix(root: string, actions: string[]): void {
2496
2545
  const specsDir = join(root, "specs");
2497
2546
  if (!existsSync(specsDir)) {
@@ -2504,16 +2553,38 @@ export function runAuditSpecsFix(root: string, actions: string[]): void {
2504
2553
  return;
2505
2554
  }
2506
2555
  const result = auditSpecs(root, { fix: true });
2507
- const rewriteCount = result.rewrites?.length ?? 0;
2508
- if (rewriteCount > 0) {
2509
- // One action per spec file actually rewritten, naming the path (#216).
2556
+ const entries = result.rewrites ?? [];
2557
+ // #426: a line that was left alone is not a rewrite. Both are reported,
2558
+ // because "the matcher could not bind this" is worth seeing — but only one
2559
+ // of them changed what a reader will read, and conflating them is how a
2560
+ // silent spec edit hid behind a summary line naming `ci.yml`.
2561
+ const rewritten = entries.filter(r => r.kept === undefined);
2562
+ const kept = entries.filter(r => r.kept !== undefined);
2563
+
2564
+ if (entries.length > 0) {
2565
+ // One action per spec file actually touched, naming the path (#216).
2510
2566
  // "rewrote 2 SCs" named no file, so the rewritten specs were never staged
2511
2567
  // and showed up to the dirty-tree check as somebody else's edit.
2512
- const touched = [...new Set((result.rewrites ?? []).map(r => `specs/${r.specFile}`))];
2568
+ const touched = [...new Set(entries.map(r => `specs/${r.specFile}`))];
2513
2569
  for (const file of touched) actions.push(`UPDATED: ${file} (audit-specs --fix)`);
2514
- actions.push(`SKIP: audit-specs summary (rewrote ${rewriteCount} SCs across ${touched.length} spec file(s))`);
2515
- } else {
2570
+ }
2571
+
2572
+ // #426 SC-3: every rewritten criterion is named, with its id and its spec.
2573
+ // A spec line edited under a documented command and reported only as a
2574
+ // count is the defect, not merely the content that was lost.
2575
+ for (const r of rewritten) {
2576
+ actions.push(`REWROTE: specs/${r.specFile} ${r.scId} as ${r.patternUsed} — was: ${r.before}`);
2577
+ }
2578
+ for (const r of kept) {
2579
+ actions.push(`KEPT: specs/${r.specFile} ${r.scId} — ${r.kept}`);
2580
+ }
2581
+
2582
+ if (entries.length === 0) {
2516
2583
  actions.push("SKIP: audit-specs (all SCs already matchable)");
2584
+ } else {
2585
+ actions.push(
2586
+ `SKIP: audit-specs summary (rewrote ${rewritten.length} SCs, left ${kept.length} unmatched but intact)`,
2587
+ );
2517
2588
  }
2518
2589
  }
2519
2590
 
@@ -2544,6 +2615,50 @@ function dirtyPaths(root: string, generated: string[]): string[] {
2544
2615
  * steps, it does not implement them. The caller decides what a refusal costs;
2545
2616
  * this only counts them, so it stays callable from a test.
2546
2617
  */
2618
+ /**
2619
+ * The path a report line says scaffold WROTE, or null if it wrote nothing.
2620
+ *
2621
+ * One binding, because two callers now depend on the same judgement and a
2622
+ * second copy would let them disagree about the same line. `postScaffoldCommit`
2623
+ * uses it to decide what to stage — a verb it fails to recognise leaves a
2624
+ * generated file uncommitted — and #398's audit/fix agreement check uses it to
2625
+ * compare what audit NAMED against what `--fix` actually wrote.
2626
+ *
2627
+ * Deliberately excludes SKIP / GAP / WARN / AUDIT / UNCHANGED / REFUSED: all
2628
+ * of them are lines about a write that did not happen. Getting that wrong in
2629
+ * the permissive direction would make audit and fix "agree" by both
2630
+ * over-reporting, which is agreement for the wrong reason — see
2631
+ * `.claude/rules/checks-must-be-able-to-fail.md` on assertions that hold
2632
+ * vacuously. `test/scaffold-audit-agreement.test.ts` pins both directions.
2633
+ *
2634
+ * **The verb list had drifted from the verbs scaffold emits, and #398's
2635
+ * agreement check is what found it.** `REGENERATED`, `REFRESHED` and
2636
+ * `REPAIRED` are all writes and none of them was here, so for as long as they
2637
+ * have existed `postScaffoldCommit --commit` has quietly failed to stage
2638
+ * `AGENTS.md` (REGENERATED, `write-steps.ts`), `.claude/rules/` (REFRESHED,
2639
+ * `steps.ts:611`) and any seeded config (REPAIRED, `steps.ts:1181`). The
2640
+ * comment above this list used to say missing a verb "silently leaves
2641
+ * generated files uncommitted", which was exactly right and exactly what was
2642
+ * happening.
2643
+ *
2644
+ * A prose warning did not keep the list current, so there is now a test that
2645
+ * greps the sources for emitted write verbs and fails when one is not here.
2646
+ */
2647
+ export const WRITE_VERBS: readonly string[] = [
2648
+ "CREATED", "UPDATED", "REPLACED", "GENERATED", "REGENERATED",
2649
+ "REFRESHED", "REPAIRED", "DEPLOYED", "SPLIT",
2650
+ // #426: a rewritten SC line is a write to the spec that names it. The
2651
+ // `UPDATED:` action for the same file already stages it, so this is
2652
+ // belt-and-braces — but a verb that announces an edit and is not here is
2653
+ // the exact drift this list exists to stop.
2654
+ "REWROTE",
2655
+ ];
2656
+
2657
+ export function writtenPath(line: string): string | null {
2658
+ const m = line.trim().match(new RegExp(`^(?:${WRITE_VERBS.join("|")}): ([^\\s(]+)`));
2659
+ return m?.[1] ?? null;
2660
+ }
2661
+
2547
2662
  export function reportScaffoldActions(actions: string[]): number {
2548
2663
  console.log("\n=== Scaffold Report ===");
2549
2664
  for (const action of actions) console.log(` ${action}`);
@@ -2575,10 +2690,7 @@ export function postScaffoldCommit(
2575
2690
  // already existed, the real commit then had to be an amend.
2576
2691
  const generated = [...new Set(
2577
2692
  actions
2578
- // Verbs that mean "scaffold wrote this path". Deliberately excludes
2579
- // SKIP / GAP / WARN / AUDIT (no write happened) — and all of them,
2580
- // because missing one silently leaves generated files uncommitted.
2581
- .map(a => a.trim().match(/^(?:CREATED|UPDATED|REPLACED|GENERATED|DEPLOYED|SPLIT): ([^\s(]+)/)?.[1])
2693
+ .map(writtenPath)
2582
2694
  .filter((p): p is string => Boolean(p))
2583
2695
  // .git/ contents are not tracked; hooks live there.
2584
2696
  // .git/ contents are never tracked. Directories are kept — scaffold