rungate 0.8.13 → 0.8.16

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 (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -43,11 +43,7 @@ import {
43
43
  readAiReviewFindingsFile,
44
44
  } from "../lib/scaffold/ai-review-findings";
45
45
  import { carryKey } from "../lib/ai-review-rounds";
46
- import {
47
- aiReviewSuppressionGate,
48
- checkoutLineText,
49
- readOrNull,
50
- } from "../lib/ai-review-suppression";
46
+ import { productionSuppression } from "../lib/ai-review-suppression";
51
47
  import { AI_REVIEW_THREADS_PATH_VAR } from "../lib/scaffold/ai-review-step";
52
48
 
53
49
  const COMMAND = "ai-review-threads";
@@ -132,14 +128,17 @@ if (!parsed.ok) {
132
128
  // agree until they do not. This step runs BEFORE the adjudicator in the
133
129
  // emitted job, so it cannot be handed the adjudicator's answer — it has to
134
130
  // form its own from the same input.
135
- const threadsPath = process.env[AI_REVIEW_THREADS_PATH_VAR];
136
- const suppress =
137
- threadsPath === undefined || threadsPath === ""
138
- ? null
139
- : aiReviewSuppressionGate({
140
- threads: readOrNull(threadsPath),
141
- lineTextFor: checkoutLineText(process.cwd()),
142
- });
131
+ //
132
+ // That sentence was true of the FUNCTION and false of its INPUTS while each
133
+ // command wrote its own object literal: #1861 added `anchorOccurrences` to
134
+ // the adjudicator alone, and the whole anchor rule was dead here — in the
135
+ // command that posts the threads, which is the half #1616's 11-threads-for-3
136
+ // measurement is about. `productionSuppression` is now the only assembly
137
+ // site, and AS-15 holds it that way.
138
+ const { gate: suppress, lineTextFor } = productionSuppression(
139
+ process.env[AI_REVIEW_THREADS_PATH_VAR],
140
+ process.cwd(),
141
+ );
143
142
 
144
143
  const reading = readAiReviewFindingsFile(
145
144
  parsed.findings,
@@ -175,12 +174,12 @@ const post: AiReviewThreadPoster = async request => {
175
174
 
176
175
  // THE KEY-SYMMETRY HALF, on the producing side. The thread carries the key
177
176
  // a later round's suppression gate will form for the same finding, so the
178
- // text anchor must be read the same way both sides read it — which is why
179
- // this is `checkoutLineText` and not a second line reader. A caller that
177
+ // text anchor must be read the same way both sides read it. A caller that
180
178
  // supplied no text would key `n:<line>` while the gate keys `t:<text>`, and
181
179
  // the two namespaces never collide: the gate would suppress nothing and
182
- // every round would re-post every thread.
183
- const lineTextFor = checkoutLineText(process.cwd());
180
+ // every round would re-post every thread. `lineTextFor` comes off the SAME
181
+ // reader the gate above was built from, so it is the same cache and the same
182
+ // normalisation rather than a second one that happens to agree.
184
183
  const result = await postReviewThreads(reading, post, f => carryKey(f, lineTextFor(f)));
185
184
  for (const line of result.detail) console.log(`${COMMAND}: ${line}`);
186
185
  console.log(
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Refuse a pull request whose closing keyword GitHub will never act on (#1362).
3
+ *
4
+ * Usage (the payload is `gh pr view`-shaped: number, body, files[].path, and
5
+ * closingIssuesReferences nodes that carry each issue body — the workflow
6
+ * builds it from one GraphQL query):
7
+ * <payload> | bun scripts/audit-closing-references.ts --repo owner/name
8
+ * bun scripts/audit-closing-references.ts --fixture <file.json> --repo owner/name # offline
9
+ *
10
+ * ## Why this reads a payload instead of calling the API
11
+ *
12
+ * The reading it needs — `closingIssuesReferences` — is GitHub's own answer to
13
+ * the question the check is about, and the one thing this script must not do
14
+ * is compute its own version of it. Taking the field as input makes that a
15
+ * structural impossibility rather than a convention: there is no code path
16
+ * here that could decide an issue is linked.
17
+ *
18
+ * It also makes the whole check runnable offline against a fixture, which is
19
+ * how `test/audit-closing-references.test.ts` exercises the refusal without a
20
+ * network or a token.
21
+ *
22
+ * ## What it refuses, and what it deliberately does not
23
+ *
24
+ * Four refusals, in the order the script reaches them. The first two refuse
25
+ * whatever `RUNGATE_REQUIRE_CLOSING_REF` says; the last two only when it is
26
+ * the string `true`, and are an annotation otherwise.
27
+ *
28
+ * 1. **An inert reference:** a closing keyword beside an issue number inside
29
+ * markup the markdown parser does not scan, for an issue GitHub did not
30
+ * link. The author wrote a closing reference and GitHub recorded none —
31
+ * the state that left #1157 open after PR #1208 merged.
32
+ * 2. **A commit message that closes an undeclared issue (#1979):** GitHub
33
+ * acts on a keyword in a commit message wherever it sits, and this
34
+ * repository squashes with the messages as the body.
35
+ * 3. **No issue closed, or one that has not answered the criterion question**
36
+ * (ADR-013 step 4, #2061).
37
+ * 4. **A closed issue naming a criterion this tree leaves unticked**, unless
38
+ * the description says `does not complete <id>` (#2005).
39
+ *
40
+ * A payload missing a field any of these reads is UNMEASURED and refused.
41
+ *
42
+ * It does NOT refuse a pull request that merely mentions an issue without
43
+ * closing it. Measured at 2026-10-23T15:31Z, 27 of the 50 open issues had a
44
+ * merged pull request referencing them and 26 of those were discussion
45
+ * mentions — `#1204's class`, `#1286 is open about this`. A check that fired
46
+ * on a mention would be wrong 26 times out of 27 on the only corpus
47
+ * available, and a check wrong that often is one people route around.
48
+ *
49
+ * ONE PROPERTY THIS FILE MUST KEEP, asserted by its test: every refusal exits
50
+ * through REFUSE_EXIT, declared exactly once.
51
+ */
52
+
53
+ import { readFileSync } from "fs";
54
+ import {
55
+ type ClosedIssue,
56
+ type ClosingCriteria,
57
+ closingCriteria,
58
+ closingRequirement,
59
+ closingRequirementMessage,
60
+ commitClosingMessage,
61
+ commitClosingReferences,
62
+ inertClosingMessage,
63
+ inertClosingReferences,
64
+ isSessionRecordOnly,
65
+ linkedIssuesInThisRepo,
66
+ } from "../lib/closing-reference-audit";
67
+
68
+ /** The one exit code every refusal travels through. */
69
+ export const REFUSE_EXIT = 1;
70
+
71
+ function arg(name: string): string | null {
72
+ const i = process.argv.indexOf(`--${name}`);
73
+ return i !== -1 && i + 1 < process.argv.length ? process.argv[i + 1]! : null;
74
+ }
75
+
76
+ /**
77
+ * A payload that could not be read is UNMEASURED, not a pass.
78
+ *
79
+ * `.claude/rules/config-access.md`'s *Silent Default Substitution*: an
80
+ * unparseable payload and a clean pull request must not produce the same
81
+ * exit, or the check switches itself off the first time the input shape
82
+ * moves.
83
+ */
84
+ function refuse(message: string): never {
85
+ console.error(`CLOSING-REFERENCE REFUSED: ${message}`);
86
+ process.exit(REFUSE_EXIT);
87
+ }
88
+
89
+ async function readPayload(): Promise<string> {
90
+ const fixture = arg("fixture");
91
+ if (fixture) return readFileSync(fixture, "utf-8");
92
+ if (process.stdin.isTTY) {
93
+ refuse("no payload on stdin and no --fixture. See the usage at the top of this file.");
94
+ }
95
+ return await new Response(process.stdin as unknown as ReadableStream).text();
96
+ }
97
+
98
+ async function main(): Promise<void> {
99
+ const raw = (await readPayload()).trim();
100
+ if (!raw) refuse("the payload is empty, so no reading was taken. This is UNMEASURED, not a clean pull request.");
101
+
102
+ let pr: { number?: number; body?: string; files?: unknown; closingIssuesReferences?: unknown };
103
+ try {
104
+ pr = JSON.parse(raw);
105
+ } catch (e) {
106
+ refuse(`the payload is not JSON (${(e as Error).message}). UNMEASURED, not clean.`);
107
+ }
108
+
109
+ // An absent key and an empty list are different facts, and only one of them
110
+ // is a reading — #530's shape. A payload fetched without the field would
111
+ // otherwise look exactly like a pull request that closes nothing.
112
+ if (!("closingIssuesReferences" in pr) || !Array.isArray(pr.closingIssuesReferences)) {
113
+ refuse(
114
+ "the payload carries no closingIssuesReferences array, so the field this check " +
115
+ "compares against was never fetched. Add it to the --json list. UNMEASURED, not clean.",
116
+ );
117
+ }
118
+ if (typeof pr.body !== "string") {
119
+ refuse("the payload carries no body string. Add `body` to the --json list. UNMEASURED, not clean.");
120
+ }
121
+ // ADR-013, SC-2737. Same shape as the two readings above, for the same
122
+ // reason: a payload fetched without the changed files would look exactly
123
+ // like a pull request that touches nothing, and "all session-record files"
124
+ // is the one exemption this check grants. Absent is NOT READ, and NOT READ
125
+ // is not a pass.
126
+ if (!Array.isArray(pr.files)) {
127
+ refuse(
128
+ "the payload carries no files array, so whether this pull request changes only " +
129
+ "session-record files was never read. Add `files` to the query. UNMEASURED, not clean.",
130
+ );
131
+ }
132
+ const changedPaths = (pr.files as unknown[]).map(f =>
133
+ f !== null && typeof f === "object" && typeof (f as { path?: unknown }).path === "string"
134
+ ? (f as { path: string }).path
135
+ : "",
136
+ );
137
+ if (changedPaths.includes("")) {
138
+ refuse("a changed file in the payload carries no path string. UNMEASURED, not clean.");
139
+ }
140
+
141
+ const prNumber = typeof pr.number === "number" ? pr.number : 0;
142
+ const linked = pr.closingIssuesReferences as unknown[];
143
+ // The linked set is read for its ISSUE NUMBERS, not for its length.
144
+ //
145
+ // This used to return early whenever `linked.length > 0`, and that let the
146
+ // defect through one issue over: a pull request that correctly links #A and
147
+ // also carries a backticked `Fixes #B` passed clean, #B never closed, and
148
+ // #B is then an open issue with a merged pull request — the exact symptom
149
+ // this script exists to find. The contradiction the docblock describes is
150
+ // not "GitHub recorded nothing", it is "the author wrote a closing
151
+ // reference GitHub did not record", and a non-empty linked set does not
152
+ // make that false for a DIFFERENT issue.
153
+ //
154
+ // An entry whose number is unreadable contributes nothing to this set,
155
+ // which is the safe direction: it can only cause an inert reference to be
156
+ // reported, never suppressed.
157
+ // SCOPED TO THIS REPOSITORY — ai-review round 2 of #1978. A bare `number`
158
+ // is not an identity: `Fixes other-org/other-repo#9` is documented GitHub
159
+ // syntax and lands a node numbered 9 here. Counting it let a pull request
160
+ // satisfy its own closing requirement with somebody else's issue.
161
+ const repoNameWithOwner = arg("repo");
162
+ if (repoNameWithOwner === null || !repoNameWithOwner.includes("/")) {
163
+ refuse(
164
+ "no --repo owner/name was given, so a closing reference cannot be told from a " +
165
+ "cross-repository one. Pass --repo \"$GITHUB_REPOSITORY\". UNMEASURED, not clean.",
166
+ );
167
+ }
168
+ const linkedIssues = linkedIssuesInThisRepo(linked, repoNameWithOwner);
169
+
170
+ // An inert keyword naming an issue that IS linked is harmless — the issue
171
+ // closes on the live reference regardless, so firing on it would be the
172
+ // false positive the docblock refuses to ship. Only the unlinked ones are
173
+ // the contradiction.
174
+ const inert = inertClosingReferences(pr.body).filter(r => !linkedIssues.has(r.issue));
175
+
176
+ // THE INERT READING IS REPORTED FIRST, and ai-review round 1 of #1978 was
177
+ // right to insist on it. My first cut ran #1950's check ahead of this one,
178
+ // and because `refuse` exits the process the two did not compose — they
179
+ // shadowed. A pull request on branch `rg/1717-fix` with a backticked
180
+ // `Fixes #1717` in its body hit the new check, never reached this one, and
181
+ // was told to ADD a reference that was already written four characters
182
+ // away. The actionable finding is always the more specific one: "you wrote
183
+ // it and GitHub cannot see it" beats "you wrote nothing".
184
+ //
185
+ // Composition rather than ordering-by-preference: the step-4 check below
186
+ // (SC-2737, which replaced #1950's) asks whether a reference is OWED and
187
+ // this one asks whether a written
188
+ // reference LANDED, so when both could speak the written one is the
189
+ // better remedy and the other is reported by the next run if it survives.
190
+ if (inert.length > 0) refuse(inertClosingMessage(inert, prNumber));
191
+
192
+ // A list GitHub cut short is not a list of every issue this closes. The
193
+ // workflow passes the total beside the nodes; when it exceeds them, an
194
+ // issue that names no criterion could sit in the part never fetched.
195
+ // Absent is NOT READ, like every field above (AI review of #2003): a total
196
+ // the workflow stopped sending would otherwise turn this guard off silently.
197
+ const total = (pr as { closingIssuesTotal?: unknown }).closingIssuesTotal;
198
+ if (typeof total !== "number") {
199
+ refuse(
200
+ "the payload carries no closingIssuesTotal number, so whether the closed-issue list was " +
201
+ "cut short was never read. Add `totalCount` to the query. UNMEASURED, not clean.",
202
+ );
203
+ }
204
+ if (total > linked.length) {
205
+ refuse(
206
+ `this pull request closes ${total} issue(s) and only ${linked.length} were fetched, so ` +
207
+ `whether every one names a criterion was never read. UNMEASURED, not clean.`,
208
+ );
209
+ }
210
+
211
+ // #1979: the commit messages the merge will carry. GitHub acts on a closing
212
+ // keyword in a commit message wherever it sits, backticks included, and this
213
+ // repository squashes with the messages as the body. Refused whatever the
214
+ // switch says, like the inert reading above: it closes live work.
215
+ //
216
+ // Absent is NOT READ and a cut list is UNMEASURED, like every field above:
217
+ // the issue a missing commit would close is exactly the one nobody sees.
218
+ const rawCommits = (pr as { commits?: unknown }).commits;
219
+ const commitsTotal = (pr as { commitsTotal?: unknown }).commitsTotal;
220
+ if (!Array.isArray(rawCommits) || typeof commitsTotal !== "number") {
221
+ refuse(
222
+ "the payload carries no commits array with a commitsTotal, so whether a commit message " +
223
+ "closes an issue this pull request does not declare was never read. Add `commits` to " +
224
+ "the query. UNMEASURED, not clean.",
225
+ );
226
+ }
227
+ if (commitsTotal > rawCommits.length) {
228
+ refuse(
229
+ `this pull request has ${commitsTotal} commit(s) and only ${rawCommits.length} were ` +
230
+ `fetched, so a closing keyword in the rest was never read. UNMEASURED, not clean.`,
231
+ );
232
+ }
233
+ const commits = rawCommits.map(c => {
234
+ const node = c as { sha?: unknown; message?: unknown } | null;
235
+ if (typeof node?.sha !== "string" || typeof node?.message !== "string") {
236
+ refuse("a commit in the payload carries no sha or message string. UNMEASURED, not clean.");
237
+ }
238
+ return { sha: node.sha, message: node.message };
239
+ });
240
+ const undeclared = commitClosingReferences(commits, repoNameWithOwner).filter(r => !linkedIssues.has(r.issue));
241
+ if (undeclared.length > 0) refuse(commitClosingMessage(undeclared, prNumber));
242
+
243
+ // The body of every issue this pull request closes HERE, read off the same
244
+ // nodes `closingIssuesReferences` returned. The workflow asks GitHub for the
245
+ // body on each node, so no second query decides which issues are linked.
246
+ //
247
+ // Each NODE is asked whether it belongs here, through the same decider as
248
+ // the set above — never its bare number. AI review of #2003: `Fixes #9` and
249
+ // `Fixes other-org/other-repo#9` share a number, and a number-only test let
250
+ // the other repository's body stand in for this one's.
251
+ //
252
+ // The TITLE too (#2061): `criterionAnswer` reads title and body, so a
253
+ // declaration written in the title answers the question for the label and
254
+ // the board, and a node fetched without one was never fully read.
255
+ const issues = new Map<number, ClosedIssue>();
256
+ for (const node of linked) {
257
+ const n = node as { number?: unknown; title?: unknown; body?: unknown } | null;
258
+ if (n === null || typeof n !== "object" || typeof n.number !== "number") continue;
259
+ if (linkedIssuesInThisRepo([n], repoNameWithOwner).size === 0) continue;
260
+ if (typeof n.body !== "string") {
261
+ refuse(
262
+ `issue #${n.number} is closed by this pull request but its node carries no body, so ` +
263
+ `whether it names a criterion was never read. Add \`body\` to the closingIssuesReferences ` +
264
+ `query. UNMEASURED, not clean.`,
265
+ );
266
+ }
267
+ if (typeof n.title !== "string") {
268
+ refuse(
269
+ `issue #${n.number} is closed by this pull request but its node carries no title, so ` +
270
+ `whether it names a criterion was never fully read. Add \`title\` to the ` +
271
+ `closingIssuesReferences query. UNMEASURED, not clean.`,
272
+ );
273
+ }
274
+ issues.set(n.number, { title: n.title, body: n.body });
275
+ }
276
+
277
+ // The ids a criterion can be named by come from the checkout's specs/ — the
278
+ // pull request's merge commit, so a criterion it adds counts. Taken only
279
+ // when an issue's answer depends on it: a session-record diff owes none.
280
+ //
281
+ // The same read says which criteria are still unticked (#2005), so a tick
282
+ // this pull request makes is seen and one it forgot is caught here, before
283
+ // the merge, rather than as a short criterion-coverage on main.
284
+ let criteria: ClosingCriteria = { ids: [], unticked: [] };
285
+ if (!isSessionRecordOnly(changedPaths) && issues.size > 0) {
286
+ const read = closingCriteria(process.cwd());
287
+ if (read === null) {
288
+ refuse(
289
+ `the spec sweep of ${process.cwd()}/specs could not be taken, so no closed issue's ` +
290
+ `criteria can be read. UNMEASURED, not an issue that names none.`,
291
+ );
292
+ }
293
+ criteria = read;
294
+ }
295
+
296
+ const runId = process.env.GITHUB_RUN_ID;
297
+ const rerun = `gh run rerun ${runId ? runId : "<run-id>"} --repo ${repoNameWithOwner}`;
298
+ const failure = closingRequirement(
299
+ changedPaths,
300
+ issues,
301
+ criteria,
302
+ pr.body,
303
+ linked.length,
304
+ repoNameWithOwner,
305
+ rerun,
306
+ );
307
+ if (failure !== null) {
308
+ const message = closingRequirementMessage(failure, prNumber);
309
+ // Read EXACTLY as `RUNGATE_REQUIRE_AI_REVIEW` is: the string `true` and
310
+ // no other value turns the refusal on (`.claude/rules/config-access.md`).
311
+ if (process.env.RUNGATE_REQUIRE_CLOSING_REF === "true") refuse(message);
312
+ // Off, the reading is still reported, as an annotation rather than as a
313
+ // silent pass. Newlines are encoded so the annotation keeps all of it.
314
+ console.log(`::warning title=Closing reference (not enforced)::${message.replace(/\n/g, "%0A")}`);
315
+ console.log(
316
+ `closing references NOT ENFORCED: PR #${prNumber} fails ADR-013 step 4, and ` +
317
+ `RUNGATE_REQUIRE_CLOSING_REF is not "true".`,
318
+ );
319
+ return;
320
+ }
321
+
322
+ // Counts what was CREDITED, not what was returned — a summary saying
323
+ // "links 1 issue" for a cross-repository node would describe the check as
324
+ // doing the thing round 2 found it was not doing.
325
+ const links =
326
+ linkedIssues.size > 0 ? `links ${linkedIssues.size} issue(s)` : "links none and claims none";
327
+ console.log(`closing references OK: PR #${prNumber} ${links}.`);
328
+ }
329
+
330
+ await main();
@@ -205,15 +205,6 @@ export interface ClosestPattern {
205
205
  patternName: string;
206
206
  rewrite: string;
207
207
  ambiguous: boolean;
208
- /**
209
- * Set ONLY by the last-resort file-token match (#589).
210
- *
211
- * `patternName` cannot carry this: the last resort renders `file-exists`,
212
- * which is also the name of a real heuristic, so a caller reading the name
213
- * alone cannot tell a pattern the statement matched from one inferred off a
214
- * filename that happened to be in the sentence.
215
- */
216
- fallback?: boolean;
217
208
  }
218
209
 
219
210
  /**
@@ -385,45 +376,22 @@ function findClosestPattern(statement: string): ClosestPattern | null {
385
376
  }
386
377
  }
387
378
 
388
- // If no heuristic matched, try a loose file-exists match.
389
- // Look for any filename-like token (word.ext) in the statement.
390
- //
391
- // #586 looked hard at narrowing this to statements whose verb is
392
- // existence, and did not. The fallback does turn behaviour into presence —
393
- // measured over the real tree, two criteria go through it:
394
- //
395
- // "Rejecting a promoted rule writes its hash to
396
- // `reference/rejected-constraints.md` and it is never re-promoted"
397
- // -> "reference/rejected-constraints.md exists"
379
+ // Nothing the statement SAYS matched, so nothing is proposed.
398
380
  //
399
- // "Makefile targets, `package.json` scripts and CI workflow files are
400
- // scanned for constraints alongside markdown"
401
- // -> "package.json exists"
381
+ // There used to be a last resort here: take any filename-like token from
382
+ // anywhere in the sentence and render the whole criterion as `<file>
383
+ // exists`. #586 kept it because it wrote the original beside the rewrite;
384
+ // #589 fenced it to single-claim sentences. #2040 removed it after it
385
+ // turned SC-2747, a criterion about what `scaffold` installs, into
386
+ // `AGENTS.md exists` on #2033 — a check that holds against a file that
387
+ // obviously exists whatever the criterion claimed. Jason's call,
388
+ // 2026-11-14: a filename a criterion only mentions is never what it is
389
+ // rewritten to. The `file-exists` heuristic above still binds a sentence
390
+ // that SAYS a file should exist, because that rewrite says the same thing.
402
391
  //
403
- // — but it reports `ambiguous: true`, and an ambiguous rewrite writes
404
- // `<!-- REVIEW: original — … -->` beside the line. #426 kept this path for
405
- // exactly that reason (see SC-1587: "a lossy render by nature … kept as the
406
- // one remaining rewrite path precisely because it writes the statement it
407
- // replaced into the next line"). Nothing is discarded, so this is a
408
- // DOWNGRADE, not a LOSS, and #586 is about loss.
409
- //
410
- // Narrowing it here turns SC-1587 and SC-1594 red for a reason those
411
- // criteria are right about, which is how the distinction got found. The
412
- // downgrade is #589, and it is now scoped by `coordinatedClaims` below
413
- // rather than by narrowing the token match: WHICH statements this may
414
- // speak for is a question about the criterion, not about the filename.
415
- const fileToken = statement.match(/\b(\S+\.\w{1,5})\b/);
416
- if (fileToken) {
417
- return {
418
- patternName: "file-exists",
419
- rewrite: `${fileToken[1]} exists`,
420
- ambiguous: true,
421
- fallback: true,
422
- };
423
- }
424
-
425
- // Truly unresolvable
426
- return null;
392
+ // `test/audit-specs-fallback-scope.test.ts` restores the last resort in a
393
+ // mutant at the line below, so it must stay a single, exact line.
394
+ return null; // #2040: a filename the statement only mentions is never a pattern
427
395
  }
428
396
 
429
397
  // ── Whether to rewrite at all, and into what (#426) ───────────
@@ -434,8 +402,8 @@ function findClosestPattern(statement: string): ClosestPattern | null {
434
402
  * Anchored, because the question is whether the statement OPENS by naming
435
403
  * its target. A filename mentioned halfway through a sentence of prose is
436
404
  * not a structured criterion, and treating it as one is how
437
- * `findClosestPattern`'s last resort turns a whole criterion into
438
- * `foo.ts exists`.
405
+ * `findClosestPattern`'s old last resort, removed by #2040, turned a whole
406
+ * criterion into `foo.ts exists`.
439
407
  */
440
408
  function leadingFileToken(statement: string): string | null {
441
409
  const m = /^(\S*[./]\S*)\s/.exec(statement);
@@ -486,9 +454,8 @@ export type RewriteDecision =
486
454
  *
487
455
  * 1. A statement already in the structured grammar is never rewritten.
488
456
  * 2. A rewrite that would drop the file the criterion names is refused
489
- * outright. `findClosestPattern`'s last resort collapses anything with a
490
- * filename in it to `<file> exists`, which is an assertion that holds
491
- * vacuously against a file that obviously exists.
457
+ * outright. A heuristic that binds on a keyword can still propose a
458
+ * rewrite about a different file than the one the criterion opens with.
492
459
  * 3. A rewrite that survives both carries the em-dash rationale across.
493
460
  *
494
461
  * One exported binding, so there is exactly one thing to mutate.
@@ -512,32 +479,10 @@ export function decideRewrite(
512
479
  };
513
480
  }
514
481
 
515
- // #589: the last resort may only speak for a criterion that makes ONE
516
- // claim. It takes a filename-like token from anywhere in a sentence and
517
- // renders the whole criterion as `<that file> exists`, which can be about
518
- // at most one thing — so a criterion that coordinates a second claim is
519
- // guaranteed to come back as a statement about something else.
520
- //
521
- // Measured over the corpus `--fix` edits: two criteria went through it,
522
- // SC-1940 (a hash is written AND the rule never resurfaces) and SC-1943 (a
523
- // three-item subject of which the filename is one). Both are kept now.
524
- //
525
- // Scoped to the fallback deliberately. A heuristic that MATCHED the
526
- // statement was chosen by what the statement says; the last resort was
527
- // chosen by a filename being present, and that is the difference this
528
- // guard is about.
529
- if (closest.fallback) {
530
- const claims = coordinatedClaims(statement);
531
- if (claims.length > 0) {
532
- return {
533
- kind: "keep",
534
- reason:
535
- `rewriting as ${closest.patternName} would assert only that ${closest.rewrite}, ` +
536
- `while the criterion coordinates a further claim (${claims[0]}) — ` +
537
- `the file is mentioned, not what the criterion is about`,
538
- };
539
- }
540
- }
482
+ // #589 had a guard here: the last resort could only speak for a criterion
483
+ // making one claim. #2040 removed the last resort, so every proposal that
484
+ // reaches this point was chosen by what the statement says, and the guard
485
+ // had nothing left to fence.
541
486
 
542
487
  const rationale = rationaleOf(statement);
543
488
  const rewritten = rationale ? `${closest.rewrite} — ${rationale}` : closest.rewrite;
@@ -604,30 +549,6 @@ export function distinguishingTerms(statement: string): string[] {
604
549
  return [...new Set(words)].filter(w => !REWRITE_STOPWORDS.has(w));
605
550
  }
606
551
 
607
- /**
608
- * The further claims this criterion coordinates, if any (#589).
609
- *
610
- * Returns the clause after each `and`/`or`, so the refusal can name what the
611
- * rewrite would have dropped rather than merely reporting that something was
612
- * dropped. Empty for a criterion that makes one claim.
613
- *
614
- * One exported binding, so there is exactly one thing to mutate — and it is
615
- * the only thing that decides which statements the last resort may speak
616
- * for.
617
- */
618
- export function coordinatedClaims(statement: string): string[] {
619
- const claims: string[] = [];
620
- const coordinator = /\s+(?:and|or)\s+/gi;
621
- let m: RegExpExecArray | null;
622
- while ((m = coordinator.exec(statement)) !== null) {
623
- const rest = statement.slice(m.index + m[0].length).trim();
624
- // A trailing coordinator joins nothing. An empty string here would read
625
- // as a second claim whose text is gone, and refuse a rewrite on it.
626
- if (rest.length > 0) claims.push(rest);
627
- }
628
- return claims;
629
- }
630
-
631
552
  /**
632
553
  * `findClosestPattern`, exported so a test can drive the real decision.
633
554
  *
@@ -686,6 +607,39 @@ function followsWith(content: string, match: RegExpMatchArray, marker: string):
686
607
  return content.slice(match.index! + match[0].length).startsWith(`\n${marker}`);
687
608
  }
688
609
 
610
+ /**
611
+ * Write `marker` on the line below the matched criterion, REPLACING a REVIEW
612
+ * marker already there rather than stacking a second one above it (#2040).
613
+ *
614
+ * A marker's text carries the reason, and a reason changes when the rewriter
615
+ * does: #2040's removal of the last resort changed why two criteria are kept,
616
+ * and the old code inserted the new marker above the old, so each criterion
617
+ * carried two contradictory reasons and the tree stopped being a fixed point
618
+ * of its own generator. Returns `content` unchanged when the marker is current.
619
+ */
620
+ function withMarkerBelow(content: string, match: RegExpMatchArray, marker: string): string {
621
+ if (followsWith(content, match, marker)) return content;
622
+ const lineEnd = match.index! + match[0].length;
623
+ const rest = content.slice(lineEnd);
624
+ const stale = STALE_UNMATCHED.exec(rest);
625
+ if (stale) return content.slice(0, lineEnd) + `\n${marker}` + rest.slice(stale[0].length);
626
+ return replaceLine(content, match, `${match[0]}\n${marker}`);
627
+ }
628
+
629
+ /** A REVIEW unmatched marker on the line directly after a criterion. */
630
+ const STALE_UNMATCHED = /^\n<!-- REVIEW: unmatched \(.*\) -->(?=\n|$)/;
631
+
632
+ /**
633
+ * Drop an unmatched marker an earlier run left below a criterion that is now
634
+ * being rewritten (review of #2139). The text after the match is cut, so the
635
+ * match's own index stays valid for the rewrite that follows.
636
+ */
637
+ function withoutMarkerBelow(content: string, match: RegExpMatchArray): string {
638
+ const lineEnd = match.index! + match[0].length;
639
+ const stale = STALE_UNMATCHED.exec(content.slice(lineEnd));
640
+ return stale ? content.slice(0, lineEnd) + content.slice(lineEnd + stale[0].length) : content;
641
+ }
642
+
689
643
  /**
690
644
  * Whether this criterion carries a non-empty `proved-by:` line.
691
645
  *
@@ -842,8 +796,9 @@ export function auditSpecs(
842
796
  // at four unmatched criteria and one marker. The three unmarked
843
797
  // ones read as reviewed because of a comment about a different
844
798
  // criterion.
845
- if (!followsWith(modified, scMatch, marker)) {
846
- modified = replaceLine(modified, scMatch, `${scMatch[0]}\n${marker}`);
799
+ const marked = withMarkerBelow(modified, scMatch, marker);
800
+ if (marked !== modified) {
801
+ modified = marked;
847
802
  hasChanges = true;
848
803
  }
849
804
  rewrites.push({
@@ -862,6 +817,7 @@ export function auditSpecs(
862
817
  if (closest!.ambiguous) {
863
818
  replacement += `\n<!-- REVIEW: original — ${usc.statement} -->`;
864
819
  }
820
+ modified = withoutMarkerBelow(modified, scMatch);
865
821
  modified = replaceLine(modified, scMatch, replacement);
866
822
  hasChanges = true;
867
823
  rewrites.push({