rungate 0.5.0 → 0.7.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 (142) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
@@ -20,7 +20,17 @@
20
20
  * others' work has to survive.
21
21
  */
22
22
 
23
- import { copyFileSync, existsSync, lstatSync, mkdirSync, realpathSync } from "fs";
23
+ import {
24
+ copyFileSync,
25
+ existsSync,
26
+ lstatSync,
27
+ mkdirSync,
28
+ mkdtempSync,
29
+ realpathSync,
30
+ rmSync,
31
+ utimesSync,
32
+ } from "fs";
33
+ import { tmpdir } from "os";
24
34
  import { dirname, isAbsolute, join, relative, resolve } from "path";
25
35
 
26
36
  export interface AgentBuildResult {
@@ -140,12 +150,94 @@ export function groupFilesByWorktree(results: AgentBuildResult[]): WorktreeGroup
140
150
  }
141
151
 
142
152
  /**
143
- * Copy each group's files from its worktree into `projectRoot`.
153
+ * One write this call made, and what undoing it means (#750).
154
+ *
155
+ * Recorded BEFORE the write, not after. A `copyFileSync` that throws partway
156
+ * has already truncated the destination, so an entry appended afterwards
157
+ * would never exist for exactly the write that needs undoing most.
158
+ */
159
+ type CollectUndo =
160
+ /** The destination did not exist: undoing it means REMOVING, not restoring. */
161
+ | { kind: "created-file"; dest: string }
162
+ /** The destination existed: its bytes and timestamps are held aside. */
163
+ | { kind: "overwritten-file"; dest: string; backup: string; atime: Date; mtime: Date }
164
+ /** The topmost directory `mkdirSync(recursive)` created for a destination. */
165
+ | { kind: "created-dir"; dir: string };
166
+
167
+ /**
168
+ * Where a rollback holds the previous bytes of a destination it overwrote.
169
+ *
170
+ * **Outside the project root, and exported so that is checkable.** A backup
171
+ * staged inside the tree being collected into is a file the caller stages,
172
+ * commits and pushes the moment the cleanup that removes it does not run.
173
+ * Inlining `mkdtempSync` at the one call site made that property true and
174
+ * unobservable: the directory is removed on the success path and on the
175
+ * failure path, so every post-call assertion reads the same either way —
176
+ * measured as battery row M8, **0 red**, which is what a vacuous case looks
177
+ * like from the outside. One binding, so there is one thing to mutate.
178
+ */
179
+ export function collectBackupRoot(): string {
180
+ return mkdtempSync(join(tmpdir(), "rungate-collect-undo-"));
181
+ }
182
+
183
+ /** Raised when the copy failed AND putting the tree back also failed. */
184
+ export class CollectRollbackError extends Error {
185
+ constructor(
186
+ readonly cause: unknown,
187
+ readonly rollbackFailures: string[],
188
+ ) {
189
+ super(
190
+ `${cause instanceof Error ? cause.message : String(cause)}\n` +
191
+ `AND the project root could NOT be put back: ${rollbackFailures.join("; ")}. ` +
192
+ `The tree is in an unknown state — do not stage or commit it.`,
193
+ );
194
+ this.name = "CollectRollbackError";
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Copy each group's files from its worktree into `projectRoot`, atomically in
200
+ * the only sense that matters here: **a throw leaves the project root as it
201
+ * was.**
144
202
  *
145
203
  * Throws rather than skipping when a destination would land outside
146
204
  * `projectRoot`. A traversal here is not a path to sanitise away quietly — it
147
205
  * means the inputs cannot be trusted, and the caller must abort the commit
148
206
  * rather than proceed with a partially-collected tree.
207
+ *
208
+ * ## Why a journal, and not the two cheaper designs (#750)
209
+ *
210
+ * Eleven throw sites sit between the group loop and the `copyFileSync`. Any
211
+ * that fires after the first successful copy used to leave copied files in
212
+ * the project root with nothing putting them back, and `workflows/ship.js`
213
+ * then reported a failed collect over a half-written tree.
214
+ *
215
+ * #750 offered three designs and asked for one with a reason.
216
+ *
217
+ * - **Validate every file before copying anything** is the issue's own named
218
+ * cheapest wrong fix, and it is wrong for a reason that survives careful
219
+ * implementation: every one of these checks is an `lstat` of a path the
220
+ * AGENT controls. Answering at T1 and copying at T2 lets the answer change
221
+ * in between, and the property asked for is about the resulting tree, not
222
+ * about the order the checks run in.
223
+ * - **Stage into a temp directory and move into place in one pass** narrows
224
+ * the window without closing it: N renames are N operations, and a throw
225
+ * during the Nth leaves N−1 done. It also degrades silently when the
226
+ * staging directory is on another filesystem, where `renameSync` raises
227
+ * `EXDEV` and the "one atomic move" becomes a copy again.
228
+ * - **A journal** — this one — delivers the property for a throw from
229
+ * ANYWHERE, including one this function did not generate: an `ENOSPC` from
230
+ * `copyFileSync`, an `EACCES` from `mkdirSync`, a race that no amount of
231
+ * pre-validation can see.
232
+ *
233
+ * ## Undoing can itself fail, and that is a different state
234
+ *
235
+ * A rollback that cannot complete leaves a tree nobody has validated, which
236
+ * is worse than the original failure and must not be reported as it. It
237
+ * raises `CollectRollbackError` carrying both the original cause and every
238
+ * undo that failed. Swallowing them would make a half-restored tree
239
+ * indistinguishable from a clean refusal — `0`, `{}` and silence are
240
+ * indistinguishable from success (`.claude/rules/config-access.md`).
149
241
  */
150
242
  export function collectWorktreeFiles(
151
243
  groups: WorktreeGroup[],
@@ -155,6 +247,67 @@ export function collectWorktreeFiles(
155
247
  const copied: string[] = [];
156
248
  const missing: string[] = [];
157
249
 
250
+ /** Every write this call has made, oldest first. Undone in reverse. */
251
+ const journal: CollectUndo[] = [];
252
+ /** Created on the first OVERWRITE, so a run that overwrites nothing makes none. */
253
+ let backupDir: string | null = null;
254
+
255
+ const backupOf = (dest: string): string => {
256
+ backupDir ??= collectBackupRoot();
257
+ const slot = join(backupDir, String(journal.length));
258
+ copyFileSync(dest, slot);
259
+ return slot;
260
+ };
261
+
262
+ const undoAll = (): string[] => {
263
+ const failures: string[] = [];
264
+ // Reverse order, so a file created inside a directory this call also
265
+ // created is removed before the directory is.
266
+ for (const entry of [...journal].reverse()) {
267
+ try {
268
+ if (entry.kind === "created-file") {
269
+ rmSync(entry.dest, { force: true });
270
+ } else if (entry.kind === "overwritten-file") {
271
+ copyFileSync(entry.backup, entry.dest);
272
+ // Bytes alone are not "as it was" for anything keyed on mtime — a
273
+ // build cache, a watcher, `make`. Restored from the stat taken
274
+ // before the overwrite.
275
+ utimesSync(entry.dest, entry.atime, entry.mtime);
276
+ } else {
277
+ // Recursive is safe here and only here: `mkdirSync(recursive)`
278
+ // returns a path only when it CREATED it, so everything beneath
279
+ // this directory was created by this call, and the files among
280
+ // them have already been removed by the entries above.
281
+ rmSync(entry.dir, { recursive: true, force: true });
282
+ }
283
+ } catch (e) {
284
+ failures.push(`${entry.kind} ${"dest" in entry ? entry.dest : entry.dir}: ${String(e)}`);
285
+ }
286
+ }
287
+ return failures;
288
+ };
289
+
290
+ try {
291
+ collect();
292
+ } catch (cause) {
293
+ const failures = undoAll();
294
+ cleanupBackups();
295
+ throw failures.length > 0 ? new CollectRollbackError(cause, failures) : cause;
296
+ }
297
+ cleanupBackups();
298
+ return { copied: [...new Set(copied)], missing };
299
+
300
+ function cleanupBackups(): void {
301
+ // Best effort, and genuinely best effort: a leftover temp directory is
302
+ // litter, not a correctness problem, and raising from here would mask
303
+ // the error being propagated.
304
+ if (backupDir) {
305
+ try { rmSync(backupDir, { recursive: true, force: true }); } catch { /* litter only */ }
306
+ backupDir = null;
307
+ }
308
+ }
309
+
310
+ function collect(): void {
158
311
  // `allowedWorktrees` is required, and an empty list authorises nothing.
159
312
  // Making it optional with an "allow anything" default would restore exactly
160
313
  // the hole it exists to close, in the quietest possible way.
@@ -251,7 +404,11 @@ export function collectWorktreeFiles(
251
404
  if (!realIsInside(projectRoot, dirname(dest))) {
252
405
  throw new Error(`destination directory escapes the project root: ${rel}`);
253
406
  }
254
- mkdirSync(dirname(dest), { recursive: true });
407
+ // The return value is the TOPMOST directory it created, or undefined
408
+ // when every component already existed. Journaling it is what makes
409
+ // an empty directory tree not survive a refusal.
410
+ const createdDir = mkdirSync(dirname(dest), { recursive: true });
411
+ if (createdDir) journal.push({ kind: "created-dir", dir: createdDir });
255
412
  // And again after: mkdir resolved and created real directories, but a
256
413
  // symlinked component could have been introduced between the two.
257
414
  if (!realIsInside(projectRoot, dirname(dest))) {
@@ -273,11 +430,26 @@ export function collectWorktreeFiles(
273
430
  if (dst && dst.nlink > 1) {
274
431
  throw new Error(`refusing to overwrite a hard link: ${rel}`);
275
432
  }
433
+
434
+ // Journal BEFORE the write. `copyFileSync` truncates the destination
435
+ // before it finishes, so an entry appended after a successful copy
436
+ // would be missing for precisely the case that needs it most — a
437
+ // copy that threw partway and left a truncated file.
438
+ journal.push(
439
+ dst
440
+ ? {
441
+ kind: "overwritten-file",
442
+ dest,
443
+ backup: backupOf(dest),
444
+ atime: dst.atime,
445
+ mtime: dst.mtime,
446
+ }
447
+ : { kind: "created-file", dest },
448
+ );
276
449
  copyFileSync(src, dest);
277
450
  }
278
451
  copied.push(relative(projectRoot, dest));
279
452
  }
280
453
  }
281
-
282
- return { copied: [...new Set(copied)], missing };
454
+ }
283
455
  }
@@ -186,6 +186,40 @@ export function readWorktreeRemote(worktreePath: string): RemoteReading {
186
186
  return url ? { url, error: null } : { url: null, error: "git printed no url" };
187
187
  }
188
188
 
189
+ /**
190
+ * Is this value a filesystem path rather than a remote?
191
+ *
192
+ * Only to SAY SO in a refusal — nothing branches on it, and `unreadable` is
193
+ * still `unreadable` (#218 is unchanged). The reading is already unusable;
194
+ * what #872 adds is the operator being told WHICH unusable thing it is,
195
+ * because the measured instance was an agent writing the parent checkout's
196
+ * directory into `worktreeRepo` after printing the right URL.
197
+ *
198
+ * ABSOLUTE only. `owner/name` is itself two segments with a slash, so a rule
199
+ * that called anything slash-shaped a path would describe a near-miss slug as
200
+ * a directory — a refusal naming the wrong mistake is worse than one naming
201
+ * none. Three forms: POSIX, `~`-relative, and Windows drive or UNC.
202
+ *
203
+ * No regex literal, and that is not a style choice. Written as one, this
204
+ * needs an escaped forward slash — and `stripStringsAndComments` mangles a
205
+ * `\/`-bearing literal in `workflows/ship.js`'s context into `/^(?:\/x/`,
206
+ * which does not parse. Two CI shards went red on it. The same literal
207
+ * strips cleanly in isolation, so the differential is real and is filed
208
+ * separately; here the fix is to not write the construct.
209
+ */
210
+ export function looksLikeFilesystemPath(reported: unknown): boolean {
211
+ const s = String(reported).trim();
212
+ if (s.startsWith("/") || s.startsWith("~/") || s.startsWith("\\\\")) return true;
213
+ // A Windows drive: one letter, a colon, then either separator.
214
+ const drive = s.charCodeAt(0) | 32;
215
+ return drive >= 97 && drive <= 122 && s[1] === ":" && (s[2] === "\\" || s[2] === "/");
216
+ }
217
+
218
+ /** The clause both copies append, so the two cannot word it differently. */
219
+ const PATH_SHAPED_CLAUSE =
220
+ " — that value is a filesystem path, and worktreeRepo is the URL " +
221
+ "`git remote get-url origin` printed, never a path (#872)";
222
+
189
223
  /**
190
224
  * Does the worktree belong to the repository this run is for?
191
225
  *
@@ -245,7 +279,8 @@ export function worktreeIdentity(
245
279
  refusal:
246
280
  `${where} reported an origin this run cannot read as owner/name ` +
247
281
  `(${JSON.stringify(redactRemote(String(reported).trim()))}), ` +
248
- `so it cannot be compared against ${expected} (#218)`,
282
+ `so it cannot be compared against ${expected} (#218)` +
283
+ (looksLikeFilesystemPath(reported) ? PATH_SHAPED_CLAUSE : ""),
249
284
  };
250
285
  }
251
286
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rungate",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Ship harness — conformity tests, scaffold, and agent briefs for AI-first development",
6
6
  "repository": {
@@ -27,6 +27,7 @@
27
27
  "scripts/create-spec.ts",
28
28
  "scripts/create-success.ts",
29
29
  "scripts/create-sc.ts",
30
+ "scripts/ai-review-findings.ts",
30
31
  "scripts/split-spec.ts",
31
32
  "scripts/sync-sc-status.ts",
32
33
  "scripts/audit-transcript.ts",
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Adjudicate an AI review's findings payload (#675).
4
+ *
5
+ * Usage:
6
+ * bunx rungate ai-review-findings <path-to-findings.json> # a consumer
7
+ * bun bin/rungate.ts ai-review-findings <path> # this repo
8
+ *
9
+ * The reading, the severity table, the contradiction check and the exit code
10
+ * all live in `lib/scaffold/ai-review-findings.ts` and none of them is
11
+ * restated here. This file exists for ONE reason, and it is a reachability
12
+ * problem rather than a logic one.
13
+ *
14
+ * ## Why a wrapper, when the module already has a `main`
15
+ *
16
+ * `lib/scaffold/ai-review-findings.ts` ends with
17
+ * `if (import.meta.main) process.exit(main(process.argv.slice(2)))` and its
18
+ * `main` is documented as "the CLI the generated workflow step runs". Two
19
+ * things stop that being reachable from a scaffolded project:
20
+ *
21
+ * - **A consumer has no copy of rungate's sources at a path it can name.**
22
+ * The reader is inside the installed package, and the generated workflow
23
+ * cannot hardcode `node_modules/rungate/lib/scaffold/…` without becoming a
24
+ * second declaring position for a path the package controls.
25
+ * `lib/cli-commands.ts` is the one place that says where a command lives,
26
+ * and `test/cli-contract.test.ts` holds it to `package.json`'s `files`.
27
+ * - **`import.meta.main` is FALSE under the dispatcher.** `bin/rungate.ts`
28
+ * rewrites `process.argv` and then `await import(script)` — the import IS
29
+ * the invocation — so a module guarded on `import.meta.main` loads, runs
30
+ * nothing, and the dispatcher exits 0. That is a subcommand that reports
31
+ * success having adjudicated nothing, which is the exact shape of defect
32
+ * #675 is about. This file calls `main` unconditionally, so there is no
33
+ * state in which it is dispatched and does not decide.
34
+ *
35
+ * The exit code is the module's, not this file's. `aiReviewExitCode` routes
36
+ * every refusal through `AI_REVIEW_REQUIRED_EXIT` in
37
+ * `lib/scaffold/ai-review-step.ts`, which is the one constant a mutant zeroes
38
+ * — see `test/ai-review-exit-binding.test.ts`. A `process.exit(1)` written
39
+ * here would be a second non-zero exit that the mutation cannot reach, and
40
+ * the case would go green over a refusal that no longer came from the
41
+ * constant.
42
+ */
43
+ import { main } from "../lib/scaffold/ai-review-findings";
44
+
45
+ process.exit(main(process.argv.slice(2)));
@@ -102,14 +102,27 @@ function extractSCs(content: string, specFile: string): ParsedSC[] {
102
102
 
103
103
  // ── Closest pattern matching for rewrites ─────────────────────
104
104
 
105
+ export interface ClosestPattern {
106
+ patternName: string;
107
+ rewrite: string;
108
+ ambiguous: boolean;
109
+ /**
110
+ * Set ONLY by the last-resort file-token match (#589).
111
+ *
112
+ * `patternName` cannot carry this: the last resort renders `file-exists`,
113
+ * which is also the name of a real heuristic, so a caller reading the name
114
+ * alone cannot tell a pattern the statement matched from one inferred off a
115
+ * filename that happened to be in the sentence.
116
+ */
117
+ fallback?: boolean;
118
+ }
119
+
105
120
  /**
106
121
  * Score how well an SC statement matches a registry pattern by
107
122
  * looking for keyword overlaps. Returns the best pattern name and
108
123
  * a generated rewrite, or null if nothing is close enough.
109
124
  */
110
- function findClosestPattern(
111
- statement: string
112
- ): { patternName: string; rewrite: string; ambiguous: boolean } | null {
125
+ function findClosestPattern(statement: string): ClosestPattern | null {
113
126
  const registry = loadRegistry();
114
127
  const lower = statement.toLowerCase();
115
128
 
@@ -118,6 +131,10 @@ function findClosestPattern(
118
131
  pattern: string;
119
132
  keywords: string[];
120
133
  extractor: (stmt: string) => string | null;
134
+ /** All keywords must be present, not any one of them (#586). */
135
+ requireAll?: boolean;
136
+ /** The extractor ignores its argument, so it cannot be unambiguous (#586). */
137
+ constant?: boolean;
121
138
  }> = [
122
139
  {
123
140
  pattern: "pointer-exists",
@@ -228,36 +245,81 @@ function findClosestPattern(
228
245
  },
229
246
  {
230
247
  pattern: "all-specs-frontmatter",
248
+ // #586: `requireAll`, because the keyword test below is `some` and the
249
+ // bare word `frontmatter` was firing a rule about ALL SPECS. It turned
250
+ // `Baseline rules carry no paths: key in frontmatter` into
251
+ // `all specs have frontmatter` — a different, weaker property.
252
+ // "all specs" is the phrase that scopes this rule; "frontmatter" is
253
+ // the phrase it shares with every other frontmatter criterion.
254
+ requireAll: true,
231
255
  keywords: ["all specs", "frontmatter"],
232
256
  extractor: () => "all specs have frontmatter",
257
+ /**
258
+ * The extractor never reads its argument, so it cannot know what the
259
+ * criterion said. #586: that is precisely when the original must be
260
+ * kept in the file, and this rule claimed `ambiguous: false` — the
261
+ * one flag that suppresses the `<!-- REVIEW: original — … -->` marker.
262
+ */
263
+ constant: true,
233
264
  },
234
265
  {
235
266
  pattern: "canary",
236
267
  keywords: ["canary"],
237
268
  extractor: () => "canary test exists",
269
+ constant: true,
238
270
  },
239
271
  ];
240
272
 
241
273
  // Try each heuristic — first one whose extractor succeeds wins
242
274
  for (const h of heuristics) {
243
- // Check if any keyword matches
244
- const hasKeyword = h.keywords.some((k) => lower.includes(k));
275
+ const hasKeyword = h.requireAll
276
+ ? h.keywords.every((k) => lower.includes(k))
277
+ : h.keywords.some((k) => lower.includes(k));
245
278
  if (!hasKeyword) continue;
246
279
 
247
280
  const rewrite = h.extractor(statement);
248
281
  if (rewrite) {
249
- return { patternName: h.pattern, rewrite, ambiguous: false };
282
+ // A constant extractor is ambiguous BY CONSTRUCTION. Marking it
283
+ // otherwise discards the original from the file in the only case where
284
+ // nothing can reconstruct it.
285
+ return { patternName: h.pattern, rewrite, ambiguous: h.constant === true };
250
286
  }
251
287
  }
252
288
 
253
- // If no heuristic matched, try a loose file-exists match
254
- // Look for any filename-like token (word.ext) in the statement
289
+ // If no heuristic matched, try a loose file-exists match.
290
+ // Look for any filename-like token (word.ext) in the statement.
291
+ //
292
+ // #586 looked hard at narrowing this to statements whose verb is
293
+ // existence, and did not. The fallback does turn behaviour into presence —
294
+ // measured over the real tree, two criteria go through it:
295
+ //
296
+ // "Rejecting a promoted rule writes its hash to
297
+ // `reference/rejected-constraints.md` and it is never re-promoted"
298
+ // -> "reference/rejected-constraints.md exists"
299
+ //
300
+ // "Makefile targets, `package.json` scripts and CI workflow files are
301
+ // scanned for constraints alongside markdown"
302
+ // -> "package.json exists"
303
+ //
304
+ // — but it reports `ambiguous: true`, and an ambiguous rewrite writes
305
+ // `<!-- REVIEW: original — … -->` beside the line. #426 kept this path for
306
+ // exactly that reason (see SC-1587: "a lossy render by nature … kept as the
307
+ // one remaining rewrite path precisely because it writes the statement it
308
+ // replaced into the next line"). Nothing is discarded, so this is a
309
+ // DOWNGRADE, not a LOSS, and #586 is about loss.
310
+ //
311
+ // Narrowing it here turns SC-1587 and SC-1594 red for a reason those
312
+ // criteria are right about, which is how the distinction got found. The
313
+ // downgrade is #589, and it is now scoped by `coordinatedClaims` below
314
+ // rather than by narrowing the token match: WHICH statements this may
315
+ // speak for is a question about the criterion, not about the filename.
255
316
  const fileToken = statement.match(/\b(\S+\.\w{1,5})\b/);
256
317
  if (fileToken) {
257
318
  return {
258
319
  patternName: "file-exists",
259
320
  rewrite: `${fileToken[1]} exists`,
260
321
  ambiguous: true,
322
+ fallback: true,
261
323
  };
262
324
  }
263
325
 
@@ -334,7 +396,7 @@ export type RewriteDecision =
334
396
  */
335
397
  export function decideRewrite(
336
398
  statement: string,
337
- closest: { patternName: string; rewrite: string; ambiguous: boolean } | null,
399
+ closest: ClosestPattern | null,
338
400
  ): RewriteDecision {
339
401
  if (alreadyStructured(statement)) {
340
402
  return { kind: "keep", reason: "already a structured criterion — a matcher gap is not a licence to rewrite it" };
@@ -351,14 +413,180 @@ export function decideRewrite(
351
413
  };
352
414
  }
353
415
 
416
+ // #589: the last resort may only speak for a criterion that makes ONE
417
+ // claim. It takes a filename-like token from anywhere in a sentence and
418
+ // renders the whole criterion as `<that file> exists`, which can be about
419
+ // at most one thing — so a criterion that coordinates a second claim is
420
+ // guaranteed to come back as a statement about something else.
421
+ //
422
+ // Measured over the corpus `--fix` edits: two criteria went through it,
423
+ // SC-1940 (a hash is written AND the rule never resurfaces) and SC-1943 (a
424
+ // three-item subject of which the filename is one). Both are kept now.
425
+ //
426
+ // Scoped to the fallback deliberately. A heuristic that MATCHED the
427
+ // statement was chosen by what the statement says; the last resort was
428
+ // chosen by a filename being present, and that is the difference this
429
+ // guard is about.
430
+ if (closest.fallback) {
431
+ const claims = coordinatedClaims(statement);
432
+ if (claims.length > 0) {
433
+ return {
434
+ kind: "keep",
435
+ reason:
436
+ `rewriting as ${closest.patternName} would assert only that ${closest.rewrite}, ` +
437
+ `while the criterion coordinates a further claim (${claims[0]}) — ` +
438
+ `the file is mentioned, not what the criterion is about`,
439
+ };
440
+ }
441
+ }
442
+
354
443
  const rationale = rationaleOf(statement);
355
444
  const rewritten = rationale ? `${closest.rewrite} — ${rationale}` : closest.rewrite;
445
+
446
+ // #586: the fourth guard, and the general one. The three above protect
447
+ // specific things — a structured line, a missing pattern, a named file.
448
+ // This one asks the question they are each a special case of: **does the
449
+ // rewrite still say what the criterion was about?**
450
+ //
451
+ // It exists because the three above all passed on
452
+ // `Baseline rules carry no paths: key in frontmatter`, which was rewritten
453
+ // to `all specs have frontmatter`. Nothing of the original survived and no
454
+ // guard was looking at that.
455
+ //
456
+ // It asks the question of `rewritten`, not of `closest.rewrite`, and the
457
+ // difference is #426's SC-1591: the rationale clause is carried across, so
458
+ // a statement whose meaning lives in its `— because …` half survives a
459
+ // constant rewrite with that half intact. Asking it of the bare pattern
460
+ // text refuses those, which turns the enricher off for every criterion
461
+ // that explains itself. SC-1930 has no rationale clause, so nothing of it
462
+ // survives either way and it is still refused.
463
+ const terms = distinguishingTerms(statement);
464
+ const lowered = rewritten.toLowerCase();
465
+ if (terms.length > 0 && !terms.some(t => lowered.includes(t))) {
466
+ return {
467
+ kind: "keep",
468
+ reason:
469
+ `rewriting as ${closest.patternName} would drop every distinguishing term the ` +
470
+ `criterion uses (${terms.join(", ")}) — the rewrite would be about something else`,
471
+ };
472
+ }
473
+
356
474
  if (rewritten === statement) {
357
475
  return { kind: "keep", reason: "the rewrite is what is already written" };
358
476
  }
359
477
  return { kind: "rewrite", statement: rewritten };
360
478
  }
361
479
 
480
+ /**
481
+ * The words that say what THIS criterion is about (#586).
482
+ *
483
+ * Deliberately not "every word": a rewrite legitimately drops grammar, and
484
+ * the term that caused the heuristic to fire is shared with every other
485
+ * criterion the heuristic matches. Counting the MATCHED keyword as retained
486
+ * content is how a constant rewrite reads as a faithful one — the proxy
487
+ * standing in for the property, which `.claude/rules/checks-must-be-able-to-fail.md`
488
+ * names as the trap in wording a refusal.
489
+ *
490
+ * So: lowercase alphanumeric tokens of four characters or more, minus
491
+ * stopwords, minus the vocabulary every registry pattern already uses.
492
+ */
493
+ const REWRITE_STOPWORDS = new Set([
494
+ "that", "this", "with", "from", "have", "has", "does", "must", "will", "when",
495
+ "then", "than", "each", "every", "into", "over", "under", "about", "there",
496
+ "their", "which", "where", "while", "been", "being", "they", "them", "than",
497
+ // The registry's own vocabulary. A rewrite keeping only these has kept
498
+ // nothing specific to the criterion it replaced.
499
+ "frontmatter", "specs", "spec", "exists", "contains", "canary", "test",
500
+ "tests", "file", "files", "all", "none",
501
+ ]);
502
+
503
+ export function distinguishingTerms(statement: string): string[] {
504
+ const words = statement.toLowerCase().match(/[a-z0-9]{4,}/g) ?? [];
505
+ return [...new Set(words)].filter(w => !REWRITE_STOPWORDS.has(w));
506
+ }
507
+
508
+ /**
509
+ * The further claims this criterion coordinates, if any (#589).
510
+ *
511
+ * Returns the clause after each `and`/`or`, so the refusal can name what the
512
+ * rewrite would have dropped rather than merely reporting that something was
513
+ * dropped. Empty for a criterion that makes one claim.
514
+ *
515
+ * One exported binding, so there is exactly one thing to mutate — and it is
516
+ * the only thing that decides which statements the last resort may speak
517
+ * for.
518
+ */
519
+ export function coordinatedClaims(statement: string): string[] {
520
+ const claims: string[] = [];
521
+ const coordinator = /\s+(?:and|or)\s+/gi;
522
+ let m: RegExpExecArray | null;
523
+ while ((m = coordinator.exec(statement)) !== null) {
524
+ const rest = statement.slice(m.index + m[0].length).trim();
525
+ // A trailing coordinator joins nothing. An empty string here would read
526
+ // as a second claim whose text is gone, and refuse a rewrite on it.
527
+ if (rest.length > 0) claims.push(rest);
528
+ }
529
+ return claims;
530
+ }
531
+
532
+ /**
533
+ * `findClosestPattern`, exported so a test can drive the real decision.
534
+ *
535
+ * One binding (#586). A test that reimplemented the heuristic walk would
536
+ * agree with it right up until somebody changed one of them.
537
+ */
538
+ export function closestPatternFor(statement: string): ClosestPattern | null {
539
+ return findClosestPattern(statement);
540
+ }
541
+
542
+ // ── Editing one SC line ───────────────────────────────────────
543
+
544
+ /**
545
+ * Put `replacement` where `match` was, as LITERAL TEXT (#586).
546
+ *
547
+ * `String.prototype.replace(re, string)` treats the second argument as a
548
+ * replacement TEMPLATE: `$'` is "everything after the match", `$&` is the
549
+ * match, `$1` is the first capture group. Every one of those is a sequence a
550
+ * success criterion can legitimately contain — `--fix` is a tool for editing
551
+ * documents written by people about shell and regex syntax — and the text
552
+ * being substituted in here is the criterion itself.
553
+ *
554
+ * Measured before this existed, on a four-criterion fixture whose first
555
+ * statement read ``Baseline rules carry no $' key in frontmatter``:
556
+ *
557
+ * - [ ] SC-9301: Baseline rules carry no <- its text, truncated
558
+ * - [ ] SC-9302: … <- the remainder of the
559
+ * - [ ] SC-9303: … document, pasted in
560
+ * - [ ] SC-9304: …
561
+ * key in frontmatter
562
+ *
563
+ * Three ids now appeared twice in one spec and one criterion had lost its
564
+ * statement — on a run whose own ledger reported `kept` and `before ===
565
+ * after` for all four. The report and the file disagreed and only the report
566
+ * was ever read.
567
+ *
568
+ * It splices by INDEX rather than re-running the regex, which also removes
569
+ * the second search: the caller has already found the line, and a function
570
+ * that searched for it again would be a second answer to a question that was
571
+ * already answered.
572
+ */
573
+ function replaceLine(content: string, match: RegExpMatchArray, replacement: string): string {
574
+ const at = match.index!;
575
+ return content.slice(0, at) + replacement + content.slice(at + match[0].length);
576
+ }
577
+
578
+ /**
579
+ * Does `marker` already sit on the line directly below the matched line?
580
+ *
581
+ * The question the suppression guard has to ask (#586). It used to ask
582
+ * `modified.includes(marker)` — of the WHOLE FILE — so the second criterion
583
+ * declined for a given reason was silently left unmarked, and the commonest
584
+ * reason by far is the generic "no registry pattern was close enough".
585
+ */
586
+ function followsWith(content: string, match: RegExpMatchArray, marker: string): boolean {
587
+ return content.slice(match.index! + match[0].length).startsWith(`\n${marker}`);
588
+ }
589
+
362
590
  // ── Core audit function ───────────────────────────────────────
363
591
 
364
592
  export function auditSpecs(
@@ -432,8 +660,15 @@ export function auditSpecs(
432
660
  // the file it names or the prose that says why it exists.
433
661
  if (decision.kind === "keep") {
434
662
  const marker = `<!-- REVIEW: unmatched (${decision.reason}) -->`;
435
- if (!modified.includes(marker)) {
436
- modified = modified.replace(scLinePattern, `${scMatch[0]}\n${marker}`);
663
+ // #586: asked of THIS criterion's own next line, not of the whole
664
+ // file. A file-wide `includes` meant that two criteria declined
665
+ // for the same reason — and "no registry pattern was close enough"
666
+ // is the commonest reason there is — shared one marker: measured
667
+ // at four unmatched criteria and one marker. The three unmarked
668
+ // ones read as reviewed because of a comment about a different
669
+ // criterion.
670
+ if (!followsWith(modified, scMatch, marker)) {
671
+ modified = replaceLine(modified, scMatch, `${scMatch[0]}\n${marker}`);
437
672
  hasChanges = true;
438
673
  }
439
674
  rewrites.push({
@@ -452,7 +687,7 @@ export function auditSpecs(
452
687
  if (closest!.ambiguous) {
453
688
  replacement += `\n<!-- REVIEW: original — ${usc.statement} -->`;
454
689
  }
455
- modified = modified.replace(scLinePattern, replacement);
690
+ modified = replaceLine(modified, scMatch, replacement);
456
691
  hasChanges = true;
457
692
  rewrites.push({
458
693
  scId: usc.id,