rungate 0.6.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 (113) 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 +81 -16
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-protection.ts +790 -0
  7. package/lib/brief-ac-alignment.ts +104 -0
  8. package/lib/brief-references.ts +205 -0
  9. package/lib/bun-version.ts +93 -14
  10. package/lib/check-remedy.ts +140 -0
  11. package/lib/ci-checkout.ts +17 -0
  12. package/lib/ci-history-depth.ts +159 -0
  13. package/lib/ci-setup-step.ts +96 -0
  14. package/lib/claude-code-action.ts +85 -0
  15. package/lib/claude-tool-vocabulary.ts +188 -0
  16. package/lib/cli-commands.ts +15 -0
  17. package/lib/commit-sha.ts +42 -0
  18. package/lib/commit-subject.ts +90 -0
  19. package/lib/compliance-report.ts +377 -45
  20. package/lib/compliance.ts +191 -17
  21. package/lib/config-loader.ts +39 -1
  22. package/lib/config-trackable.ts +391 -0
  23. package/lib/conformity.ts +1087 -100
  24. package/lib/containment.ts +238 -0
  25. package/lib/content-hash.ts +24 -0
  26. package/lib/create-sc.ts +249 -16
  27. package/lib/dev-liveness.ts +180 -0
  28. package/lib/discovery-branch-points.ts +432 -0
  29. package/lib/discovery-stability.ts +481 -0
  30. package/lib/distribution-currency.ts +186 -0
  31. package/lib/doc-routing.ts +157 -0
  32. package/lib/evidence-prevalidator.ts +224 -2
  33. package/lib/evidence-satisfiability.ts +534 -12
  34. package/lib/failure-intake.ts +317 -0
  35. package/lib/fallow-availability.ts +157 -0
  36. package/lib/fs-write-capabilities.ts +232 -0
  37. package/lib/gate-run-split.ts +147 -0
  38. package/lib/generators/agents-md.ts +140 -32
  39. package/lib/git-isolation.ts +140 -0
  40. package/lib/github.ts +15 -0
  41. package/lib/google-auth-action.ts +93 -0
  42. package/lib/harness-project.ts +48 -0
  43. package/lib/harness-provenance.ts +255 -0
  44. package/lib/hook-evidence.ts +235 -0
  45. package/lib/hook-scopes.ts +386 -0
  46. package/lib/hook-target-tree.ts +398 -0
  47. package/lib/hook-trees.ts +447 -0
  48. package/lib/js-top-level-code.ts +78 -10
  49. package/lib/junit-checks.ts +52 -0
  50. package/lib/launch-base.ts +253 -0
  51. package/lib/line-citation.ts +372 -0
  52. package/lib/orphan-reaper.ts +468 -0
  53. package/lib/parity-binding.ts +205 -0
  54. package/lib/per-test-timeouts.ts +219 -0
  55. package/lib/plan-coverage.ts +151 -0
  56. package/lib/prior-branch.ts +201 -8
  57. package/lib/process-table.ts +146 -0
  58. package/lib/project-state-derivation.ts +219 -0
  59. package/lib/project-state-root.ts +258 -0
  60. package/lib/published-artifact.ts +525 -0
  61. package/lib/readdir-sorted.ts +45 -0
  62. package/lib/review-execution-reading.ts +206 -0
  63. package/lib/review-tool-agreement.ts +433 -0
  64. package/lib/rule-promotion.ts +234 -0
  65. package/lib/rule-retirement.ts +525 -0
  66. package/lib/run-branch.ts +612 -0
  67. package/lib/rungate-schema.ts +19 -0
  68. package/lib/runner-home.ts +274 -0
  69. package/lib/sc-id-cross-tree.ts +19 -7
  70. package/lib/sc-ids.ts +121 -13
  71. package/lib/sc-reservations.ts +289 -0
  72. package/lib/scaffold/ai-review-findings.ts +403 -0
  73. package/lib/scaffold/ai-review-step.ts +4661 -64
  74. package/lib/scaffold/managed-workflow.ts +587 -192
  75. package/lib/scaffold/owned-files.ts +152 -45
  76. package/lib/scaffold/pre-push-hook.ts +49 -5
  77. package/lib/scaffold/steps.ts +1413 -244
  78. package/lib/scaffold/workflow-census.ts +217 -0
  79. package/lib/scaffold/workflow-drift.ts +217 -0
  80. package/lib/scaffold/write-steps.ts +4 -0
  81. package/lib/scan-budget.ts +247 -0
  82. package/lib/scanner.ts +43 -51
  83. package/lib/scratch-roots.ts +50 -5
  84. package/lib/screenshot-discovery.ts +121 -0
  85. package/lib/screenshot-upload.ts +41 -1
  86. package/lib/secret-patterns.ts +511 -8
  87. package/lib/ship-mode.ts +219 -0
  88. package/lib/source-slice.ts +294 -0
  89. package/lib/stale-cleanup.ts +37 -3
  90. package/lib/suite-flake.ts +278 -0
  91. package/lib/suite-measurement.ts +23 -4
  92. package/lib/suite-run-reading.ts +241 -1
  93. package/lib/suite-timeout-margin.ts +193 -0
  94. package/lib/test-case-bodies.ts +883 -0
  95. package/lib/test-case-deletion.ts +653 -0
  96. package/lib/test-census.ts +97 -29
  97. package/lib/test-command-positions.ts +274 -0
  98. package/lib/test-suite-lock.ts +159 -16
  99. package/lib/tool-probe.ts +31 -9
  100. package/lib/top-level-cd.ts +393 -0
  101. package/lib/tree-entries.ts +89 -0
  102. package/lib/ts-ast.ts +200 -0
  103. package/lib/walk-test-files.ts +97 -0
  104. package/lib/workflow-actions.ts +263 -0
  105. package/lib/worktree-collect.ts +177 -5
  106. package/lib/worktree-repo.ts +36 -1
  107. package/package.json +2 -1
  108. package/scripts/ai-review-findings.ts +45 -0
  109. package/scripts/create-sc.ts +21 -1
  110. package/scripts/extract-constraints.ts +107 -7
  111. package/scripts/generate-code-map.ts +23 -30
  112. package/scripts/scaffold-project.ts +8 -1
  113. package/scripts/sync-sc-status.ts +77 -16
