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
@@ -61,6 +61,8 @@
61
61
  */
62
62
  import { spawnSync } from "child_process";
63
63
 
64
+ import { fencedBlocks } from "./markdown-fence";
65
+
64
66
  export interface CliCommand {
65
67
  /** The script this runs, relative to the package root. Must be in `files`. */
66
68
  script: string;
@@ -162,7 +164,7 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
162
164
  "plan-spec": {
163
165
  script: "scripts/plan-spec.ts",
164
166
  summary: "Derive a repository's milestones from a spec's Phase placement table",
165
- usage: "rungate plan-spec <spec.md> --repo <owner/name> --prefix <name> [--write] [--json]",
167
+ usage: "rungate plan-spec <spec.md> --repo <owner/name> --prefix <name> [--rename-from <old name>] [--write] [--json]",
166
168
  projectRootFlag: true,
167
169
  },
168
170
  // Registered after two hours of building a weaker version of it beside it
@@ -178,7 +180,7 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
178
180
  "criterion-inventory": {
179
181
  script: "scripts/criterion-inventory.ts",
180
182
  summary: "Trace every criterion to the tests, issues and pull requests that name it",
181
- usage: "rungate criterion-inventory --snapshot <dir> --spec <path> [--json] [--markdown]",
183
+ usage: "rungate criterion-inventory --spec <path> [--snapshot <cache-dir>] [--repo <owner/name>] [--json] [--markdown]",
182
184
  projectRootFlag: true,
183
185
  },
184
186
  // Step 3 of ADR-003 made VISIBLE (#1647). The issue body declares which
@@ -255,6 +257,30 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
255
257
  usage:
256
258
  "rungate plan-deps --repo <owner/name> --milestone-prefix <name> [--write] [--json] [--include-closed]",
257
259
  },
