rungate 0.6.0 → 0.8.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 (164) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +427 -0
  36. package/lib/agent-audit.ts +2 -3
  37. package/lib/agent-worktree.ts +287 -0
  38. package/lib/agents-md-sections.ts +81 -16
  39. package/lib/bash-write-guard.ts +373 -0
  40. package/lib/behavioral-cache.ts +150 -2
  41. package/lib/branch-cleanup.ts +279 -7
  42. package/lib/branch-protection.ts +790 -0
  43. package/lib/brief-ac-alignment.ts +104 -0
  44. package/lib/brief-references.ts +205 -0
  45. package/lib/bun-version.ts +93 -14
  46. package/lib/check-remedy.ts +140 -0
  47. package/lib/ci-checkout.ts +17 -0
  48. package/lib/ci-history-depth.ts +159 -0
  49. package/lib/ci-setup-step.ts +96 -0
  50. package/lib/claude-code-action.ts +85 -0
  51. package/lib/claude-tool-vocabulary.ts +188 -0
  52. package/lib/cli-commands.ts +15 -0
  53. package/lib/commit-sha.ts +42 -0
  54. package/lib/commit-subject.ts +90 -0
  55. package/lib/compliance-report.ts +377 -45
  56. package/lib/compliance.ts +191 -17
  57. package/lib/config-loader.ts +39 -1
  58. package/lib/config-trackable.ts +400 -0
  59. package/lib/conformity.ts +1087 -100
  60. package/lib/containment.ts +238 -0
  61. package/lib/content-hash.ts +24 -0
  62. package/lib/create-sc.ts +249 -16
  63. package/lib/dev-liveness.ts +180 -0
  64. package/lib/discovery-branch-points.ts +432 -0
  65. package/lib/discovery-stability.ts +481 -0
  66. package/lib/distribution-currency.ts +236 -0
  67. package/lib/doc-routing.ts +157 -0
  68. package/lib/evidence-prevalidator.ts +224 -2
  69. package/lib/evidence-satisfiability.ts +534 -12
  70. package/lib/failure-intake.ts +323 -0
  71. package/lib/fallow-availability.ts +157 -0
  72. package/lib/fs-write-capabilities.ts +232 -0
  73. package/lib/gate-enforcement.ts +222 -28
  74. package/lib/gate-names.ts +72 -0
  75. package/lib/gate-result-protection.ts +427 -0
  76. package/lib/gate-run-split.ts +147 -0
  77. package/lib/generators/agents-md.ts +140 -32
  78. package/lib/git-isolation.ts +140 -0
  79. package/lib/github.ts +15 -0
  80. package/lib/google-auth-action.ts +93 -0
  81. package/lib/harness-project.ts +48 -0
  82. package/lib/harness-provenance.ts +255 -0
  83. package/lib/hook-evidence.ts +235 -0
  84. package/lib/hook-scopes.ts +386 -0
  85. package/lib/hook-target-tree.ts +398 -0
  86. package/lib/hook-trees.ts +447 -0
  87. package/lib/intake-sources.ts +380 -0
  88. package/lib/js-top-level-code.ts +78 -10
  89. package/lib/junit-checks.ts +52 -0
  90. package/lib/late-env-spawn.ts +331 -0
  91. package/lib/launch-base.ts +376 -0
  92. package/lib/line-citation.ts +372 -0
  93. package/lib/orphan-reaper.ts +468 -0
  94. package/lib/parity-binding.ts +205 -0
  95. package/lib/paths.ts +96 -3
  96. package/lib/per-test-timeouts.ts +219 -0
  97. package/lib/phase2-decomposition.ts +1 -1
  98. package/lib/plan-coverage.ts +151 -0
  99. package/lib/prior-branch.ts +201 -8
  100. package/lib/process-table.ts +146 -0
  101. package/lib/project-state-derivation.ts +219 -0
  102. package/lib/project-state-root.ts +258 -0
  103. package/lib/published-artifact.ts +669 -0
  104. package/lib/readdir-sorted.ts +45 -0
  105. package/lib/review-execution-reading.ts +206 -0
  106. package/lib/review-tool-agreement.ts +433 -0
  107. package/lib/rule-promotion.ts +234 -0
  108. package/lib/rule-retirement.ts +525 -0
  109. package/lib/run-branch.ts +612 -0
  110. package/lib/rungate-schema.ts +19 -0
  111. package/lib/runner-home.ts +274 -0
  112. package/lib/sc-id-cross-tree.ts +103 -15
  113. package/lib/sc-ids.ts +121 -13
  114. package/lib/sc-reservations.ts +289 -0
  115. package/lib/scaffold/ai-review-findings.ts +409 -0
  116. package/lib/scaffold/ai-review-step.ts +5406 -64
  117. package/lib/scaffold/defaults.ts +82 -1
  118. package/lib/scaffold/managed-workflow.ts +587 -192
  119. package/lib/scaffold/owned-files.ts +152 -45
  120. package/lib/scaffold/pre-push-hook.ts +49 -5
  121. package/lib/scaffold/steps.ts +1836 -275
  122. package/lib/scaffold/workflow-census.ts +217 -0
  123. package/lib/scaffold/workflow-drift.ts +217 -0
  124. package/lib/scaffold/write-steps.ts +4 -0
  125. package/lib/scan-budget.ts +247 -0
  126. package/lib/scanner.ts +43 -51
  127. package/lib/scratch-roots.ts +50 -5
  128. package/lib/screenshot-discovery.ts +121 -0
  129. package/lib/screenshot-upload.ts +41 -1
  130. package/lib/secret-patterns.ts +511 -8
  131. package/lib/security-verdict.ts +1 -1
  132. package/lib/shell-path-interpolation.ts +594 -0
  133. package/lib/ship-mode.ts +219 -0
  134. package/lib/source-slice.ts +294 -0
  135. package/lib/stale-cleanup.ts +37 -3
  136. package/lib/suite-flake.ts +278 -0
  137. package/lib/suite-measurement.ts +23 -4
  138. package/lib/suite-run-reading.ts +241 -1
  139. package/lib/suite-timeout-margin.ts +193 -0
  140. package/lib/test-case-bodies.ts +883 -0
  141. package/lib/test-case-deletion.ts +653 -0
  142. package/lib/test-census.ts +97 -29
  143. package/lib/test-command-positions.ts +274 -0
  144. package/lib/test-suite-lock.ts +159 -16
  145. package/lib/text-dependents.ts +875 -0
  146. package/lib/tool-probe.ts +31 -9
  147. package/lib/top-level-cd.ts +393 -0
  148. package/lib/tree-entries.ts +89 -0
  149. package/lib/ts-ast.ts +200 -0
  150. package/lib/walk-test-files.ts +97 -0
  151. package/lib/workflow-actions.ts +263 -0
  152. package/lib/workflow-security.ts +29 -0
  153. package/lib/workflow-taint.ts +732 -0
  154. package/lib/worktree-cleanup.ts +65 -38
  155. package/lib/worktree-collect.ts +177 -5
  156. package/lib/worktree-repo.ts +68 -3
  157. package/package.json +4 -1
  158. package/scripts/ai-review-findings.ts +45 -0
  159. package/scripts/check-installed-hook-currency.ts +825 -0
  160. package/scripts/create-sc.ts +21 -1
  161. package/scripts/extract-constraints.ts +107 -7
  162. package/scripts/generate-code-map.ts +23 -30
  163. package/scripts/scaffold-project.ts +8 -1
  164. package/scripts/sync-sc-status.ts +77 -16