@@ -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.6.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)));
@@ -5,8 +5,13 @@
5
5
  * Usage:
6
6
  * bun scripts/create-sc.ts --pattern file-exists --params '{"file":"AGENTS.md"}'
7
7
  * bun scripts/create-sc.ts --pattern file-exists --params '{"file":"AGENTS.md"}' --spec specs/MY-SPEC.md
8
+ * bun scripts/create-sc.ts --pattern file-exists --params '{...}' --spec specs/X.md --owner '#725'
8
9
  * bun scripts/create-sc.ts --list
9
10
  *
11
+ * `--owner` names the entry in `specs/sc-reservations.json` to allocate from.
12
+ * It defaults to this checkout's branch. An owner holding no block allocates
13
+ * above every block in the store, which is the safe direction.
14
+ *
10
15
  * Thin CLI consumer — all logic lives in lib/create-sc.ts.
11
16
  */
12
17
  import { readFileSync, writeFileSync, existsSync } from "fs";
@@ -18,6 +23,7 @@ import {
18
23
  } from "../lib/create-sc";
19
24
  import { readScRegistry } from "./sync-sc-status";
20
25
  import { describeReading } from "../lib/sc-id-cross-tree";
26
+ import { currentScOwner } from "../lib/sc-reservations";
21
27
  import { join } from "path";
22
28
 
23
29
  /** Same resolution sync-sc-status uses, so both halves read one tree. */
