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
@@ -0,0 +1,525 @@
1
+ /**
2
+ * Retire a candidate whose citation no longer resolves (#544, SC-1941).
3
+ *
4
+ * ## Why this is the half that makes the rest safe
5
+ *
6
+ * `lib/failure-intake.ts` mines candidates out of commit subjects and
7
+ * `scripts/extract-constraints.ts` mines them out of documents. Both cite a
8
+ * position: a commit sha, or a `path:line`. Neither has ever checked that the
9
+ * position is still there, and `lib/rule-promotion.ts` says so in its own
10
+ * WHAT THIS DOES NOT COVER:
11
+ *
12
+ * > Nothing reads whether the cited evidence still resolves. [...] a
13
+ * > candidate citing a commit that has been rebased away still ranks on its
14
+ * > date.
15
+ *
16
+ * That is not a theoretical gap in this repository. `main` is squash-merged
17
+ * and branches are rebased onto it constantly, so the sha a candidate was
18
+ * mined from is routinely not the sha that landed. A candidate citing one
19
+ * ranks top of the list — recency is the only ordering signal — and arrives
20
+ * at the top of the rule file pointing at nothing.
21
+ *
22
+ * Retirement is also the only thing in the lifecycle that REMOVES. A ladder
23
+ * that only adds degrades the thing it feeds: `docs/research/context-
24
+ * management.md` measures rule-set effectiveness collapsing past roughly
25
+ * sixteen rules, over the total in context. So the generator has to be able
26
+ * to stop emitting, and this is where it does.
27
+ *
28
+ * ## Retire, do not warn
29
+ *
30
+ * SC-1941 says *auto-retired, not warned about*, and the spec gives the
31
+ * reason three sections earlier: a warning is how 1,010 candidates
32
+ * accumulated. A retired candidate is dropped from the population the
33
+ * promoter ranks and reported with the detail that retired it. Nothing asks
34
+ * anybody to approve it.
35
+ *
36
+ * ## UNANSWERABLE IS NOT RESOLVED, AND IT IS NOT GONE EITHER
37
+ *
38
+ * This is the whole correctness question and it has a direction.
39
+ *
40
+ * `git cat-file -e <sha>` on a shallow clone answers "no" for every commit
41
+ * that predates the cut — including every commit that is perfectly fine
42
+ * upstream. `actions/checkout@v4` with no `fetch-depth` clones to depth 1, so
43
+ * a CI runner is in that state by default. A retirement check that read a
44
+ * shallow clone's "no" as GONE would retire the entire mined tier on its
45
+ * first CI run, and the diff would look like the system working.
46
+ *
47
+ * So there are three readings and not two: RESOLVES, GONE, and UNMEASURED —
48
+ * and UNMEASURED never retires anything. `lib/line-citation.ts` makes the
49
+ * same distinction for the same reason and is reused rather than reimplemented
50
+ * for the `path:line` form.
51
+ *
52
+ * ## WHAT THIS DOES NOT COVER
53
+ *
54
+ * Each is asserted as a case in `test/rule-retirement.test.ts`.
55
+ *
56
+ * - **A resolving citation is not a correct one.** `readLineCitation` returns
57
+ * UNMEASURED, never VALID, for a line that exists, because whether it is
58
+ * still the line the sentence describes cannot be decided mechanically. A
59
+ * sha that resolves says only that the commit is in this history. This
60
+ * module retires what is demonstrably gone and makes no claim about the
61
+ * rest.
62
+ * - **A citation form it does not recognise is UNMEASURED, so it survives.**
63
+ * A candidate whose `source` is neither `git:<sha>` nor `path:line` is
64
+ * kept, and the reading says it was not read. The other direction —
65
+ * retiring everything unrecognised — turns a parser gap into silent data
66
+ * loss, and a parser gap is the defect this repository has shipped most
67
+ * recently (`\Z` in a JavaScript regex, #1028).
68
+ * - **Nothing deletes an existing `.claude/rules/*.md` file.** Retirement
69
+ * happens at the generator: a retired candidate is not emitted on the next
70
+ * run, so the rule stops being written. A hand-edited rule is preserved by
71
+ * #370 and is not the generator's to retire.
72
+ */
73
+ import { spawnSync } from "child_process";
74
+ import { existsSync } from "fs";
75
+ import { join } from "path";
76
+ import { readLineCitation, repoFileIndex, type LineCitation } from "./line-citation";
77
+
78
+ /** Why a citation could not be answered. Exported so a caller compares against the producer's spelling. */
79
+ export const NOT_A_GIT_REPOSITORY = "RETIREMENT_NOT_A_GIT_REPOSITORY";
80
+ export const SHALLOW_HISTORY = "RETIREMENT_SHALLOW_HISTORY";
81
+ export const UNRECOGNISED_CITATION = "RETIREMENT_UNRECOGNISED_CITATION";
82
+ /** `git` could not be run, timed out, was signalled, or exited non-zero. */
83
+ export const GIT_UNREADABLE = "RETIREMENT_GIT_UNREADABLE";
84
+ /** The prefix matches more than one object, so it names no commit in particular. */
85
+ export const AMBIGUOUS_SHA = "RETIREMENT_AMBIGUOUS_SHA";
86
+ /** The object is in the tree and is not a commit. */
87
+ export const NOT_A_COMMIT = "RETIREMENT_NOT_A_COMMIT";
88
+ /** The batch returned, and returned nothing about this input. */
89
+ export const NO_BATCH_ANSWER = "RETIREMENT_NO_BATCH_ANSWER";
90
+
91
+ /**
92
+ * Every reason code, in the order a reading is searched for one.
93
+ *
94
+ * ONE declaring position, and the search is over the detail string the
95
+ * producer wrote rather than over the candidate. A reason re-derived at the
96
+ * consumer is a second decider for "why could this not be read", and it can
97
+ * name a cause the reading never gave — which is the two-projections-
98
+ * disagreeing shape this module's `reading`/`unmeasuredReasons` pair exists
99
+ * to avoid.
100
+ */
101
+ export const REASON_CODES = [
102
+ NOT_A_GIT_REPOSITORY,
103
+ SHALLOW_HISTORY,
104
+ GIT_UNREADABLE,
105
+ AMBIGUOUS_SHA,
106
+ NOT_A_COMMIT,
107
+ NO_BATCH_ANSWER,
108
+ UNRECOGNISED_CITATION,
109
+ ] as const;
110
+
111
+ export type CitationReading =
112
+ /** The position is in the tree. Says nothing about whether it is the right position. */
113
+ | { reading: "RESOLVES"; detail: string }
114
+ /** The position is demonstrably not in the tree. The only arm that retires. */
115
+ | { reading: "GONE"; detail: string }
116
+ /** The question could not be asked. Never retires. */
117
+ | { reading: "UNMEASURED"; detail: string };
118
+
119
+ /** `git:<sha>`, as `lib/failure-intake.ts` writes it. */
120
+ const GIT_SOURCE = /^git:([0-9a-f]{7,40})$/;
121
+ /** `<path>:<line>`, as `scripts/extract-constraints.ts` writes it. */
122
+ const LINE_SOURCE = /^(.+):(\d+)$/;
123
+
124
+ /**
125
+ * The deadline for the whole pass, not for one call.
126
+ *
127
+ * It is a TOTAL because there is exactly one `git cat-file` subprocess for
128
+ * the entire population — see `batchCheckShas`. A per-candidate timeout with
129
+ * a per-candidate subprocess gives N x 60s, which is not a bound.
130
+ */
131
+ export const GIT_TIMEOUT_MS = 60_000;
132
+
133
+ interface GitResult {
134
+ /** True only when git ran to completion and exited 0. */
135
+ ok: boolean;
136
+ out: string;
137
+ /** Why it is not ok, in git's own words where there are any. */
138
+ detail: string;
139
+ }
140
+
141
+ /**
142
+ * The four fields `git()` reads off a spawn, and nothing else.
143
+ *
144
+ * Narrower than `SpawnSyncReturns` on purpose: these are exactly the values
145
+ * the branches below decide on, so a reading handed to the seam cannot
146
+ * accidentally carry a field the decision never consults.
147
+ */
148
+ export interface GitSpawnReading {
149
+ error?: Error;
150
+ signal?: NodeJS.Signals | null;
151
+ status?: number | null;
152
+ stdout?: string | null;
153
+ stderr?: string | null;
154
+ }
155
+
156
+ export type GitSpawner = (
157
+ root: string,
158
+ args: readonly string[],
159
+ stdin: string | undefined,
160
+ timeoutMs: number,
161
+ ) => GitSpawnReading;
162
+
163
+ /**
164
+ * The ONE spawn this module makes, exported so the kill path has a witness.
165
+ *
166
+ * There is no way to make git hang on demand, so `r.error` and `r.signal`
167
+ * are otherwise branches no case reaches — and an unreachable branch is the
168
+ * shape this repository pays for most. The previous attempt at a witness was
169
+ * a real 1 ms deadline at a real repository, which asserts that git LOSES a
170
+ * race: on a warm runner git wins it, the read is RESOLVES, and `main` goes
171
+ * red accusing code that is behaving correctly (#1063). Worse, the runner
172
+ * that produced that failure answered in 19.53 ms, so the 1 ms deadline was
173
+ * not enforced there at all — which also rules out pointing the deadline at
174
+ * a command that cannot finish, because on a platform that drops the
175
+ * deadline that command does not finish.
176
+ *
177
+ * So the kill is injected rather than raced for. A seam is a default
178
+ * parameter the production path always takes; a flag read inside the
179
+ * decision would be a second decider, which is the thing to avoid.
180
+ */
181
+ export const spawnGit: GitSpawner = (root, args, stdin, timeoutMs) =>
182
+ spawnSync("git", ["-C", root, ...args], {
183
+ timeout: timeoutMs,
184
+ maxBuffer: 16 * 1024 * 1024,
185
+ encoding: "utf-8",
186
+ input: stdin,
187
+ });
188
+
189
+ /**
190
+ * Run git and say whether the ANSWER is usable, not merely what it exited.
191
+ *
192
+ * A boolean `ok` rather than a status number, because the one thing callers
193
+ * here must never do is compare an exit code against a literal. `git
194
+ * cat-file -e <sha>^{commit}` — the first implementation of this module —
195
+ * exits 128 for a missing object, and 128 for a broken repository, and 128
196
+ * for an unreadable object store, and 128 for bad ref syntax. Measured, not
197
+ * assumed:
198
+ *
199
+ * missing object exit=128
200
+ * not a repository exit=128
201
+ * malformed ref syntax exit=128
202
+ * unreadable object store exit=128
203
+ * present object exit=0
204
+ *
205
+ * So `status !== 0 -> GONE` read four different events as "retire this
206
+ * rule", and the narrower repair of treating only 0 and 1 as answers reads
207
+ * all five as "cannot tell" and retires nothing, ever. Neither is a
208
+ * measurement. The fix is not a better threshold on that exit code; it is
209
+ * `--batch-check`, which reports absence, ambiguity and type in its OUTPUT
210
+ * and reserves a non-zero exit for not having run.
211
+ */
212
+ function git(
213
+ root: string,
214
+ args: string[],
215
+ stdin?: string,
216
+ timeoutMs = GIT_TIMEOUT_MS,
217
+ spawn: GitSpawner = spawnGit,
218
+ ): GitResult {
219
+ const r = spawn(root, args, stdin, timeoutMs);
220
+ // A timeout arrives as `error` on some platforms and as `signal` on
221
+ // others, and reading only `status` makes a killed process look like a
222
+ // clean non-zero exit. Both are checked, and both are named in `detail`
223
+ // so a timeout is visible in the reading as a timeout.
224
+ if (r.error) return { ok: false, out: "", detail: `git ${args[0]}: ${r.error.message}` };
225
+ if (r.signal) return { ok: false, out: "", detail: `git ${args[0]}: killed by ${r.signal}` };
226
+ if (r.status !== 0) {
227
+ return {
228
+ ok: false,
229
+ out: r.stdout ?? "",
230
+ detail: `git ${args[0]} exited ${r.status}: ${(r.stderr ?? "").trim() || "(no stderr)"}`,
231
+ };
232
+ }
233
+ return { ok: true, out: r.stdout ?? "", detail: "" };
234
+ }
235
+
236
+ /**
237
+ * The state of the repository that every sha question is answered against.
238
+ *
239
+ * Read ONCE per retirement pass rather than per candidate: two `git` calls
240
+ * for a thousand candidates, and — more to the point — one answer, so a
241
+ * population cannot contain candidates judged against different beliefs
242
+ * about whether the history is complete.
243
+ */
244
+ export interface HistoryState {
245
+ /** `git cat-file` can be asked at all. */
246
+ readable: boolean;
247
+ /** The clone is truncated, so an absent sha means nothing. */
248
+ shallow: boolean;
249
+ }
250
+
251
+ export function readHistoryState(root: string): HistoryState {
252
+ if (!existsSync(join(root, ".git"))) return { readable: false, shallow: false };
253
+ const shallow = git(root, ["rev-parse", "--is-shallow-repository"]);
254
+ return {
255
+ readable: true,
256
+ // A `rev-parse` that could not run is not a repository with full history.
257
+ shallow: !shallow.ok || shallow.out.trim() === "true",
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Ask git about every sha in ONE subprocess, and keep the four answers apart.
263
+ *
264
+ * `git cat-file --batch-check` emits exactly one line per input line, in
265
+ * input order, and says which of four things happened — measured on this
266
+ * repository:
267
+ *
268
+ * <full oid> commit <size> the commit is here
269
+ * <input> missing no object of that name
270
+ * <input> ambiguous the prefix matches more than one object
271
+ * <full oid> tree <size> the name resolves, and not to a commit
272
+ *
273
+ * and exits 0 for all four, reserving non-zero for not having run at all.
274
+ * That separation is the whole reason to use it: absence and failure-to-look
275
+ * become different OBSERVATIONS rather than two values of one exit code, and
276
+ * only the first of them is allowed to retire anything.
277
+ *
278
+ * Only `missing` returns GONE. `ambiguous` does not — an eight-character
279
+ * prefix that matches two objects names no commit in particular, and
280
+ * `lib/failure-intake.ts` writes eight-character prefixes, so this is a real
281
+ * state in a repository this size rather than a hypothetical one.
282
+ *
283
+ * Results are zipped by INDEX, because git echoes the resolved oid for an
284
+ * input it resolved and the raw input for one it did not — so a map keyed by
285
+ * the input silently loses every short sha that worked. A line count that
286
+ * does not match the input count is not a partial answer; the whole batch is
287
+ * UNMEASURED, because nothing then says which line answered which input.
288
+ */
289
+ export function batchCheckShas(
290
+ root: string,
291
+ shas: readonly string[],
292
+ history: HistoryState,
293
+ /** The TOTAL deadline for the pass, threaded to the one spawn below. */
294
+ timeoutMs = GIT_TIMEOUT_MS,
295
+ /** The one spawn, injectable so the kill path has a witness — see `spawnGit`. */
296
+ spawn: GitSpawner = spawnGit,
297
+ ): Map<string, CitationReading> {
298
+ const out = new Map<string, CitationReading>();
299
+ if (shas.length === 0) return out;
300
+
301
+ const all = (reading: CitationReading) => {
302
+ for (const sha of shas) out.set(sha, reading);
303
+ return out;
304
+ };
305
+
306
+ if (!history.readable) {
307
+ return all({
308
+ reading: "UNMEASURED",
309
+ detail: `${root} is not a git repository, so no sha can be looked up (${NOT_A_GIT_REPOSITORY})`,
310
+ });
311
+ }
312
+ if (history.shallow) {
313
+ return all({
314
+ reading: "UNMEASURED",
315
+ detail:
316
+ `the clone is shallow, so an absent commit means the history was truncated and not ` +
317
+ `that the commit is gone (${SHALLOW_HISTORY})`,
318
+ });
319
+ }
320
+
321
+ const r = git(root, ["cat-file", "--batch-check"], shas.join("\n") + "\n", timeoutMs, spawn);
322
+ if (!r.ok) {
323
+ return all({ reading: "UNMEASURED", detail: `${r.detail} (${GIT_UNREADABLE})` });
324
+ }
325
+
326
+ const lines = r.out.split("\n").filter(l => l.length > 0);
327
+ if (lines.length !== shas.length) {
328
+ return all({
329
+ reading: "UNMEASURED",
330
+ detail:
331
+ `cat-file --batch-check answered ${lines.length} of ${shas.length} inputs, so no line ` +
332
+ `can be attributed to an input (${NO_BATCH_ANSWER})`,
333
+ });
334
+ }
335
+
336
+ shas.forEach((sha, i) => {
337
+ const parts = lines[i]!.split(" ");
338
+ const verdict = parts[1] ?? "";
339
+ if (verdict === "missing") {
340
+ out.set(sha, { reading: "GONE", detail: `git:${sha} names no object in this history` });
341
+ } else if (verdict === "ambiguous") {
342
+ out.set(sha, {
343
+ reading: "UNMEASURED",
344
+ detail: `git:${sha} matches more than one object, so it names no commit (${AMBIGUOUS_SHA})`,
345
+ });
346
+ } else if (verdict === "commit") {
347
+ out.set(sha, { reading: "RESOLVES", detail: `git:${sha} is a commit in this history` });
348
+ } else {
349
+ out.set(sha, {
350
+ reading: "UNMEASURED",
351
+ detail: `git:${sha} resolves to a ${verdict || "(unreadable)"}, not a commit (${NOT_A_COMMIT})`,
352
+ });
353
+ }
354
+ });
355
+ return out;
356
+ }
357
+
358
+ /**
359
+ * THE resolver. One binding, so there is one thing to mutate.
360
+ *
361
+ * `index` is `repoFileIndex(root)`, hoisted for the same reason as
362
+ * `HistoryState`: it is the file list the `path:line` arm is answered
363
+ * against, and computing it per candidate would let two candidates disagree
364
+ * about what is in the tree.
365
+ */
366
+ export function resolveCitation(
367
+ root: string,
368
+ source: string,
369
+ index: string[],
370
+ shaReadings: ReadonlyMap<string, CitationReading>,
371
+ ): CitationReading {
372
+ const sha = GIT_SOURCE.exec(source);
373
+ if (sha) {
374
+ // The sha arm is answered by `batchCheckShas`, once, for the whole
375
+ // population. Looking it up here rather than asking git again is what
376
+ // keeps one binding: a second place deciding "is this commit present"
377
+ // could disagree with the batch, and on a shallow clone the two
378
+ // disagreeing means one of them retires a rule the other kept.
379
+ return (
380
+ shaReadings.get(sha[1]!) ?? {
381
+ reading: "UNMEASURED",
382
+ detail: `${source}: the batch returned no answer for it (${NO_BATCH_ANSWER})`,
383
+ }
384
+ );
385
+ }
386
+
387
+ const line = LINE_SOURCE.exec(source);
388
+ if (line) {
389
+ const cite: LineCitation = { path: line[1]!, line: Number(line[2]), raw: source };
390
+ const read = readLineCitation(root, index, cite);
391
+ // `readLineCitation` has two arms and neither says "correct". BROKEN is
392
+ // the one that names a position that is not there; its UNMEASURED means
393
+ // the line exists and whether it is the right line is undecidable, which
394
+ // is a reason to KEEP.
395
+ return read.reading === "BROKEN"
396
+ ? { reading: "GONE", detail: `${source}: ${read.detail}` }
397
+ : { reading: "RESOLVES", detail: `${source}: ${read.detail}` };
398
+ }
399
+
400
+ return {
401
+ reading: "UNMEASURED",
402
+ detail: `${source}: not a citation form this module reads (${UNRECOGNISED_CITATION})`,
403
+ };
404
+ }
405
+
406
+ /** The minimum a candidate needs to be judged. Structurally what `PromotableCandidate` is. */
407
+ export interface CitingCandidate {
408
+ source: string;
409
+ hash: string;
410
+ }
411
+
412
+ export interface RetiredCandidate<T> {
413
+ candidate: T;
414
+ detail: string;
415
+ }
416
+
417
+ export interface RetirementReading<T> {
418
+ /**
419
+ * The single discriminator. `unmeasuredReasons` is the other projection of
420
+ * the same computation, so the two cannot disagree.
421
+ */
422
+ reading: "MEASURED" | "UNMEASURED";
423
+ unmeasuredReasons: string[];
424
+ /** Survivors, in input order. The population the promoter ranks. */
425
+ kept: T[];
426
+ /** Dropped, each with the detail that dropped it. */
427
+ retired: RetiredCandidate<T>[];
428
+ /** Judged but unanswerable. Kept, and counted here so the silence is visible. */
429
+ unread: RetiredCandidate<T>[];
430
+ }
431
+
432
+ /**
433
+ * Drop every candidate whose citation is demonstrably gone.
434
+ *
435
+ * A pass over a repository whose history cannot be read retires NOTHING and
436
+ * says so. `0 retired` from a shallow clone and `0 retired` from a tree where
437
+ * every citation is good are the same empty list, and only the reading tells
438
+ * them apart — which is the shape `.claude/rules/checks-must-be-able-to-
439
+ * fail.md` is about and the one this module is most likely to take.
440
+ */
441
+ export function retireUnresolvable<T extends CitingCandidate>(
442
+ candidates: readonly T[],
443
+ root: string,
444
+ ): RetirementReading<T> {
445
+ const history = readHistoryState(root);
446
+ const index = repoFileIndex(root);
447
+
448
+ // Every sha in one subprocess, before the loop. Two `git` calls for the
449
+ // whole pass — this and `readHistoryState` — so `GIT_TIMEOUT_MS` is the
450
+ // TOTAL deadline rather than a per-candidate one that multiplies.
451
+ //
452
+ // The `new Set` is an EFFICIENCY measure and has no behavioural witness:
453
+ // a duplicated sha gets the same answer twice and the map keyed by sha is
454
+ // identical either way. Recorded as such rather than covered by a case
455
+ // that would pass with or without it.
456
+ const shas = [...new Set(
457
+ candidates.map(c => GIT_SOURCE.exec(c.source)?.[1]).filter((s): s is string => !!s),
458
+ )];
459
+ const shaReadings = batchCheckShas(root, shas, history);
460
+
461
+ const kept: T[] = [];
462
+ const retired: RetiredCandidate<T>[] = [];
463
+ const unread: RetiredCandidate<T>[] = [];
464
+ const reasons = new Set<string>();
465
+
466
+ for (const candidate of candidates) {
467
+ const read = resolveCitation(root, candidate.source, index, shaReadings);
468
+ if (read.reading === "GONE") {
469
+ retired.push({ candidate, detail: read.detail });
470
+ continue;
471
+ }
472
+ kept.push(candidate);
473
+ if (read.reading === "UNMEASURED") {
474
+ unread.push({ candidate, detail: read.detail });
475
+ // The reason is read off the DETAIL the producer wrote, not
476
+ // re-derived from the candidate here. Re-deriving it was the first
477
+ // version and it was a second decider: it could name SHALLOW_HISTORY
478
+ // for a reading that actually said AMBIGUOUS_SHA, and the two would
479
+ // never be compared.
480
+ reasons.add(
481
+ REASON_CODES.find(code => read.detail.includes(code)) ?? UNRECOGNISED_CITATION,
482
+ );
483
+ }
484
+ }
485
+
486
+ const unmeasuredReasons = [...reasons].sort();
487
+ return {
488
+ reading: unmeasuredReasons.length > 0 ? "UNMEASURED" : "MEASURED",
489
+ unmeasuredReasons,
490
+ kept,
491
+ retired,
492
+ unread,
493
+ };
494
+ }
495
+
496
+ /**
497
+ * The members of `subset` that survived a retirement pass over a population
498
+ * containing them.
499
+ *
500
+ * Exported because it is the SINK: `scripts/extract-constraints.ts` writes
501
+ * what this returns, and a filter spelled inline there is a filter a test can
502
+ * only check by writing the same expression a second time — which asserts
503
+ * that the test agrees with itself. One binding, one thing to mutate.
504
+ *
505
+ * Identity, not hash. A hash is a judgement about a SENTENCE, and
506
+ * `lib/failure-intake.ts` relies on two candidates sharing one for a revert
507
+ * and the fix it reverts, so matching on the hash would drop a survivor
508
+ * alongside a retired twin.
509
+ */
510
+ export function survivingSubset<T extends CitingCandidate, S extends T>(
511
+ subset: readonly S[],
512
+ reading: RetirementReading<T>,
513
+ ): S[] {
514
+ const survived = new Set<T>(reading.kept);
515
+ return subset.filter((c) => survived.has(c));
516
+ }
517
+
518
+ /** One line a caller can print without re-deriving any of the above. */
519
+ export function retirementSummary(reading: RetirementReading<unknown>): string {
520
+ return (
521
+ `retirement ${reading.reading}: ${reading.retired.length} retired, ` +
522
+ `${reading.kept.length} kept, ${reading.unread.length} unread` +
523
+ (reading.unmeasuredReasons.length > 0 ? ` — ${reading.unmeasuredReasons.join("; ")}` : "")
524
+ );
525
+ }