260
+ // The two scripts ADR-014's process workflows ran and no consumer could
261
+ // (#2044, SC-2742). A consumer has `node_modules/rungate`, not `scripts/`,
262
+ // so `board-ready.yml`, `adr-accepted.yml` and `closing-references.yml`
263
+ // could only be emitted for a consumer once these were commands.
264
+ //
265
+ // No `projectRootFlag` on either: both read their project from
266
+ // `process.cwd()`, which the dispatcher's child inherits, and neither
267
+ // parses `--project-root`, so an appended flag would be ignored at best.
268
+ // `board-ready`'s own `--project-root` is #1968.
269
+ "board-ready": {
270
+ script: "scripts/board-ready.ts",
271
+ summary: "Move the work a closed blocker freed, or the top of the backlog, into the board's Ready lane",
272
+ usage:
273
+ "rungate board-ready --repo <owner/name> --project <node-id> [--closed-issue <n>] [--top-up] " +
274
+ "[--moving-issue <n>] [--actor <login>] [--write] (at least one of --closed-issue, --top-up)",
275
+ },
276
+ // Reads a `gh pr view`-shaped payload on stdin, which the dispatcher passes
277
+ // through (`stdio: "inherit"`), or `--fixture` offline.
278
+ "audit-closing-references": {
279
+ script: "scripts/audit-closing-references.ts",
280
+ summary: "Refuse a pull request whose closing reference GitHub will not act on, or that closes no issue",
281
+ usage: "<payload> | rungate audit-closing-references --repo <owner/name> | " +
282
+ "rungate audit-closing-references --fixture <file.json> --repo <owner/name>",
283
+ },
258
284
  "sync-spec-tests": {
259
285
  script: "scripts/sync-spec-tests.ts",
260
286
  summary: "Regenerate the conformity suite from the specs",
@@ -270,6 +296,45 @@ export const CLI_COMMANDS: Record<string, CliCommand> = {
270
296
  summary: "Extract constraints from a project's docs into agent rules",
271
297
  usage: "rungate extract-constraints",
272
298
  },
299
+ // The two doors, registered by #1938 and #1939. Both scripts existed and
300
+ // were tested for weeks while being unreachable: `HYGIENE-3` fails a file
301
+ // in `scripts/` with ZERO references and a test counts as a reference, so
302
+ // a script with a test and no registry entry passes every orphan check and
303
+ // can still be run by nobody. The same shape as #675 above, and as #1935.
304
+ //
305
+ // `finding-promotion` is the one that mattered. It decides whether a gap
306
+ // belongs to a criterion (the front door) or to the side door, and while
307
+ // it was unreachable that decision fell to whoever found the gap — a
308
+ // self-classification, which takes the cheaper door every time. Sixteen
309
+ // issues were filed by hand on 2026-11-09 for exactly that reason.
310
+ // `projectRootFlag` is load-bearing here for the #363 reason stated at the
311
+ // top of this file, and registering the command is what made it live: the
312
+ // script resolved `ROOT` from `import.meta.dir`, its own install location.
313
+ // Run as `bunx rungate finding-promotion` from a consumer, that is
314
+ // `node_modules/rungate` — so `--spec specs/MY-SPEC.md` resolved inside the
315
+ // installed package, refused SPEC_ABSENT with the consumer's spec sitting
316
+ // right there, and on a name collision would have appended a criterion
317
+ // into a tree the next install wipes while printing "Appended to …".
318
+ "finding-promotion": {
319
+ script: "scripts/finding-promotion.ts",
320
+ projectRootFlag: true,
321
+ summary: "Turn a review finding that names real work into a spec criterion",
322
+ // TWO modes, and the usage says so because the script has two outcomes.
323
+ // #1940 added `--declines` after this registration was written, so the
324
+ // merged tree had a `required("declines")` the usage did not mention —
325
+ // which is exactly what the usage-vs-required-flags sweep is for. Neither
326
+ // pull request could see it alone; it appeared on the merge ref.
327
+ usage:
328
+ "rungate finding-promotion --issue <N> --spec <path> --outcome <text> --symbol <name> " +
329
+ "--module <path> [--project-root <path>] [--write] | " +
330
+ "rungate finding-promotion --issue <N> --declines <why> [--write]",
331
+ },
332
+ "claim-files": {
333
+ script: "scripts/claim-files.ts",
334
+ summary: "Claim the files an issue will change, so parallel agents do not collide",
335
+ usage:
336
+ "rungate claim-files [--check <path>] [--claim <path> --owner <branch> --issue <N>] [--release --owner <branch>] [--list]",
337
+ },
273
338
  // Registered so the GENERATED ai-review workflow has something to run. The
274
339
  // reader has existed and been tested since #631 and nothing executed it:
275
340
  // `lib/scaffold/ai-review-step.ts` emitted a warning saying so by name,
@@ -453,8 +518,14 @@ export function commandRoutingTable(): string {
453
518
  * not the document").
454
519
  */
455
520
  export function codeSpans(markdown: string): string {
456
- const fenced = markdown.match(/```[\s\S]*?```/g) ?? [];
457
- const withoutFences = markdown.replace(/```[\s\S]*?```/g, "\n");
521
+ // Fenced blocks through `lib/markdown-fence.ts` (#2135). The regex this
522
+ // replaced ignored `~~~` fences and ended a ```` block at its first ```.
523
+ const blocks = fencedBlocks(markdown);
524
+ const fenced = blocks.map(b => markdown.slice(b.start, b.end));
525
+ let withoutFences = markdown;
526
+ for (const b of [...blocks].reverse()) {
527
+ withoutFences = withoutFences.slice(0, b.start) + "\n" + withoutFences.slice(b.end);
528
+ }
458
529
  const inline = withoutFences.match(/`[^`\n]+`/g) ?? [];
459
530
  return [...fenced, ...inline].join("\n");
460
531
  }
@@ -52,6 +52,48 @@
52
52
  * that exists, the loosened rule is wrong nineteen times out of twenty-one.
53
53
  */
54
54
 
55
+ import { NAMES_NONE, answerableIds, criterionAnswer, specCriteriaIn } from "./board-mirror";
56
+ import { idBoundedPattern } from "./sc-ids";
57
+ import { declaredClosingIn } from "./local-work";
58
+ import { fencedBlocks } from "./markdown-fence";
59
+
60
+ /**
61
+ * The issues a pull request closes **in this repository**, from `gh`'s shape.
62
+ *
63
+ * ai-review round 2 of #1978. `closingIssuesReferences` resolves GitHub's
64
+ * closing keywords and those match across repositories: a body writing
65
+ * `Fixes other-org/other-repo#9` produces a node numbered 9 that has nothing
66
+ * to do with this tracker. Counting it made a cross-repo reference satisfy
67
+ * the branch's own-issue requirement, so a pull request on `rg/1950-foo`
68
+ * closing somebody else's #9 printed "closing references OK" — the exact
69
+ * PR-#1903 shape this change exists to catch, let through by the check
70
+ * itself.
71
+ *
72
+ * Identical to the defect `declaredClosingIn` was added for in round 5 of
73
+ * #1974, one consumer over, which is why that function is called here rather
74
+ * than re-implemented: "which of these nodes belong to us" has one decider.
75
+ *
76
+ * This only adapts the SHAPE. `gh pr view --json closingIssuesReferences`
77
+ * returns `repository: { name, owner: { login } }` where the GraphQL field
78
+ * `declaredClosingIn` was written against returns `nameWithOwner`. A node
79
+ * missing either half composes to a string that matches no repository, which
80
+ * is the safe direction: it can cause a reference to be ignored and a
81
+ * refusal raised, never a refusal suppressed.
82
+ */
83
+ export function linkedIssuesInThisRepo(
84
+ nodes: readonly unknown[],
85
+ repoNameWithOwner: string,
86
+ ): Set<number> {
87
+ const shaped = nodes
88
+ .filter((n): n is Record<string, any> => n !== null && typeof n === "object")
89
+ .filter(n => typeof n.number === "number")
90
+ .map(n => ({
91
+ number: n.number as number,
92
+ repository: { nameWithOwner: `${n.repository?.owner?.login}/${n.repository?.name}` },
93
+ }));
94
+ return new Set(declaredClosingIn(shaped, repoNameWithOwner));
95
+ }
96
+
55
97
  /**
56
98
  * The verbs GitHub acts on, in one declaring position.
57
99
  *
@@ -94,10 +136,11 @@ export interface InertClosingReference {
94
136
  */
95
137
  function maskedRanges(body: string): { start: number; end: number; reason: InertClosingReference["reason"] }[] {
96
138
  const out: { start: number; end: number; reason: InertClosingReference["reason"] }[] = [];
97
- const fenced = /^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm;
98
- for (const m of body.matchAll(fenced)) {
99
- out.push({ start: m.index!, end: m.index! + m[0].length, reason: "fenced-block" });
100
- }
139
+ // The shared reader (#2130). The regex this replaced required the close to
140
+ // repeat the opening run exactly, so a longer close was missed and the
141
+ // block ran on; and an unclosed fence, which GitHub renders as code to the
142
+ // end, read as live.
143
+ for (const b of fencedBlocks(body)) out.push({ ...b, reason: "fenced-block" });
101
144
  const inFence = (i: number) => out.some(r => i >= r.start && i < r.end);
102
145
  // Single-line code spans. `[^`\n]+` keeps a span from spilling across a line,
103
146
  // which is what an unmatched backtick in ordinary prose would otherwise do —
@@ -116,16 +159,40 @@ function maskedRanges(body: string): { start: number; end: number; reason: Inert
116
159
  * backticks is one mistake, not two, and a message listing it twice reads as
117
160
  * two problems to fix.
118
161
  */
162
+ /**
163
+ * A closing keyword beside an issue number: `Fixes #12`, `closes: #12`.
164
+ *
165
+ * The one place the keyword list and its adjacency are decided, for a pull
166
+ * request body and a commit message alike (#1979). Two patterns would be two
167
+ * deciders, free to disagree about the same text.
168
+ */
169
+ function closingKeywordPattern(): RegExp {
170
+ // `(` as well as `:` may sit between verb and number: GitHub closed #1148
171
+ // from the squash subject "fix(#1148): …" (PR #1208), the conventional-commit
172
+ // form most subjects here take.
173
+ // And an optional `owner/repo` before the `#` (AI review of #2120):
174
+ // `Fixes hornjason/rungate#1717` closes #1717 as surely as the bare form.
175
+ // Group 1 the keyword, 2 the repository if spelled, 3 the number.
176
+ return new RegExp(
177
+ `\\b(${CLOSING_KEYWORDS.join("|")})\\b[ \\t]*[:(]?[ \\t]*([\\w.-]+\\/[\\w.-]+)?#(\\d+)\\b`,
178
+ "gi",
179
+ );
180
+ }
181
+
119
182
  export function inertClosingReferences(body: string): InertClosingReference[] {
120
183
  if (!body) return [];
121
184
  const ranges = maskedRanges(body);
122
- const pattern = new RegExp(`\\b(${CLOSING_KEYWORDS.join("|")})\\b[ \\t]*:?[ \\t]*#(\\d+)\\b`, "gi");
185
+ const pattern = closingKeywordPattern();
123
186
  const seen = new Set<number>();
124
187
  const out: InertClosingReference[] = [];
125
188
  for (const m of body.matchAll(pattern)) {
126
189
  const hit = ranges.find(r => m.index! >= r.start && m.index! < r.end);
127
190
  if (!hit) continue;
128
- const issue = Number.parseInt(m[2]!, 10);
191
+ // A spelled-out repository is left out here, as it always was: the body
192
+ // check compares numbers against this repository's linked set, and another
193
+ // repository's #9 is not this one's.
194
+ if (m[2] !== undefined) continue;
195
+ const issue = Number.parseInt(m[3]!, 10);
129
196
  if (seen.has(issue)) continue;
130
197
  seen.add(issue);
131
198
  out.push({ issue, keyword: m[1]!, reason: hit.reason, text: m[0] });
@@ -133,6 +200,193 @@ export function inertClosingReferences(body: string): InertClosingReference[] {
133
200
  return out;
134
201
  }
135
202
 
203
+ /**
204
+ * The files whose pull requests owe no closing reference (ADR-013, SC-2737).
205
+ *
206
+ * The session record, and nothing else: a state update closes no issue and is
207
+ * expected not to. Paths are repository-relative and exact — the root copies,
208
+ * never a file of the same name somewhere else in the tree.
209
+ */
210
+ export const SESSION_RECORD_FILES: readonly string[] = [
211
+ "project-state.json",
212
+ "PROJECT-STATE.md",
213
+ "SUCCESS.md",
214
+ ];
215
+
216
+ /**
217
+ * Is every changed file a session-record file?
218
+ *
219
+ * **Decided from the diff, never from the branch name.** #1950 decided whether
220
+ * a reference was owed from the branch, and the AI review of #1989 refused
221
+ * that: a branch that does not open with an issue number skipped the check
222
+ * whatever it changed. A file-set rule has no such door — touching one other
223
+ * file makes the pull request owe a reference.
224
+ *
225
+ * An empty list is `false`. A pull request with no readable files has not
226
+ * shown it is a session record, and the caller refuses an absent list as
227
+ * UNMEASURED before this is reached.
228
+ */
229
+ export function isSessionRecordOnly(paths: readonly string[]): boolean {
230
+ return paths.length > 0 && paths.every(p => SESSION_RECORD_FILES.includes(p));
231
+ }
232
+
233
+ /** An issue this pull request closes, as the workflow's one query returns it. */
234
+ export interface ClosedIssue {
235
+ readonly title: string;
236
+ readonly body: string;
237
+ }
238
+
239
+ /**
240
+ * Every id an issue can answer the criterion question with, read from the
241
+ * checkout's `specs/` — or `null` when the sweep could not be taken.
242
+ *
243
+ * `null` is UNMEASURED, never an empty list: read as "no ids", every issue
244
+ * naming a criterion would be refused for naming none (#2061).
245
+ */
246
+ export function closingCriteria(root: string): ClosingCriteria | null {
247
+ const sweep = specCriteriaIn(root);
248
+ if (sweep.reading === "UNMEASURED") return null;
249
+ // Only the ids ONE spec states (`sweep.ids`). A collided id is reported,
250
+ // never attributed (AI review of #2115): a tick could not say which spec's
251
+ // box to tick, so it is not demanded here either.
252
+ const unambiguous = new Set(sweep.ids);
253
+ const unticked = [...new Set(sweep.specs.flatMap(s => s.unticked))].filter(id => unambiguous.has(id));
254
+ return { ids: answerableIds(sweep), unticked };
255
+ }
256
+
257
+ /**
258
+ * The criteria a closing check reads from the checkout (#2061, #2005): every
259
+ * id an issue can name, and the ids still unticked in at least one spec that
260
+ * states them. The checkout is the pull request's merge commit, so a tick the
261
+ * pull request makes is already here.
262
+ */
263
+ export interface ClosingCriteria {
264
+ readonly ids: readonly string[];
265
+ readonly unticked: readonly string[];
266
+ }
267
+
268
+ /**
269
+ * The words a pull request writes when it closes an issue naming a criterion
270
+ * it does not finish, followed by the id (#2005): `does not complete SC-12`.
271
+ * For a criterion more than one issue carries, so the last of them is the one
272
+ * that has to tick it. Exact, like the criterion declaration: a looser match
273
+ * would let a sentence excuse a criterion by accident.
274
+ */
275
+ export const DOES_NOT_COMPLETE = "does not complete";
276
+
277
+ /** Does this pull request body excuse `id` with the exact words? */
278
+ export function excusesCriterion(prBody: string, id: string): boolean {
279
+ return idBoundedPattern(`${DOES_NOT_COMPLETE} `, id).test(prBody);
280
+ }
281
+
282
+ /**
283
+ * Why a pull request fails ADR-013's step 4, or `null` when it does not.
284
+ *
285
+ * Two failures, in the order a fix has to happen: closing no issue in this
286
+ * repository, then closing one that has not answered the criterion question.
287
+ * Every value the message names is carried here, the rule rounds 1 and 3 of
288
+ * #1978 arrived at: a claim the message cannot support is a claim it cannot
289
+ * spell.
290
+ *
291
+ * **The criterion question is `criterionAnswer`'s, not this file's** (#2061).
292
+ * The `needs-criterion` label and the `criteria-named` reading ask it there;
293
+ * a copy here accepted any `SC-<digits>`, so a payload issue naming `CRC-B4`
294
+ * was refused a closing pull request while the board counted it answered.
295
+ */
296
+ export type ClosingRequirementFailure =
297
+ | { kind: "NO_ISSUE"; rawReferenceCount: number; repoNameWithOwner: string; rerun: string }
298
+ | { kind: "NO_CRITERION"; issues: number[]; rerun: string }
299
+ | {
300
+ kind: "UNTICKED";
301
+ /** Each closed issue and the unticked, unexcused criteria it names. */
302
+ unticked: { issue: number; ids: string[] }[];
303
+ /** `#77 (SC-12, SC-13)`, one per issue: what the message names. */
304
+ named: string;
305
+ /** The one sync command per criterion that ticks it. */
306
+ ticks: string;
307
+ /** The exact words that excuse each criterion instead. */
308
+ excuses: string;
309
+ };
310
+
311
+ /**
312
+ * Third, after an issue is closed and has answered the criterion question
313
+ * (#2005): every criterion it names is ticked in this tree, or this pull
314
+ * request says it does not complete it. A merge that removes a criterion's
315
+ * last open issue without a tick turns `criterion-coverage` short on main for
316
+ * every other pull request, and no pull request can repair that from its own
317
+ * tree — #2003 closing #1998 and #2094 closing #1964 both did.
318
+ */
319
+ export function closingRequirement(
320
+ changedPaths: readonly string[],
321
+ linkedIssues: ReadonlyMap<number, ClosedIssue>,
322
+ criteria: ClosingCriteria,
323
+ prBody: string,
324
+ rawReferenceCount: number,
325
+ repoNameWithOwner: string,
326
+ rerun: string,
327
+ ): ClosingRequirementFailure | null {
328
+ if (isSessionRecordOnly(changedPaths)) return null;
329
+ if (linkedIssues.size === 0) {
330
+ return { kind: "NO_ISSUE", rawReferenceCount, repoNameWithOwner, rerun };
331
+ }
332
+ const ordered = [...linkedIssues].sort(([a], [b]) => a - b);
333
+ const issues = ordered
334
+ .filter(([, issue]) => !criterionAnswer(issue, criteria.ids).answered)
335
+ .map(([n]) => n);
336
+ if (issues.length > 0) return { kind: "NO_CRITERION", issues, rerun };
337
+
338
+ const unticked = ordered
339
+ .map(([issue, body]) => ({
340
+ issue,
341
+ ids: criterionAnswer(body, criteria.ids).names.filter(
342
+ id => criteria.unticked.includes(id) && !excusesCriterion(prBody, id),
343
+ ),
344
+ }))
345
+ .filter(u => u.ids.length > 0);
346
+ if (unticked.length === 0) return null;
347
+ const ids = [...new Set(unticked.flatMap(u => u.ids))];
348
+ return {
349
+ kind: "UNTICKED",
350
+ unticked,
351
+ named: unticked.map(u => `#${u.issue} (${u.ids.join(", ")})`).join(", "),
352
+ ticks: ids.map(id => `bun scripts/sync-sc-status.ts --only ${id}`).join("; "),
353
+ excuses: ids.map(id => `"${DOES_NOT_COMPLETE} ${id}"`).join(", "),
354
+ };
355
+ }
356
+
357
+ /** The refusal text for the above. Names what was read, and the remedy. */
358
+ export function closingRequirementMessage(f: ClosingRequirementFailure, prNumber: number): string {
359
+ if (f.kind === "NO_ISSUE") {
360
+ return (
361
+ `PR #${prNumber} closes no issue in ${f.repoNameWithOwner}` +
362
+ (f.rawReferenceCount === 0
363
+ ? ` — closingIssuesReferences is empty.\n\n`
364
+ : `: none of the ${f.rawReferenceCount} closing reference(s) GitHub recorded belongs to it.\n\n`) +
365
+ `Every pull request closes an issue (ADR-013, step 4). Add "Fixes #<N>" to the BODY, ` +
366
+ `not inside backticks, naming the issue this work was filed under. Only a pull request ` +
367
+ `whose changed files are all session-record files owes none. Editing the body re-runs ` +
368
+ `this check by itself.`
369
+ );
370
+ }
371
+ if (f.kind === "UNTICKED") {
372
+ return (
373
+ `PR #${prNumber} closes issue(s) naming criteria that are not ticked in its own tree: ` +
374
+ `${f.named}. Merging would leave each criterion with one fewer open issue and no tick, ` +
375
+ `and criterion-coverage would read short on main for every other pull request.\n\n` +
376
+ `Tick each in this pull request (${f.ticks}, then its proved-by: line), or, if another ` +
377
+ `open issue still carries it, write the exact words ${f.excuses} in this description. ` +
378
+ `Editing the description re-runs this check by itself.`
379
+ );
380
+ }
381
+ return (
382
+ `PR #${prNumber} closes issue(s) #${f.issues.join(", #")}, whose title and body name ` +
383
+ `neither a criterion any spec states nor "${NAMES_NONE}".\n\n` +
384
+ `Add the criterion it serves to the issue, or the exact words "${NAMES_NONE}" if it ` +
385
+ `is cleanup. Editing an issue fires no pull-request event, so re-run this check after: ` +
386
+ `${f.rerun}`
387
+ );
388
+ }
389
+
136
390
  /**
137
391
  * The refusal text.
138
392
  *
@@ -141,6 +395,53 @@ export function inertClosingReferences(body: string): InertClosingReference[] {
141
395
  * remedy is an obstacle. The remedy here is one character of punctuation, so
142
396
  * the message says exactly which.
143
397
  */
398
+ /** A closing keyword in a commit message, which GitHub acts on wherever it sits. */
399
+ export interface CommitClosingReference {
400
+ readonly sha: string;
401
+ readonly issue: number;
402
+ /** The matched text, so the message can quote what to reword. */
403
+ readonly text: string;
404
+ }
405
+
406
+ /**
407
+ * Every closing keyword in these commit messages, backticks and fences
408
+ * included (#1979).
409
+ *
410
+ * A commit message is not markdown. GitHub reads a keyword in it wherever it
411
+ * sits, so the markup that makes `Fixes #12` inert in a pull request body
412
+ * changes nothing here. That asymmetry closed #1717: PR #1978's squash commit
413
+ * quoted a backticked keyword while describing the defect.
414
+ */
415
+ export function commitClosingReferences(
416
+ commits: readonly { readonly sha: string; readonly message: string }[],
417
+ repoNameWithOwner: string,
418
+ ): CommitClosingReference[] {
419
+ const out: CommitClosingReference[] = [];
420
+ for (const c of commits) {
421
+ for (const m of c.message.matchAll(closingKeywordPattern())) {
422
+ // Bare `#N`, or this repository spelled out. Another repository's issue
423
+ // is not this pull request's to declare.
424
+ if (m[2] !== undefined && m[2].toLowerCase() !== repoNameWithOwner.toLowerCase()) continue;
425
+ out.push({ sha: c.sha, issue: Number.parseInt(m[3]!, 10), text: m[0] });
426
+ }
427
+ }
428
+ return out;
429
+ }
430
+
431
+ /** The refusal for a commit message that would close an issue this pull request does not declare. */
432
+ export function commitClosingMessage(refs: readonly CommitClosingReference[], prNumber: number): string {
433
+ const rows = refs.map(r => ` ${r.sha.slice(0, 8)}: "${r.text}" would close #${r.issue}`).join("\n");
434
+ return (
435
+ `PR #${prNumber} carries commit messages with a closing keyword for an issue it does ` +
436
+ `not declare:\n${rows}\n\n` +
437
+ `This repository squashes with the commit messages as the body, and merge and rebase ` +
438
+ `keep them as they are, so the merge closes each of these. Backticks do not stop it ` +
439
+ `in a commit message. Reword the commit so the number is not beside the verb ` +
440
+ `(write "issue #N"), then push. Or, if closing it is intended, add "Fixes #N" to this ` +
441
+ `description so the pull request declares it.`
442
+ );
443
+ }
444
+
144
445
  export function inertClosingMessage(refs: InertClosingReference[], prNumber: number): string {
145
446
  const rows = refs
146
447
  .map(r => ` ${r.text} — inside a ${r.reason}, so GitHub never linked it (issue #${r.issue})`)