@@ -91,7 +97,20 @@ try {
91
97
  //
92
98
  // All three widths compose inside `allocateScNumber`, so this CLI cannot
93
99
  // assemble two of them and believe it asked.
94
- const { number: scNumber, namespace } = allocateScNumber(ROOT, content, readScRegistry());
100
+ //
101
+ // And a FOURTH, which none of the first three can be (#725): every one of
102
+ // them reads ids that are already written down somewhere, and the four
103
+ // collisions of 2026-10-19 were ids that had been decided on and not yet
104
+ // typed. `specs/sc-reservations.json` is where a session declares a block
105
+ // before consuming it; the owner is this checkout's branch, so a session
106
+ // that reserved one is handed an id out of it and a session that did not
107
+ // is handed one above every block in the store.
108
+ //
109
+ // `--owner` overrides the branch for the case the store is keyed by issue
110
+ // rather than by branch. An owner matching no block is not an error: it
111
+ // is the no-block path, which is the safe one.
112
+ const owner = getFlag("owner") ?? currentScOwner(ROOT);
113
+ const { number: scNumber, namespace } = allocateScNumber(ROOT, content, readScRegistry(), { owner });
95
114
  const scLine = formatSCLine(scNumber, statement);
96
115
 
97
116
  // Append SC line to the end of the file
@@ -103,6 +122,7 @@ try {
103
122
  // allocator that printed only the number would be claiming a guarantee it
104
123
  // cannot give (`.claude/rules/config-access.md`).
105
124
  console.log(` namespace: ${describeReading(namespace)}`);
125
+ console.log(` owner: ${owner ?? "(none — allocated above every reserved block)"}`);
106
126
  for (const gap of namespace.unmeasured) console.log(` UNMEASURED: ${gap}`);
107
127
  } else {
108
128
  // Output to stdout for piping
@@ -1,10 +1,25 @@
1
1
  #!/usr/bin/env bun
2
2
  import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
3
3
  import { join, relative } from "path";
4
- import { createHash } from "crypto";
5
4
  import { SIGNAL_PHRASE_PATTERNS } from "../lib/signal-phrases";
6
5
  import { planDocScan, type DocScanPlan } from "../lib/doc-scan-targets";
7
6
  import { lastCommitDates } from "../lib/git-dates";
7
+ import { contentHash } from "../lib/content-hash";
8
+ import {
9
+ mineFixCommits,
10
+ type EvidenceCandidate,
11
+ type FailureIntakeReading,
12
+ } from "../lib/failure-intake";
13
+ import {
14
+ promoteCandidates,
15
+ PROMOTION_BUDGET_RULES,
16
+ type PromotionReading,
17
+ } from "../lib/rule-promotion";
18
+ import {
19
+ retireUnresolvable,
20
+ survivingSubset,
21
+ type RetirementReading,
22
+ } from "../lib/rule-retirement";
8
23
 
9
24
  // ── Types ────────────────────────────────────────────────────────
10
25
 
@@ -63,6 +78,32 @@ export interface ExtractResult {
63
78
  staleness: StalenessEntry[];
64
79
  /** What was planned against what was read. Never inferred from `candidates`. */
65
80
  coverage: ScanCoverage;
81
+ /**
82
+ * Observed failures mined from `fix:` and `Revert` commits (#545).
83
+ *
84
+ * Carried BESIDE `candidates` rather than merged into it, deliberately. The
85
+ * two populations answer different questions — "is this sentence
86
+ * rule-shaped" against "did something go wrong and cost us something" — and
87
+ * folding them together would move HYGIENE-6's advisory backlog count for a
88
+ * reason that has nothing to do with the backlog.
89
+ */
90
+ evidence: FailureIntakeReading;
91
+ /**
92
+ * Who survives, and why everything else did not (#544). Computed over BOTH
93
+ * populations, which is the point: the doc candidates are what the
94
+ * evidence-required criterion is being applied to.
95
+ */
96
+ promotion: PromotionReading;
97
+ /**
98
+ * What the generator stopped emitting, and why (#544, SC-1941).
99
+ *
100
+ * Separate from `promotion` for the same reason `evidence` is: a candidate
101
+ * dropped because the commit it cites was rebased away and one dropped
102
+ * because it ranked below the cut are different events with different
103
+ * repairs, and one `withheld` list carrying both would need a reader to
104
+ * tell them apart by reason string.
105
+ */
106
+ retirement: RetirementReading<EvidenceCandidate | Candidate>;
66
107
  /**
67
108
  * What was scanned and what could not be (#440).
68
109
  *
@@ -76,9 +117,14 @@ export interface ExtractResult {
76
117
 
77
118
  // ── Helpers ──────────────────────────────────────────────────────
78
119
 
79
- export function contentHash(text: string): string {
80
- return createHash("sha256").update(text.trim().toLowerCase()).digest("hex").slice(0, 12);
81
- }
120
+ // `contentHash` lives in `lib/content-hash.ts` now and is re-exported here
121
+ // under the name its callers already know — one binding, two names, the
122
+ // arrangement `lastCommitDates` has with `lib/conformity.ts` (#508). It moved
123
+ // because `lib/failure-intake.ts` is a second producer of candidates and the
124
+ // SC-137 veto table matches on this hash: two implementations of it would be
125
+ // behaviourally one until the day they disagreed, and the veto would silently
126
+ // stop applying to whichever producer used the other copy.
127
+ export { contentHash };
82
128
 
83
129
  function surroundingContext(lines: string[], lineIdx: number): string {
84
130
  const start = Math.max(0, lineIdx - 1);
@@ -273,12 +319,63 @@ export async function extractConstraints(
273
319
 
274
320
  const staleness = computeStaleness(projectPath, scanFiles);
275
321
 
276
- if (options?.apply && allCandidates.length > 0) {
277
- applyToAgentsMd(projectPath, allCandidates);
322
+ // #545. One bounded `git log`, after the document walk, so a repository
323
+ // without one costs nothing and a repository with one is read once.
324
+ const evidence = mineFixCommits(projectPath);
325
+
326
+ // #544. The doc candidates arrive with no `evidence` field at all, so the
327
+ // gate withholds every one of them. That is not a bug in the wiring — it is
328
+ // the measurement: signal-phrase extraction produces nothing a promotion
329
+ // criterion based on observed failure can promote.
330
+ // #544 SC-1941. Retirement runs BEFORE promotion and over both
331
+ // populations: a candidate citing a commit that was rebased away, or a
332
+ // `path:line` in a file that has since moved, is dropped rather than
333
+ // ranked. Recency is the only ordering signal the promoter has, so a
334
+ // candidate citing a vanished sha would otherwise rank at the very top.
335
+ //
336
+ // Its reading is folded into the promotion as an upstream, not merged into
337
+ // one here: `0 retired` on a shallow clone means the question could not be
338
+ // asked, and a promotion that reported MEASURED over that population would
339
+ // be claiming a completeness nothing established.
340
+ const retirement = retireUnresolvable(
341
+ [...evidence.candidates, ...allCandidates],
342
+ projectPath,
343
+ );
344
+
345
+ const promotion = promoteCandidates(
346
+ retirement.kept,
347
+ {
348
+ budget: PROMOTION_BUDGET_RULES,
349
+ rejectedHashes: rejectedHashes,
350
+ upstream: [evidence, retirement],
351
+ },
352
+ );
353
+
354
+ // #544. The gate has to reach the WRITE, or it is a control with no sink.
355
+ //
356
+ // Until this line, `--apply` wrote `allCandidates` — the unfiltered list —
357
+ // so a candidate the retirement pass had just dropped was written into
358
+ // `AGENTS.md` anyway and `retirement` was a field on the result that
359
+ // nothing downstream consulted. A gate whose verdict changes no output is
360
+ // not a fail-open; it is decoration.
361
+ //
362
+ // Filtered by object identity, not by hash: the same candidate objects
363
+ // flow through `retireUnresolvable`, and a hash is a judgement about a
364
+ // SENTENCE — two candidates mined from different positions can share one
365
+ // (`lib/failure-intake.ts` relies on exactly that for a revert and the fix
366
+ // it reverts), so matching on it would drop a survivor alongside a retired
367
+ // twin.
368
+ const keptDocCandidates = survivingSubset(allCandidates, retirement);
369
+
370
+ if (options?.apply && keptDocCandidates.length > 0) {
371
+ applyToAgentsMd(projectPath, keptDocCandidates);
278
372
  }
279
373
 
280
374
  return {
281
- candidates: allCandidates,
375
+ // The backlog HYGIENE-6 counts is the surviving population, for the same
376
+ // reason: re-reporting a candidate the generator has already retired
377
+ // asks somebody to triage a position that is not there any more.
378
+ candidates: keptDocCandidates,
282
379
  deduped: {
283
380
  existingConstraints: existingRemoved,
284
381
  rejectedPrior: rejectedRemoved,
@@ -286,6 +383,9 @@ export async function extractConstraints(
286
383
  },
287
384
  staleness,
288
385
  coverage: { planned: scanFiles.length, read, unread },
386
+ evidence,
387
+ retirement,
388
+ promotion,
289
389
  scan,
290
390
  };
291
391
  }
@@ -13,9 +13,8 @@ import { join, basename } from "path";
13
13
  import { localCalendarDay } from "../lib/local-calendar-day";
14
14
  import {
15
15
  fallowAvailable,
16
- fallowNotInstalled,
17
- fallowRunFailed,
18
16
  fallowUnmeasuredNotice,
17
+ runFallowJson,
19
18
  type FallowUnavailable,
20
19
  } from "../lib/fallow-availability";
21
20
 
@@ -55,34 +54,28 @@ function runFallow(): FallowOutcome {
55
54
  // path — once per consumer, forever, including behind a proxy and in an
56
55
  // air-gapped CI. `lib/conformity.ts` fixed this for itself in #510 and
57
56
  // this caller never got it.
58
- if (!fallowAvailable(projectPath) && !fallowAvailable(process.cwd())) {
59
- return { unavailable: fallowNotInstalled() };
60
- }
61
- const result = Bun.spawnSync(
62
- ["npx", "fallow", "dead-code", "--format", "json", "--quiet"],
63
- { cwd: projectPath, timeout: 30_000 }
64
- );
65
- const stdout = result.stdout.toString().trim();
66
- if (!stdout) return { unavailable: fallowRunFailed(`exit ${result.exitCode}, no output`) };
67
- if (stdout.startsWith("{\"error\"")) {
68
- return { unavailable: fallowRunFailed(stdout.slice(0, 200)) };
69
- }
70
- try {
71
- const d = JSON.parse(stdout);
72
- return { data: {
73
- entryPoints: d.entry_points?.total || 0,
74
- unusedFiles: (d.unused_files || []).map((f: any) => f.path),
75
- unusedExports: (d.unused_exports || []).map((e: any) => ({
76
- path: e.path, export_name: e.export_name, line: e.line
77
- })),
78
- circularDeps: (d.circular_dependencies || []).map((c: any) => ({
79
- files: c.files || [c.path]
80
- })),
81
- elapsed: d.elapsed_ms || 0,
82
- } };
83
- } catch (e) {
84
- return { unavailable: fallowRunFailed(`output did not parse as JSON (${(e as Error).name})`) };
85
- }
57
+ //
58
+ // The spawn, the budget and the classification are no longer here: they
59
+ // were a second copy of `lib/conformity.ts`'s, with a second `30_000`
60
+ // literal, and the two disagreed about what to do with a killed run. One
61
+ // binding now, in `lib/fallow-availability.ts` (#935). What stays here is
62
+ // the SHAPING of fallow's JSON into the fields CODE-MAP.md needs, which is
63
+ // this script's own business and nobody else's.
64
+ const root = fallowAvailable(projectPath) ? projectPath : process.cwd();
65
+ const reading = runFallowJson<any>(root, ["dead-code"]);
66
+ if ("unavailable" in reading) return { unavailable: reading.unavailable };
67
+ const d = reading.data;
68
+ return { data: {
69
+ entryPoints: d.entry_points?.total || 0,
70
+ unusedFiles: (d.unused_files || []).map((f: any) => f.path),
71
+ unusedExports: (d.unused_exports || []).map((e: any) => ({
72
+ path: e.path, export_name: e.export_name, line: e.line
73
+ })),
74
+ circularDeps: (d.circular_dependencies || []).map((c: any) => ({
75
+ files: c.files || [c.path]
76
+ })),
77
+ elapsed: d.elapsed_ms || 0,
78
+ } };
86
79
  }
87
80
 
88
81
  // ── Route scanning ───────────────────────────────────────────
@@ -114,4 +114,11 @@ if (fix) {
114
114
  // ── Report ─────────────────────────────────────────────────────
115
115
 
116
116
  // A refusal that only prints is one nobody's CI notices (#216).
117
- if (reportScaffoldActions(actions) > 0) process.exit(1);
117
+ //
118
+ // `!fix` is the mode, read from the same flag the branch above dispatches on
119
+ // rather than from a second variable that could disagree with it (#642). The
120
+ // notice at the top of the run is not enough on its own: a report line is
121
+ // what a grep, a `| tail`, a scrolled terminal and an agent reading the last
122
+ // N lines of a tool result each receive, and without this every one of them
123
+ // was byte-identical to the line a run that really wrote the file prints.
124
+ if (reportScaffoldActions(actions, { rehearsed: !fix }) > 0) process.exit(1);