@@ -0,0 +1,372 @@
1
+ /**
2
+ * Read a `path.ts:<N>` citation, and refuse to call it correct (#541).
3
+ *
4
+ * `lib/source-anchor.ts` (#514) is the form this repository is moving TO: a
5
+ * citation that carries the text it is about, so the resolver reports the
6
+ * position instead of the document asserting it. This module is about the
7
+ * 231 citations still written the old way, and the measurement that says
8
+ * why they need a guard rather than a cleanup:
9
+ *
10
+ * Of `specs/GATE-CONTRACTS-SPEC.md`'s seven line citations, the three under
11
+ * a test were correct and **three of the four unguarded ones were already
12
+ * wrong** — `gate-executor.ts:1725` pointed at a `parseFloat`,
13
+ * `evidence-prevalidator.ts:208` at a comment, `scaffold-rungate-config.ts:66`
14
+ * at an unrelated `existsSync`. Each pointed at a plausible-looking line in
15
+ * the right file, and nobody had noticed because nothing could.
16
+ *
17
+ * Two readings follow from that, and both are refusals of a comfortable
18
+ * default:
19
+ *
20
+ * **There is no VALID.** `LineReading` has two arms. A citation that
21
+ * resolves is `UNMEASURED`, not correct: the file exists and the line
22
+ * exists, and whether it is the line the sentence describes is not something
23
+ * this code can decide. A 75% staleness rate in the unguarded half of one
24
+ * document is the argument against reporting "ok" — `0`, `null`, `SKIP` and
25
+ * a green tick are all indistinguishable from a correct answer, and a
26
+ * refusal naming the reading is not.
27
+ *
28
+ * **A citation that cannot be resolved has a named cause.** A file that
29
+ * moved, a bare basename, a basename matching two files, a line past the
30
+ * end — four different repairs, so four different readings. "This citation
31
+ * is broken" is not actionable; `steps.ts:43` is ambiguous between two files
32
+ * and `src/api/auth.ts:23` names nothing at all, and the fix for one is not
33
+ * the fix for the other.
34
+ *
35
+ * The enforcement splits the same way, which is the only honest split
36
+ * available: the anchor form is DECIDABLE, so `citationFailures` is a hard
37
+ * gate over every document in the tree; the line form is not, so the
38
+ * population is held by a both-ways ratchet that records what it banked.
39
+ */
40
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "fs";
41
+ import { join, resolve, sep } from "path";
42
+
43
+ import { anchorCitations, citationFailures } from "./source-anchor";
44
+
45
+ /**
46
+ * `path.ts:<N>`, optionally opening a code span.
47
+ *
48
+ * Deliberately NOT matching the historical prose form. "line 4462 of ship.js
49
+ * as it then stood" is a paragraph whose whole point is that the line no
50
+ * longer exists, and refusing it would be refusing the document for being
51
+ * about history. The two forms are distinguished by the colon and nothing
52
+ * else, which is why that boundary is asserted rather than described.
53
+ */
54
+ export const LINE_CITATION = /`?\b([A-Za-z0-9_./-]+\.(?:ts|js|json)):(\d+)\b/g;
55
+
56
+ export interface LineCitation {
57
+ path: string;
58
+ line: number;
59
+ raw: string;
60
+ }
61
+
62
+ export type BrokenCause =
63
+ | "NO_SUCH_FILE"
64
+ | "UNQUALIFIED_PATH"
65
+ | "AMBIGUOUS_PATH"
66
+ | "PAST_END_OF_FILE"
67
+ | "OUTSIDE_REPOSITORY";
68
+
69
+ /**
70
+ * Two arms. Adding a third that means "fine" would undo the whole module.
71
+ */
72
+ export type LineReading =
73
+ | { reading: "BROKEN"; cause: BrokenCause; cite: LineCitation; detail: string }
74
+ | { reading: "UNMEASURED"; cite: LineCitation; detail: string };
75
+
76
+ /** Raised when a document that should carry citations yields none (#621). */
77
+ export class NoLineCitationsError extends Error {
78
+ constructor(message: string) {
79
+ super(message);
80
+ this.name = "NoLineCitationsError";
81
+ }
82
+ }
83
+
84
+ /** Every line citation in a document, in order. */
85
+ export function lineCitations(doc: string): LineCitation[] {
86
+ const out: LineCitation[] = [];
87
+ // Anchor citations contain a path and a quoted fragment, and a fragment
88
+ // can end in `.ts:12`. Removing them first stops the new form being
89
+ // counted as an instance of the old one.
90
+ const text = doc.replace(/`[A-Za-z0-9_./-]+@"[^"`]*"`/g, " ");
91
+ for (const m of text.matchAll(LINE_CITATION)) {
92
+ out.push({ path: m[1], line: Number.parseInt(m[2], 10), raw: m[0] });
93
+ }
94
+ return out;
95
+ }
96
+
97
+ const SKIP_DIRS = new Set([
98
+ ".git",
99
+ "node_modules",
100
+ "worktrees",
101
+ "dist",
102
+ "build",
103
+ "coverage",
104
+ ".next",
105
+ ".bun",
106
+ ]);
107
+
108
+ function walk(root: string, rel: string, out: string[], want: (p: string) => boolean): void {
109
+ let entries;
110
+ try {
111
+ entries = readdirSync(join(root, rel), { withFileTypes: true });
112
+ } catch {
113
+ // A directory that cannot be read is not an empty directory. Nothing in
114
+ // this walk can repair that, but it must not be reported as "nothing
115
+ // here" either, so the caller's control — a floor on the count — is what
116
+ // catches it rather than a silent zero.
117
+ return;
118
+ }
119
+ for (const e of entries) {
120
+ if (e.name.startsWith(".") && e.name !== ".claude" && e.name !== ".github") continue;
121
+ const next = rel ? `${rel}/${e.name}` : e.name;
122
+ // `isDirectory()` is false for a symlink, which is what keeps the walk
123
+ // out of the `node_modules` link a worktree carries.
124
+ if (e.isDirectory()) {
125
+ if (SKIP_DIRS.has(e.name)) continue;
126
+ walk(root, next, out, want);
127
+ } else if (e.isFile() && want(next)) {
128
+ out.push(next);
129
+ }
130
+ }
131
+ }
132
+
133
+ /** Every repository-relative file path, for deciding whether a basename is unique. */
134
+ export function repoFileIndex(root: string): string[] {
135
+ const out: string[] = [];
136
+ walk(root, "", out, () => true);
137
+ return out.sort();
138
+ }
139
+
140
+ /** Every markdown document in the tree. */
141
+ export function markdownDocuments(root: string): string[] {
142
+ const out: string[] = [];
143
+ walk(root, "", out, p => p.endsWith(".md"));
144
+ return out.sort();
145
+ }
146
+
147
+ /**
148
+ * What a line citation can be said about, which is never that it is right.
149
+ */
150
+ export function readLineCitation(root: string, index: string[], cite: LineCitation): LineReading {
151
+ const { path } = cite;
152
+ const broken = (cause: BrokenCause, detail: string): LineReading =>
153
+ ({ reading: "BROKEN", cause, cite, detail });
154
+
155
+ // `join` concatenates a leading slash rather than absorbing it, so an
156
+ // absolute citation reads `<root>/etc/passwd` and the containment check
157
+ // below has nothing to say about it. Refused on its own, because a
158
+ // citation written absolute means something other than what its author
159
+ // thinks it means.
160
+ if (path.startsWith("/")) {
161
+ return broken("OUTSIDE_REPOSITORY", `${path} is absolute — citations are repository-relative`);
162
+ }
163
+ const full = join(root, path);
164
+ if (!resolve(full).startsWith(resolve(root) + sep)) {
165
+ return broken("OUTSIDE_REPOSITORY", `${path} resolves outside the repository`);
166
+ }
167
+
168
+ if (existsSync(full) && statSync(full).isFile()) {
169
+ // The symlink question the lexical check cannot answer: a link inside
170
+ // the tree whose target is outside it passes containment and then reads
171
+ // a file that is not in the repository at all.
172
+ if (!realpathSync(full).startsWith(realpathSync(resolve(root)) + sep)) {
173
+ return broken("OUTSIDE_REPOSITORY", `${path} is a symlink whose target is outside the repository`);
174
+ }
175
+ const lines = readFileSync(full, "utf-8").split("\n").length;
176
+ if (cite.line > lines) {
177
+ return broken("PAST_END_OF_FILE", `${path} has ${lines} lines, so line ${cite.line} is not in it`);
178
+ }
179
+ return {
180
+ reading: "UNMEASURED",
181
+ cite,
182
+ detail:
183
+ `${path}:${cite.line} names a line that exists; whether it is the line this sentence ` +
184
+ `describes cannot be decided mechanically`,
185
+ };
186
+ }
187
+
188
+ // Not a path in this repository. It may still be a basename somebody wrote
189
+ // instead of one, which is a different defect with a different repair.
190
+ const suffix = `/${path}`;
191
+ const candidates = index.filter(f => f === path || f.endsWith(suffix));
192
+ if (candidates.length === 0) {
193
+ return broken("NO_SUCH_FILE", `${path} names no file in the repository`);
194
+ }
195
+ if (candidates.length > 1) {
196
+ return broken(
197
+ "AMBIGUOUS_PATH",
198
+ `${path} matches ${candidates.length} files (${candidates.join(", ")}), so it names no site`,
199
+ );
200
+ }
201
+ return broken(
202
+ "UNQUALIFIED_PATH",
203
+ `${path} is not a repository path; it probably means ${candidates[0]}, and writing that down ` +
204
+ `is the repair`,
205
+ );
206
+ }
207
+
208
+ export interface DocumentCensus {
209
+ broken: number;
210
+ unmeasured: number;
211
+ anchors: number;
212
+ readings: LineReading[];
213
+ anchorFailures: string[];
214
+ }
215
+
216
+ /**
217
+ * Count one document's citations by reading.
218
+ *
219
+ * `expectCitations` is the ratchet's statement that this document carries
220
+ * some. When it does and none are found, this THROWS — because a checker
221
+ * that finds zero citations in every document is in perfect agreement, and
222
+ * zero strings are trivially all fine. Returning an empty census would fold
223
+ * a dead pattern into a clean result, which is the exact shape #621
224
+ * describes: the refusal has to escape.
225
+ */
226
+ export function documentCensus(
227
+ root: string,
228
+ index: string[],
229
+ docPath: string,
230
+ expectCitations: boolean,
231
+ ): DocumentCensus {
232
+ const full = join(root, docPath);
233
+ if (!existsSync(full)) {
234
+ throw new NoLineCitationsError(
235
+ `${docPath} is banked in the citation ratchet and is not in the tree. If the document was ` +
236
+ `removed or renamed, delete or move its entry in the same commit.`,
237
+ );
238
+ }
239
+ const text = readFileSync(full, "utf-8");
240
+ const cites = lineCitations(text);
241
+ if (expectCitations && cites.length === 0) {
242
+ throw new NoLineCitationsError(
243
+ `${docPath} is banked in the citation ratchet as carrying line citations and the census ` +
244
+ `found none. Either every one of them was converted — in which case delete the entry's ` +
245
+ `broken and unmeasured counts in the same commit — or LINE_CITATION has stopped matching, ` +
246
+ `in which case this guard was about to pass over the whole tree.`,
247
+ );
248
+ }
249
+ const readings = cites.map(c => readLineCitation(root, index, c));
250
+ return {
251
+ broken: readings.filter(r => r.reading === "BROKEN").length,
252
+ unmeasured: readings.filter(r => r.reading === "UNMEASURED").length,
253
+ anchors: anchorCitations(text).length,
254
+ readings,
255
+ anchorFailures: citationFailures(root, text),
256
+ };
257
+ }
258
+
259
+ export interface RatchetEntry {
260
+ broken: number;
261
+ unmeasured: number;
262
+ anchors: number;
263
+ note?: string;
264
+ }
265
+
266
+ export interface CitationRatchet {
267
+ meaning: string[];
268
+ documents: Record<string, RatchetEntry>;
269
+ }
270
+
271
+ /**
272
+ * The banked population, read from `.claude/line-citation-ratchet.json`.
273
+ *
274
+ * A tree with no file gets no entries — zero tolerance, which is the right
275
+ * default for a project that has never had the defect. `lib/` travels into
276
+ * every scaffolded project and rungate's own numbers have no business there.
277
+ */
278
+ export function readCitationRatchet(root: string): CitationRatchet {
279
+ const p = join(root, ".claude", "line-citation-ratchet.json");
280
+ if (!existsSync(p)) return { meaning: [], documents: {} };
281
+ const raw = JSON.parse(readFileSync(p, "utf-8"));
282
+ const documents: Record<string, RatchetEntry> = {};
283
+ for (const [k, v] of Object.entries(raw.documents ?? {})) {
284
+ const e = v as Record<string, unknown>;
285
+ if (typeof e?.broken !== "number" || typeof e?.unmeasured !== "number" || typeof e?.anchors !== "number") {
286
+ // A malformed entry is not an absent one. Skipping it silently would
287
+ // turn a typo into an exemption, which is the fail-open this file is
288
+ // about; the comparison below then reports the document as unbanked.
289
+ continue;
290
+ }
291
+ documents[k] = { broken: e.broken, unmeasured: e.unmeasured, anchors: e.anchors };
292
+ }
293
+ return { meaning: Array.isArray(raw.meaning) ? raw.meaning.map(String) : [], documents };
294
+ }
295
+
296
+ /**
297
+ * Turn the census into refusals. THE binding — one place to mutate.
298
+ *
299
+ * Both directions, per number. Over the banked count fails, and so does
300
+ * under it: an entry that has stopped being true is an entry nobody will
301
+ * ever remove, and the file rots into a number nobody lowers.
302
+ *
303
+ * Three numbers rather than one, because a single total cannot see progress
304
+ * happen. Qualifying `ship.js:<N>` to `workflows/ship.js:<N>` deletes
305
+ * nothing and adds nothing, and converting a line citation to the anchor
306
+ * form looks, to a total, exactly like deleting it. **The arithmetic cannot
307
+ * forbid a deletion — a paragraph is allowed to go away — so what it does
308
+ * instead is make the three numbers move differently, so a reviewer reading
309
+ * the diff can tell a conversion from a deletion.** That distinction is the
310
+ * point of the file and it is written into the file.
311
+ *
312
+ * Anchor citations are NOT ratcheted for correctness: an anchor carries its
313
+ * own text, so whether it still names a site is decidable, and there is
314
+ * nothing to tolerate. Their failures are returned as hard violations here
315
+ * for every document in the tree — enforce the half the repository owns,
316
+ * and report the other half as UNMEASURED.
317
+ */
318
+ export function citationRatchetViolations(
319
+ root: string,
320
+ index: string[],
321
+ docs: string[],
322
+ ratchet: CitationRatchet,
323
+ ): string[] {
324
+ const out: string[] = [];
325
+ const seen = new Set<string>();
326
+
327
+ for (const doc of docs) {
328
+ const entry = ratchet.documents[doc];
329
+ seen.add(doc);
330
+ const census = documentCensus(root, index, doc, (entry?.broken ?? 0) + (entry?.unmeasured ?? 0) > 0);
331
+
332
+ for (const f of census.anchorFailures) {
333
+ out.push(`${doc}: an anchor citation no longer names a site — ${f}`);
334
+ }
335
+
336
+ if (!entry) {
337
+ if (census.broken + census.unmeasured > 0) {
338
+ out.push(
339
+ `${doc} is not in .claude/line-citation-ratchet.json and carries ` +
340
+ `${census.broken + census.unmeasured} line citations. A document absent from the ratchet ` +
341
+ `is allowed none: the migration window is exactly when the next one gets written.`,
342
+ );
343
+ }
344
+ continue;
345
+ }
346
+
347
+ const rows: [keyof RatchetEntry & string, number, number][] = [
348
+ ["broken", census.broken, entry.broken],
349
+ ["unmeasured", census.unmeasured, entry.unmeasured],
350
+ ["anchors", census.anchors, entry.anchors],
351
+ ];
352
+ for (const [name, found, banked] of rows) {
353
+ if (found === banked) continue;
354
+ out.push(
355
+ found > banked
356
+ ? `${doc}: ${found} ${name} citations, ${banked} banked. Bank the number in the same ` +
357
+ `commit that earned it, and say in the PR why it went up.`
358
+ : `${doc}: ${found} ${name} citations, ${banked} banked. Lower it — or delete the entry ` +
359
+ `if the document has none left. A stale entry is a number nobody lowers.`,
360
+ );
361
+ }
362
+ }
363
+
364
+ for (const doc of Object.keys(ratchet.documents)) {
365
+ if (seen.has(doc)) continue;
366
+ out.push(
367
+ `${doc} is banked in .claude/line-citation-ratchet.json and was not among the documents ` +
368
+ `scanned. Delete its entry in the same commit that removed or renamed it.`,
369
+ );
370
+ }
371
+ return out;
372
+ }