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
@@ -0,0 +1,1123 @@
1
+ /**
2
+ * Covers SC-2612 (SPEC-TO-BOARD-PIPELINE-SPEC.md) — #1678.
3
+ *
4
+ * Turn a review finding that names real work into a criterion in a spec.
5
+ *
6
+ * ## The one design decision, stated out loud
7
+ *
8
+ * **`promote` does not decide whether a finding is real work.** That is a
9
+ * judgement, it is not re-derivable, and `lib/criterion-issue-census.ts`
10
+ * already refused to make the sibling judgement a column for exactly this
11
+ * reason: a boolean settable by whoever is looking rebuilds the
12
+ * tick-is-proof defect one level up, inside the instrument built to measure
13
+ * it.
14
+ *
15
+ * So the judgement arrives as INPUT — the caller supplies the criterion's
16
+ * sentence and the symbol it names, and owns them. What this module
17
+ * mechanises is everything downstream of that judgement and nothing before
18
+ * it:
19
+ *
20
+ * | Mechanical, decided here | Judgement, supplied by the caller |
21
+ * |---|---|
22
+ * | does the issue already serve a criterion | is this finding real work |
23
+ * | is the target spec one a criterion can live in | which spec it belongs to |
24
+ * | which id is free, and in whose block | what the criterion should say |
25
+ * | the criterion line's form | which symbol proves it |
26
+ *
27
+ * The second column is why this is not a `--auto` flag over the backlog.
28
+ *
29
+ * ## It reuses the decider that already exists
30
+ *
31
+ * "Does this issue serve a criterion" is answered by `criteriaNamedBy` in
32
+ * `lib/board-mirror.ts`, which the board renders from. A second answer to
33
+ * that question here would be behaviourally ONE decider with a dead half
34
+ * nobody can identify — the fourth shape in
35
+ * `.claude/rules/checks-must-be-able-to-fail.md`, and the defect this
36
+ * repository hits most. The board and this module agree because they are the
37
+ * same call, not because two implementations were kept in step.
38
+ *
39
+ * ## It fails closed
40
+ *
41
+ * Every refusal is a named member of {@link PROMOTION_REFUSALS}, and they are
42
+ * all produced by {@link promotionViolations} — one binding, so a mutation of
43
+ * it moves every refusing case at once and a case that passes for an
44
+ * unrelated reason is distinguishable from one genuinely caught.
45
+ */
46
+ import { existsSync, readFileSync } from "fs";
47
+ import { resolve, sep } from "path";
48
+
49
+ import { NAMES_NONE, answerableIds, criteriaNamedBy, criterionAnswer, specCriteriaIn } from "./board-mirror";
50
+ import { allocateScNumber, formatSCLine } from "./create-sc";
51
+ import { ISSUE_SECTIONS, headingFor, headingOccurrencesOf } from "./issue-shape";
52
+ import { fenceOpening, readFences } from "./markdown-fence";
53
+ import type { ScRegistry } from "./sc-ids";
54
+ import { declaresDeferred, parsePlacementRows, placementReading } from "./spec-placement";
55
+
56
+ /** The issue a finding was filed as. The shape `criteriaNamedBy` reads. */
57
+ export interface PromotableIssue {
58
+ readonly number: number;
59
+ readonly title: string;
60
+ readonly body?: string | null;
61
+ }
62
+
63
+ export interface PromotionInput {
64
+ readonly issue: PromotableIssue;
65
+ /** Repo-relative path of the spec the criterion will live in. */
66
+ readonly spec: string;
67
+ /** The criterion's sentence. The caller's judgement, carried verbatim. */
68
+ readonly outcome: string;
69
+ /** The symbol the criterion names, so it points at something a test can move. */
70
+ readonly symbol: string;
71
+ /** The module the symbol lives in, e.g. `lib/finding-promotion.ts`. */
72
+ readonly module: string;
73
+ readonly projectRoot: string;
74
+ /** Branch the reservation allocator should draw this id out of. */
75
+ readonly owner?: string | null;
76
+ /**
77
+ * The letter group for a spec whose ids are grouped, like the convergence
78
+ * spec's `CRC-M17` (#2066). Which section a criterion belongs to is the
79
+ * caller's judgement, like the symbol; it is refused when the spec needs
80
+ * one and none is given.
81
+ */
82
+ readonly group?: string | null;
83
+ }
84
+
85
+ /**
86
+ * Every way a promotion can be refused.
87
+ *
88
+ * Closed set, by design. A refusal nobody can name is a refusal nobody can
89
+ * act on, and "it didn't work" is the state this whole line of work exists to
90
+ * stop being reportable.
91
+ */
92
+ export const PROMOTION_REFUSALS = [
93
+ "SPEC_OUTSIDE_TREE",
94
+ "SPEC_ABSENT",
95
+ "SPEC_UNREADABLE",
96
+ "SWEEP_UNMEASURED",
97
+ "SPEC_STATES_NO_CRITERIA",
98
+ "ALREADY_SERVES",
99
+ "NO_OUTCOME",
100
+ "NO_SYMBOL",
101
+ "NO_MODULE",
102
+ "MALFORMED_STATEMENT",
103
+ "ID_UNAVAILABLE",
104
+ "SYMBOL_EXISTS",
105
+ "AMBIGUOUS_HEADING",
106
+ "GROUP_REQUIRED",
107
+ "GROUP_UNKNOWN",
108
+ "PHASE_REQUIRED",
109
+ "PHASE_ROW_ABSENT",
110
+ "BANK_DRIFT",
111
+ "ALREADY_PLACED",
112
+ "SECTION_REQUIRED",
113
+ "SECTION_UNKNOWN",
114
+ "SECTION_AMBIGUOUS",
115
+ ] as const;
116
+
117
+ export type PromotionRefusal = (typeof PROMOTION_REFUSALS)[number];
118
+
119
+ export interface PromotionViolation {
120
+ readonly refusal: PromotionRefusal;
121
+ readonly why: string;
122
+ }
123
+
124
+ export type Promotion =
125
+ | {
126
+ readonly promoted: true;
127
+ /** The criterion id, e.g. `SC-2615`. */
128
+ readonly id: string;
129
+ /** The line to insert, already in the form `sync-sc-status` reads. */
130
+ readonly line: string;
131
+ readonly spec: string;
132
+ readonly issue: number;
133
+ /** Anything the allocator could not consult, carried rather than dropped. */
134
+ readonly unmeasured: readonly string[];
135
+ /**
136
+ * The spec already states this exact criterion — a retry after the issue
137
+ * link failed (review of #2065). The caller writes nothing and links.
138
+ */
139
+ readonly alreadyWritten: boolean;
140
+ }
141
+ | { readonly promoted: false; readonly refusal: PromotionRefusal; readonly why: string };
142
+
143
+ /**
144
+ * The one resolver, exported so the CLI writes the file this module read.
145
+ *
146
+ * It had two: this resolved an absolute `--spec` as-is while
147
+ * `scripts/finding-promotion.ts` did `join(ROOT, spec)`, so for an absolute
148
+ * path the file VALIDATED and the file WRITTEN were different files. A guard
149
+ * whose subject is not the consumer's subject is not a guard.
150
+ *
151
+ * Containment to `specs/` is not a privilege boundary — the caller is a
152
+ * developer running a CLI in their own checkout and already owns the disk.
153
+ * It is here because a criterion written anywhere else is invisible to
154
+ * `specCriteriaIn`, `criterion-inventory` and `sync-sc-status`: the write
155
+ * would succeed and the criterion would not exist as far as this repository
156
+ * can tell.
157
+ */
158
+ export function specPath(input: Pick<PromotionInput, "spec" | "projectRoot">): string {
159
+ return resolve(input.projectRoot, input.spec);
160
+ }
161
+
162
+ /** Is the resolved target inside the project's `specs/` directory. */
163
+ function insideSpecs(input: Pick<PromotionInput, "spec" | "projectRoot">): boolean {
164
+ return specPath(input).startsWith(resolve(input.projectRoot, "specs") + sep);
165
+ }
166
+
167
+ /**
168
+ * A criterion is ONE line, and this is what keeps it one.
169
+ *
170
+ * `outcome`, `symbol` and `module` are the caller's free text and they are
171
+ * interpolated straight into markdown that `sync-sc-status` later parses. A
172
+ * newline in any of them appends further lines to a spec, and the cheapest
173
+ * useful one to append is `- [x] SC-NNNN: …` — a ticked criterion nobody
174
+ * wrote, in the file that is this repository's record of what is proved.
175
+ * `create-sc` guards its own statement with a regex; this is that guard.
176
+ */
177
+ const CRITERION_LINE = /^- \[ \] SC-\d+: [^\n\r]+$/;
178
+
179
+ /**
180
+ * Every free-text field `promotionStatement` interpolates, and its refusal.
181
+ *
182
+ * A LIST rather than three `if` blocks, because the first version guarded
183
+ * `outcome` and `symbol` and silently left `module` — an empty module
184
+ * produced `" contains [promote] — …"`, which still matches
185
+ * {@link CRITERION_LINE} and so sailed past the only other guard. Two of
186
+ * three is the shape this repository keeps shipping: the named instance
187
+ * repaired, its siblings left, and no behavioural case able to tell.
188
+ *
189
+ * `test/finding-promotion.test.ts` derives its cases from this array, so a
190
+ * fourth field added to `promotionStatement` without a row here is red
191
+ * rather than unguarded.
192
+ */
193
+ const STATEMENT_FIELDS = [
194
+ {
195
+ field: "outcome",
196
+ refusal: "NO_OUTCOME",
197
+ why: "a criterion with no sentence states nothing, so nothing could ever prove it",
198
+ },
199
+ {
200
+ field: "symbol",
201
+ refusal: "NO_SYMBOL",
202
+ why:
203
+ "a criterion that names no symbol cannot be moved by a mutation, so a test claiming " +
204
+ "it would be green by construction",
205
+ },
206
+ {
207
+ field: "module",
208
+ refusal: "NO_MODULE",
209
+ why:
210
+ "a criterion that names no module points its symbol at the whole tree, and " +
211
+ "sync-sc-status has no file to look in",
212
+ },
213
+ ] as const satisfies readonly {
214
+ field: "outcome" | "symbol" | "module";
215
+ refusal: PromotionRefusal;
216
+ why: string;
217
+ }[];
218
+
219
+ /** The fields above, for a test that wants to sweep them. */
220
+ export const STATEMENT_FIELD_NAMES = STATEMENT_FIELDS.map(f => f.field);
221
+
222
+ /**
223
+ * Every reason this promotion must not happen, in the order a reader should
224
+ * hear them.
225
+ *
226
+ * **This is the single binding.** `promote` adds no condition of its own, so
227
+ * short-circuiting this function to `[]` turns every refusing case into a
228
+ * promoting one — which is what `test/finding-promotion.test.ts` does to
229
+ * prove the refusals are observed rather than incidental.
230
+ */
231
+ /**
232
+ * Would `<module> contains [<symbol>]` already read as met? The SAME reading
233
+ * the matcher takes — `content-contains` in `lib/conformity.ts` is
234
+ * `expect(content).toContain(item)`: raw substring, comments and strings
235
+ * included. A narrower check here (a whole-identifier match, the first cut
236
+ * of #2060) let `promoted` through for symbol `promote`, which the matcher
237
+ * then reads as present: the false pass this refusal exists to stop.
238
+ */
239
+ function matcherWouldPass(text: string, symbol: string): boolean {
240
+ return text.includes(symbol);
241
+ }
242
+
243
+ export function promotionViolations(input: PromotionInput): PromotionViolation[] {
244
+ const out: PromotionViolation[] = [];
245
+
246
+ for (const { field, refusal, why } of STATEMENT_FIELDS) {
247
+ if (input[field].trim() === "") out.push({ refusal, why });
248
+ }
249
+
250
+ // #2060: the criterion is matched by `<module> contains [<symbol>]`, a
251
+ // presence check. A symbol the module already contains makes a criterion
252
+ // for work nobody has done read as met — `heredocInterpreter` on #2034.
253
+ // A module that exists and cannot be read cannot prove the symbol absent.
254
+ if (input.symbol.trim() !== "" && input.module.trim() !== "") {
255
+ const modulePath = resolve(input.projectRoot, input.module);
256
+ if (existsSync(modulePath)) {
257
+ let text: string | null;
258
+ try {
259
+ text = readFileSync(modulePath, "utf8");
260
+ } catch {
261
+ text = null;
262
+ }
263
+ if (text === null || matcherWouldPass(text, input.symbol)) {
264
+ out.push({
265
+ refusal: "SYMBOL_EXISTS",
266
+ why:
267
+ text === null
268
+ ? `${input.module} exists and could not be read, so ${input.symbol} cannot be shown to be absent`
269
+ : `${input.module} already contains ${input.symbol}, so \`contains [${input.symbol}]\` would read ` +
270
+ "as met before the work it names is done — pick a name the work will introduce",
271
+ });
272
+ }
273
+ }
274
+ }
275
+
276
+ // Checked before `existsSync`, so a path outside the tree is named for what
277
+ // it is rather than reported as a missing spec.
278
+ if (!insideSpecs(input)) {
279
+ out.push({
280
+ refusal: "SPEC_OUTSIDE_TREE",
281
+ why:
282
+ `${input.spec} resolves outside ${input.projectRoot}/specs, and a criterion written ` +
283
+ "there is invisible to specCriteriaIn, criterion-inventory and sync-sc-status",
284
+ });
285
+ return out;
286
+ }
287
+
288
+ const path = specPath(input);
289
+ if (!existsSync(path)) {
290
+ out.push({
291
+ refusal: "SPEC_ABSENT",
292
+ why: `${input.spec} is not in this tree, so the criterion would have no home`,
293
+ });
294
+ // Everything below reads the file. Stop rather than guess at its contents.
295
+ return out;
296
+ }
297
+
298
+ // EXISTS is not READABLE, and the two refusals must not share a message.
299
+ // A directory where a file was, or a permission, satisfies `existsSync`
300
+ // and throws here. Checked before the sweep because the sweep answers a
301
+ // target it cannot parse by simply contributing no ids, which reads
302
+ // downstream as "this spec states no criteria" — a true-sounding sentence
303
+ // about a file nobody managed to open.
304
+ try {
305
+ readFileSync(path, "utf8");
306
+ } catch (e) {
307
+ out.push({
308
+ refusal: "SPEC_UNREADABLE",
309
+ why: `${input.spec} exists and could not be read: ${e instanceof Error ? e.message : String(e)}`,
310
+ });
311
+ return out;
312
+ }
313
+
314
+ // The WHOLE tree, not this spec's ids. Scoping the duplicate check to the
315
+ // target let an issue serving a criterion in spec A promote into spec B
316
+ // unopposed — which is the outcome the refusal below says it prevents, so
317
+ // the detector was narrower than the thing it detects.
318
+ const sweep = specCriteriaIn(input.projectRoot);
319
+
320
+ // FIRST, and returning. `specCriteriaIn` answers UNMEASURED with
321
+ // `specs: []` and `ids: []`, so every reading below it is the reading for
322
+ // an empty tree: `hereIds` is empty and SPEC_STATES_NO_CRITERIA fires,
323
+ // reporting "this spec states no criteria" when the fact is "the sweep
324
+ // could not be taken". Two different states, one message, and the
325
+ // UNMEASURED branch that used to sit further down could never be reached.
326
+ //
327
+ // Found by the AI review of `4d48c7a3`, and the measurement is worse than
328
+ // the finding: `test/finding-promotion.test.ts`'s own
329
+ // SPEC_STATES_NO_CRITERIA case was passing through this path, so the
330
+ // criterion it claimed to cover was green for the wrong reason.
331
+ if (sweep.reading === "UNMEASURED") {
332
+ out.push({
333
+ refusal: "SWEEP_UNMEASURED",
334
+ why:
335
+ "the spec sweep could not be taken, so neither 'this spec states no criteria' nor " +
336
+ "'this issue serves none' is a reading anything here can make: " +
337
+ sweep.unmeasuredReasons.join("; "),
338
+ });
339
+ return out;
340
+ }
341
+
342
+ // `sweep.ids` keeps only criteria stated by exactly ONE spec — an id two
343
+ // specs both state is dropped and reported under `collisions`, because the
344
+ // board's cell has no room to say which spec was meant.
345
+ //
346
+ // That exclusion answers "which criterion do I attribute this issue to".
347
+ // The question here is "does this issue serve ANY criterion", and for that
348
+ // the ambiguity is irrelevant: an issue naming `SC-A1`, which three specs
349
+ // in this tree state, serves a criterion whichever one it meant. Reusing
350
+ // the narrower set let exactly those issues promote.
351
+ const allIds = answerableIds(sweep);
352
+ const hereIds = sweep.specs.find(s => resolve(input.projectRoot, s.path) === path)?.ids ?? [];
353
+
354
+ if (hereIds.length === 0) {
355
+ out.push({
356
+ refusal: "SPEC_STATES_NO_CRITERIA",
357
+ why:
358
+ `${input.spec} states no criteria, so it has no section a criterion belongs in — ` +
359
+ "promoting into it would put the first one somewhere nothing reads",
360
+ });
361
+ }
362
+
363
+ // Before the spec is written, not when the link fails after it: the link
364
+ // has no one section to write into (review of #2065).
365
+ const ambiguity = criteriaHeadingAmbiguity(input.issue.body ?? "", `#${input.issue.number}`);
366
+ if (ambiguity !== null) out.push({ refusal: "AMBIGUOUS_HEADING", why: ambiguity });
367
+
368
+ // The existing decider, not a second one. See the module docblock.
369
+ const alreadyServes = criteriaNamedBy(input.issue, allIds);
370
+ if (alreadyServes.length > 0) {
371
+ out.push({
372
+ refusal: "ALREADY_SERVES",
373
+ why:
374
+ `#${input.issue.number} already names ${alreadyServes.join(", ")}, so promoting it ` +
375
+ "would give one piece of work two criteria and make both of them partly true",
376
+ });
377
+ }
378
+
379
+ // Last, because it reads `outcome` and `symbol`, and an empty one of those
380
+ // is already reported above with a reason a caller can act on.
381
+ if (out.length === 0 && !CRITERION_LINE.test(formatSCLine(1, promotionStatement(input)))) {
382
+ out.push({
383
+ refusal: "MALFORMED_STATEMENT",
384
+ why:
385
+ "the statement would not be a single criterion line — a newline or carriage return in " +
386
+ "--outcome, --symbol or --module appends further markdown to the spec, and the cheapest " +
387
+ "thing to append is a ticked criterion nobody wrote",
388
+ });
389
+ }
390
+
391
+ return out;
392
+ }
393
+
394
+ /**
395
+ * The criterion a promoted finding becomes.
396
+ *
397
+ * Form follows `create-sc`: `contains [symbol]` is what `sync-sc-status`
398
+ * matches on, so a criterion written any other way is one nothing can tick.
399
+ */
400
+ export function promotionStatement(input: PromotionInput): string {
401
+ return `${input.module} contains [${input.symbol}] — ${input.outcome}`;
402
+ }
403
+
404
+ /**
405
+ * Promote a finding into a criterion, or refuse and say which refusal it was.
406
+ *
407
+ * Pure: it allocates an id and returns the line. The write is the caller's,
408
+ * so a dry run and a real run read the same spec and compute the same answer.
409
+ *
410
+ * `registry` has **no default**, for the reason `createIssue`'s `gate` has
411
+ * none (#1677): the reader lives in `scripts/sync-sc-status.ts`, and a lib
412
+ * reaching into `scripts/` to supply its own would both invert the
413
+ * dependency and make "a caller that forgot" a silent behaviour change. With
414
+ * no default the compiler catches every site.
415
+ */
416
+ export function promote(input: PromotionInput, registry: ScRegistry): Promotion {
417
+ const violations = promotionViolations(input);
418
+ // SYMBOL_EXISTS alone is held until the already-written scan below: once
419
+ // the criterion is in the spec, the symbol appearing is the work landing,
420
+ // and a retry of a failed link must still reach the link (review of #2065).
421
+ // Every other refusal holds. SYMBOL_EXISTS alone also means every spec
422
+ // check passed, so the read below is of a spec inside the tree.
423
+ // The blocker is reported, not SYMBOL_EXISTS, which is pushed early and
424
+ // would otherwise sit at index 0 over a missing spec (review of #2065).
425
+ const blocker = violations.find(v => v.refusal !== "SYMBOL_EXISTS");
426
+ if (blocker) return { promoted: false, refusal: blocker.refusal, why: blocker.why };
427
+
428
+ // Inside a guard, because `promotionViolations` proved the file EXISTS and
429
+ // existing is not the same as readable — a permission, a directory where a
430
+ // file was, or a removal between the two calls. An uncaught throw out of a
431
+ // function whose docblock says it fails closed is the one shape a caller
432
+ // cannot handle as a refusal.
433
+ let specText: string;
434
+ try {
435
+ specText = readFileSync(specPath(input), "utf8");
436
+ } catch (e) {
437
+ return {
438
+ promoted: false,
439
+ refusal: "SPEC_UNREADABLE",
440
+ why: `${input.spec} exists and could not be read: ${e instanceof Error ? e.message : String(e)}`,
441
+ };
442
+ }
443
+
444
+ // A retry after a failed issue link finds its own line already written.
445
+ // Allocating again would append a second copy of one criterion for one
446
+ // finding (review of #2065), so the existing line is the answer.
447
+ const statement = promotionStatement(input);
448
+ for (const raw of specText.split("\n")) {
449
+ const m = /^- \[[ xX]\] ([A-Z]+-[A-Z]?\d+): (.*)$/.exec(raw);
450
+ if (m && m[2] === statement) {
451
+ return {
452
+ promoted: true,
453
+ id: m[1]!,
454
+ line: raw,
455
+ spec: input.spec,
456
+ issue: input.issue.number,
457
+ unmeasured: [],
458
+ alreadyWritten: true,
459
+ };
460
+ }
461
+ }
462
+
463
+ if (violations.length > 0) {
464
+ const first = violations[0]!;
465
+ return { promoted: false, refusal: first.refusal, why: first.why };
466
+ }
467
+
468
+ // #2066: a spec whose criteria use their own grouped family (the
469
+ // convergence spec's `CRC-M17`) gets an id in that family, never an `SC-`
470
+ // id. It used to be allocated `SC-N` and renamed by hand.
471
+ const family = idFamily(specText);
472
+ if (family !== "SC") {
473
+ const grouped = nextGroupedId(specText, family, input.group ?? null);
474
+ if (!grouped.ok) return { promoted: false, refusal: grouped.refusal, why: grouped.why };
475
+ return {
476
+ promoted: true,
477
+ id: grouped.id,
478
+ line: `- [ ] ${grouped.id}: ${statement}`,
479
+ spec: input.spec,
480
+ issue: input.issue.number,
481
+ // Said, not hidden: `SC-` ids go through specs/sc-reservations.json, and
482
+ // a grouped family has no reservation registry, so another branch
483
+ // promoting into the same group can take the same id (review of #2105).
484
+ unmeasured: [
485
+ `${family}-* ids have no reservation registry: an id another branch allocated in group ${input.group} is not visible here`,
486
+ ],
487
+ alreadyWritten: false,
488
+ };
489
+ }
490
+
491
+ let allocated: { number: number; namespace: { unmeasured: string[] } };
492
+ try {
493
+ allocated = allocateScNumber(input.projectRoot, specText, registry, {
494
+ owner: input.owner ?? null,
495
+ }) as typeof allocated;
496
+ } catch (e) {
497
+ // The allocator refuses on an unreadable reservation store and on a spent
498
+ // block. Both are states where handing out a number would collide with
499
+ // work nobody in this session can see.
500
+ return {
501
+ promoted: false,
502
+ refusal: "ID_UNAVAILABLE",
503
+ why: e instanceof Error ? e.message : String(e),
504
+ };
505
+ }
506
+
507
+ return {
508
+ promoted: true,
509
+ id: `SC-${allocated.number}`,
510
+ line: formatSCLine(allocated.number, promotionStatement(input)),
511
+ spec: input.spec,
512
+ issue: input.issue.number,
513
+ unmeasured: allocated.namespace.unmeasured ?? [],
514
+ alreadyWritten: false,
515
+ };
516
+ }
517
+
518
+ /** A criterion id at the start of a checkbox line, any family: `SC-12`, `CRC-M17`. */
519
+ const ANY_CRITERION_LINE = /^- \[[ xX]\] ([A-Z]+)-([A-Z]?)(\d+):/;
520
+
521
+ /**
522
+ * The id family a spec's criteria use — #2066.
523
+ *
524
+ * `SC` unless every criterion in the spec uses one other prefix, as the
525
+ * convergence spec's `CRC-*` do. A spec with no criteria, or a mixture, is
526
+ * `SC`: a mixture has no single family to continue, and `SC` is the
527
+ * repository's default.
528
+ */
529
+ export function idFamily(specText: string): string {
530
+ const prefixes = new Set<string>();
531
+ for (const line of specText.split("\n")) {
532
+ const m = ANY_CRITERION_LINE.exec(line);
533
+ if (m) prefixes.add(m[1]!);
534
+ }
535
+ return prefixes.size === 1 && !prefixes.has("SC") ? [...prefixes][0]! : "SC";
536
+ }
537
+
538
+ /**
539
+ * The next id in a grouped family: one above the highest number in the
540
+ * group. The group must already exist in the spec — a letter nothing uses is
541
+ * almost always a typo, and a new section is a spec edit, not a promotion.
542
+ */
543
+ export function nextGroupedId(
544
+ specText: string,
545
+ family: string,
546
+ group: string | null,
547
+ ): { ok: true; id: string } | { ok: false; refusal: PromotionRefusal; why: string } {
548
+ if (group === null || group.trim() === "") {
549
+ return {
550
+ ok: false,
551
+ refusal: "GROUP_REQUIRED",
552
+ why: `this spec's criteria are ${family}-* ids in letter groups; pass --group <letter> to say which section this one belongs to`,
553
+ };
554
+ }
555
+ let highest = 0;
556
+ let seen = false;
557
+ for (const line of specText.split("\n")) {
558
+ const m = ANY_CRITERION_LINE.exec(line);
559
+ if (m && m[1] === family && m[2] === group) {
560
+ seen = true;
561
+ highest = Math.max(highest, Number(m[3]));
562
+ }
563
+ }
564
+ if (!seen) {
565
+ return { ok: false, refusal: "GROUP_UNKNOWN", why: `no criterion in this spec is ${family}-${group}*; check the letter` };
566
+ }
567
+ return { ok: true, id: `${family}-${group}${highest + 1}` };
568
+ }
569
+
570
+ /**
571
+ * The spec with the criterion line inserted where the spec keeps its
572
+ * criteria, and its id placed in a phase when asked — #2066.
573
+ *
574
+ * The line goes after the last criterion of its own group (any criterion, for
575
+ * an ungrouped family), below that criterion's indented `proved-by:` lines.
576
+ * It used to be appended at the end of the file, under whatever section came
577
+ * last, and moved by hand.
578
+ *
579
+ * **A spec that places its criteria refuses an unplaced one.** When the spec
580
+ * has a Phase placement table that is fully read, a criterion with no phase
581
+ * leaves `spec-placement` short, and that reading is stage item E1's proof,
582
+ * run live in every pull request's CI. So `--phase` is required there, and
583
+ * the result is re-read with `placementReading`, the reader the check uses.
584
+ */
585
+ export function specWithCriterion(
586
+ specText: string,
587
+ line: string,
588
+ id: string,
589
+ phase: number | null,
590
+ section: string | null = null,
591
+ ): { ok: true; text: string } | { ok: false; refusal: PromotionRefusal; why: string } {
592
+ // Already written (a retry after a failed link): the line stays where it
593
+ // is, and the phase and placement checks below still run on it, so a retry
594
+ // with --phase places it and a missing row still refuses (review of #2105).
595
+ const lines = specText.split("\n");
596
+ const present = lines.includes(line);
597
+ const [, family, group] = /^([A-Z]+)-([A-Z]?)\d+$/.exec(id) ?? [];
598
+ // #2110: the SECTION each criterion of this family sits in, so a spec
599
+ // keeping them in several is not appended to after whichever comes last.
600
+ // A section is a heading OCCURRENCE, not its text: HARNESS-STANDARD.md has
601
+ // `### Success Criteria` twenty-six times, one per feature (review of
602
+ // #2127). Each is named by its path of parent headings, so `Feature A >
603
+ // Success Criteria` and `Feature B > Success Criteria` are told apart.
604
+ // A `#` line inside a fenced block is code, and an unclosed fence refuses
605
+ // rather than hiding every line after it.
606
+ type Section = { line: number; path: string; text: string };
607
+ const sectionOf: { at: number; section: Section }[] = [];
608
+ const stack: { level: number; text: string }[] = [];
609
+ let current: Section = { line: 0, path: "", text: "" };
610
+ // CommonMark: a fence closes only on the SAME character, at least as many
611
+ // times, with nothing after it. Any other fence-shaped line inside is
612
+ // content (review round 2 of #2127: ``` holding ~~~, and the reverse).
613
+ // The grammar is `lib/markdown-fence.ts`'s, shared with every lib/ reader
614
+ // (#2130).
615
+ const fences = readFences(lines);
616
+ for (let i = 0; i < lines.length; i++) {
617
+ const raw = lines[i]!;
618
+ if (fences.roles[i] !== "prose") continue;
619
+ const h = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(raw);
620
+ if (h) {
621
+ const level = h[1]!.length;
622
+ while (stack.length > 0 && stack[stack.length - 1]!.level >= level) stack.pop();
623
+ stack.push({ level, text: h[2]! });
624
+ current = { line: i + 1, path: stack.map(x => x.text).join(" > "), text: h[2]! };
625
+ }
626
+ const m = ANY_CRITERION_LINE.exec(raw);
627
+ if (m && (family === "SC" || (m[1] === family && m[2] === group))) sectionOf.push({ at: i, section: current });
628
+ }
629
+ if (fences.unclosedAt !== null && !present) {
630
+ return {
631
+ ok: false,
632
+ refusal: "SPEC_UNREADABLE",
633
+ why:
634
+ `the code fence opened at line ${fences.unclosedAt + 1} is never closed, so no heading or ` +
635
+ "criterion after it can be read; close it, then re-run",
636
+ };
637
+ }
638
+ const sections = [...new Map(sectionOf.map(s => [s.section.line, s.section])).values()];
639
+ // Every label is a string `--section` accepts. The headless section has no
640
+ // heading text or path, so it is named by its line, which is 0 (#2131).
641
+ const label = (sec: Section) =>
642
+ sec.path === "" ? `"line ${sec.line}" (before any heading)` : `"${sec.path}" (line ${sec.line})`;
643
+ let candidates = sectionOf;
644
+ if (!present && section !== null) {
645
+ const asked = section.trim();
646
+ const byLine = /^line (\d+)$/.exec(asked);
647
+ const matches = sections.filter(sec =>
648
+ byLine ? sec.line === Number(byLine[1]) : sec.path === asked || sec.path.endsWith(` > ${asked}`) || sec.text === asked,
649
+ );
650
+ if (matches.length === 0) {
651
+ return {
652
+ ok: false,
653
+ refusal: "SECTION_UNKNOWN",
654
+ why:
655
+ `no criterion sits under a section "${asked}"` +
656
+ (sections.length > 0 ? `; the sections holding this spec's criteria are ${sections.map(label).join(", ")}` : ""),
657
+ };
658
+ }
659
+ if (matches.length > 1) {
660
+ return {
661
+ ok: false,
662
+ refusal: "SECTION_AMBIGUOUS",
663
+ why:
664
+ `"${asked}" names ${matches.length} sections: ${matches.map(label).join(", ")}. ` +
665
+ 'Name one by its path ("Parent > Heading") or by its heading line ("line N")',
666
+ };
667
+ }
668
+ candidates = sectionOf.filter(s => s.section.line === matches[0]!.line);
669
+ } else if (!present && sections.length > 1) {
670
+ return {
671
+ ok: false,
672
+ refusal: "SECTION_REQUIRED",
673
+ why:
674
+ `this spec keeps its criteria in ${sections.length} sections, so the line needs --section ` +
675
+ `naming one: ${sections.map(label).join(", ")}. After the last criterion in the file can be ` +
676
+ "inside an unrelated section, above that section's own analysis",
677
+ };
678
+ }
679
+ const last = candidates.length === 0 ? -1 : candidates[candidates.length - 1]!.at;
680
+ let text: string;
681
+ if (present) {
682
+ text = specText;
683
+ } else if (last === -1) {
684
+ text = `${specText.trimEnd()}\n${line}\n`;
685
+ } else {
686
+ let at = last + 1;
687
+ // Past the criterion's indented proof lines AND any note directly under
688
+ // it, such as a `<!-- REVIEW: … -->` line: both belong to that criterion,
689
+ // and a new line between them moves the note onto the wrong one (#2107).
690
+ while (
691
+ at < lines.length &&
692
+ (/^\s+\S/.test(lines[at]!) || /^<!--.*-->\s*$/.test(lines[at]!)) &&
693
+ !ANY_CRITERION_LINE.test(lines[at]!)
694
+ ) {
695
+ at++;
696
+ }
697
+ text = [...lines.slice(0, at), line, ...lines.slice(at)].join("\n");
698
+ }
699
+ if (phase !== null) {
700
+ // One home per criterion: an id already in a DIFFERENT phase row is refused
701
+ // rather than listed twice (#2107). Its own row again is a no-op below.
702
+ const elsewhere = parsePlacementRows(text).find(r => r.ids.includes(id) && r.placement !== `Phase ${phase}`);
703
+ if (elsewhere) {
704
+ return {
705
+ ok: false,
706
+ refusal: "ALREADY_PLACED",
707
+ why: `${id} is already placed in ${elsewhere.placement}; a criterion has one phase, so move it by editing the table`,
708
+ };
709
+ }
710
+ const placed = withPhase(text, id, phase);
711
+ if (placed === null) {
712
+ return { ok: false, refusal: "PHASE_ROW_ABSENT", why: `this spec's Phase placement table has no row for Phase ${phase}` };
713
+ }
714
+ text = placed;
715
+ }
716
+ const reading = placementReading(text);
717
+ if (reading.reading === "MEASURED" && reading.unplaced.includes(id)) {
718
+ return {
719
+ ok: false,
720
+ refusal: "PHASE_REQUIRED",
721
+ why: `this spec places every criterion in a phase, so ${id} needs --phase N; unplaced, it would leave spec-placement short`,
722
+ };
723
+ }
724
+ return { ok: true, text };
725
+ }
726
+
727
+ /** The spec with `id` added to its `Phase N` placement row, or null when there is no such row. */
728
+ function withPhase(specText: string, id: string, phase: number | null): string | null {
729
+ if (phase === null) return specText;
730
+ const row = parsePlacementRows(specText).find(r => r.placement === `Phase ${phase}`);
731
+ if (!row) return null;
732
+ if (row.ids.includes(id)) return specText;
733
+ const lines = specText.split("\n");
734
+ const cells = lines[row.line - 1]!.split("|");
735
+ // `| **Phase 6** | SC-1, SC-2 | notes |` splits to ["", " **Phase 6** ", " SC-1, SC-2 ", " notes ", ""].
736
+ const idsCell = cells[2]!.trim();
737
+ cells[2] = ` ${idsCell === "" ? id : `${idsCell}, ${id}`} `;
738
+ lines[row.line - 1] = cells.join("|");
739
+ return lines.join("\n");
740
+ }
741
+
742
+ /**
743
+ * The deferral bank with this spec's count moved to its new number, when the
744
+ * spec is deferred — #2066.
745
+ *
746
+ * `spec-placement` refuses a deferred spec whose criteria count disagrees with
747
+ * `.claude/spec-deferral-ratchet.json`, so a promotion into one left E1's proof
748
+ * red until the bank was edited by hand. The bank moves only from the count
749
+ * the spec had BEFORE this promotion: a bank already out of step is drift
750
+ * someone has to look at, and moving it silently would hide it.
751
+ */
752
+ export function bankWithPromotion(
753
+ bankText: string,
754
+ specPath: string,
755
+ before: number,
756
+ after: number,
757
+ ): { ok: true; text: string } | { ok: false; refusal: PromotionRefusal; why: string } {
758
+ let bank: { deferred?: { path: string; criteria: number }[] };
759
+ try {
760
+ bank = JSON.parse(bankText);
761
+ } catch (e) {
762
+ return { ok: false, refusal: "BANK_DRIFT", why: `the deferral bank is not JSON (${(e as Error).message})` };
763
+ }
764
+ const row = Array.isArray(bank.deferred) ? bank.deferred.find(d => d.path === specPath) : undefined;
765
+ if (!row) return { ok: false, refusal: "BANK_DRIFT", why: `${specPath} is deferred and not in the deferral bank` };
766
+ if (row.criteria !== before) {
767
+ return {
768
+ ok: false,
769
+ refusal: "BANK_DRIFT",
770
+ why: `the deferral bank holds ${row.criteria} for ${specPath}, which states ${before}; reconcile it before promoting`,
771
+ };
772
+ }
773
+ row.criteria = after;
774
+ return { ok: true, text: `${JSON.stringify(bank, null, 2)}\n` };
775
+ }
776
+
777
+ /**
778
+ * The bank on a RETRY, when the criterion is already in the spec — review of
779
+ * #2105.
780
+ *
781
+ * A run whose spec write landed and whose bank write failed leaves the bank
782
+ * one behind. A retry finds the line already written, sees no count change,
783
+ * and without this would report success over a bank that disagrees with the
784
+ * spec, so the next unrelated promotion is the one refused. So: in step, write
785
+ * nothing (`text: null`); exactly one behind, move it; further out, refuse.
786
+ */
787
+ export function bankForRetry(
788
+ bankText: string,
789
+ specPath: string,
790
+ count: number,
791
+ ): { ok: true; text: string | null } | { ok: false; refusal: PromotionRefusal; why: string } {
792
+ let bank: { deferred?: { path: string; criteria: number }[] };
793
+ try {
794
+ bank = JSON.parse(bankText);
795
+ } catch (e) {
796
+ return { ok: false, refusal: "BANK_DRIFT", why: `the deferral bank is not JSON (${(e as Error).message})` };
797
+ }
798
+ const row = Array.isArray(bank.deferred) ? bank.deferred.find(d => d.path === specPath) : undefined;
799
+ if (row?.criteria === count) return { ok: true, text: null };
800
+ return bankWithPromotion(bankText, specPath, count - 1, count);
801
+ }
802
+
803
+ /** Whether `specText` is deferred, and how many criteria it states, as `spec-placement` reads them. */
804
+ export function placementCount(specText: string): { deferred: boolean; criteria: number } {
805
+ return { deferred: declaresDeferred(specText), criteria: placementReading(specText).criteria.length };
806
+ }
807
+
808
+ /**
809
+ * ## Declining — the router's other outcome
810
+ *
811
+ * `NAMES_NONE` has been readable since SC-2609 and writable by nothing.
812
+ * `scripts/board-snapshot.ts` reports an issue carrying the literal as a
813
+ * DELIBERATE decline rather than a blank cell, which is the whole point of
814
+ * spelling the value: *not yet filled in*, *the tool could not tell* and
815
+ * *deliberately none* stop being the same zero bytes.
816
+ *
817
+ * The one creation path was worse than none. `.github/ISSUE_TEMPLATE/
818
+ * spec-work.yml` tells a human author to type the phrase, so the board's
819
+ * only source for "this work serves no criterion" was a **self-declaration**
820
+ * — the shape `lib/criterion-issue-census.ts` refused to make a column and
821
+ * this module's own docblock refuses to make a flag, for the same reason in
822
+ * all three places: a judgement settable by whoever is looking rebuilds the
823
+ * tick-is-proof defect inside the instrument built to measure it.
824
+ *
825
+ * So the declaration is an OUTCOME here, on the same terms as a promotion:
826
+ *
827
+ * - The board must already agree there is no criterion. {@link decline} asks
828
+ * `criteriaNamedBy` — the call the board renders from, not a second answer
829
+ * to the same question.
830
+ * - A sweep that could not be taken refuses. "This issue serves none" is not
831
+ * a reading available to something that could not enumerate the criteria.
832
+ * - The phrase is interpolated from {@link NAMES_NONE}. A producer that
833
+ * retyped it would be a second language for one value, which is exactly
834
+ * the drift `test/board-snapshot.test.ts` had to add a case for when the
835
+ * form said `none — machinery` and the reader matched the constant.
836
+ */
837
+ export const DECLINE_REFUSALS = [
838
+ "NO_WHY",
839
+ "MALFORMED_WHY",
840
+ "WHY_NAMES_CRITERION",
841
+ "SWEEP_UNMEASURED",
842
+ "ALREADY_SERVES",
843
+ "ALREADY_DECLINED",
844
+ "AMBIGUOUS_HEADING",
845
+ "CRITERIA_SECTION_OCCUPIED",
846
+ ] as const;
847
+
848
+ export type DeclineRefusal = (typeof DECLINE_REFUSALS)[number];
849
+
850
+ export interface DeclineViolation {
851
+ readonly refusal: DeclineRefusal;
852
+ readonly why: string;
853
+ }
854
+
855
+ export interface DeclineInput {
856
+ readonly issue: PromotableIssue;
857
+ /** The caller's reason. Their judgement, owned by them, and required. */
858
+ readonly why: string;
859
+ readonly projectRoot: string;
860
+ }
861
+
862
+ export type Decline =
863
+ | {
864
+ readonly declined: true;
865
+ /**
866
+ * The issue's COMPLETE new body — exactly the bytes a caller writes.
867
+ *
868
+ * The first version returned only `section` and documented it as the
869
+ * preview. For a body already carrying an empty criteria heading
870
+ * {@link bodyWithDecline} inserts the line alone, so the preview
871
+ * showed a second heading that never appeared: a false report about
872
+ * a write, which is the one thing this module exists not to produce.
873
+ */
874
+ readonly body: string;
875
+ /** The standalone section, for a body that has no criteria heading. */
876
+ readonly section: string;
877
+ readonly issue: number;
878
+ }
879
+ | { readonly declined: false; readonly refusal: DeclineRefusal; readonly why: string };
880
+
881
+ /** The heading a declaration lives under, from the one place that names it. */
882
+ const CRITERIA_HEADING = headingFor(ISSUE_SECTIONS.find(s => s.id === "criteria")!);
883
+
884
+ /**
885
+ * The text a decline writes.
886
+ *
887
+ * `NAMES_NONE` is interpolated, never retyped: `scripts/board-snapshot.ts`
888
+ * matches the literal, so a producer spelling it itself would be a second
889
+ * language for one value and the two would drift silently.
890
+ */
891
+ export function declineSection(why: string): string {
892
+ return `${CRITERIA_HEADING}\n\n${NAMES_NONE} — ${why.trim()}\n`;
893
+ }
894
+
895
+ /**
896
+ * Every reason this decline must not be written.
897
+ *
898
+ * **The single binding.** {@link decline} adds no condition of its own, so
899
+ * short-circuiting this to `[]` turns every refusing input into a declining
900
+ * one — which is what `test/finding-promotion.test.ts` does to prove the
901
+ * refusals are observed rather than incidental.
902
+ */
903
+ export function declineViolations(input: DeclineInput): DeclineViolation[] {
904
+ const out: DeclineViolation[] = [];
905
+
906
+ if (input.why.trim() === "") {
907
+ out.push({
908
+ refusal: "NO_WHY",
909
+ why:
910
+ "a decline with no reason is a tick — it asserts a judgement and records nothing " +
911
+ "anybody could later disagree with",
912
+ });
913
+ }
914
+
915
+ // The `why` is interpolated into an issue BODY that `missingSections`
916
+ // parses by heading, so a line opening with `#` forges a section. Same
917
+ // class as MALFORMED_STATEMENT above, one layer out: there the cheapest
918
+ // thing to append was a ticked criterion, here it is a Files heading that
919
+ // makes an issue look like it named files nobody wrote.
920
+ if (/^[ \t]*#{1,6}[ \t]/m.test(input.why)) {
921
+ out.push({
922
+ refusal: "MALFORMED_WHY",
923
+ why:
924
+ "--why opens a markdown heading, which forges a section in the issue body that " +
925
+ "missingSections and every reader would then treat as the author's",
926
+ });
927
+ }
928
+
929
+ // A FENCE, not only a heading. The first version guarded the heading and
930
+ // not this, which is a detector narrower than what it detects: an odd
931
+ // number of fence lines flips fence state for everything below, and
932
+ // `headingOccurrencesOf`, `hasContent` and `missingSections` all track
933
+ // fences the same way — so every later heading in the body becomes
934
+ // invisible to all three at once and the issue parses as having no
935
+ // sections at all. Refused outright rather than balanced, because a
936
+ // one-line reason has no use for a code block. A `~~~` line too: every
937
+ // heading reader shares `lib/markdown-fence.ts` now (#2130), so it flips
938
+ // fence state for all of them exactly as a ``` line does.
939
+ if (input.why.split("\n").some(line => fenceOpening(line) !== null)) {
940
+ out.push({
941
+ refusal: "MALFORMED_WHY",
942
+ why:
943
+ "--why contains a code fence, and an odd number of them flips fence state for the " +
944
+ "rest of the body — every heading below it becomes invisible to headingOccurrencesOf, " +
945
+ "hasContent and missingSections at once",
946
+ });
947
+ }
948
+
949
+ const sweep = specCriteriaIn(input.projectRoot);
950
+
951
+ // FIRST among the sweep-dependent readings, and returning. An UNMEASURED
952
+ // sweep answers with `ids: []`, which makes "this issue serves no
953
+ // criterion" true of every issue — the sentence this whole function exists
954
+ // to stop being writable without evidence.
955
+ if (sweep.reading === "UNMEASURED") {
956
+ out.push({
957
+ refusal: "SWEEP_UNMEASURED",
958
+ why:
959
+ "the spec sweep could not be taken, so 'this issue serves no criterion' is not a " +
960
+ "reading anything here can make: " + sweep.unmeasuredReasons.join("; "),
961
+ });
962
+ return out;
963
+ }
964
+
965
+ // `collisions` folded in for the reason `promotionViolations` folds them
966
+ // in: the question is whether the issue serves ANY criterion, and an id two
967
+ // specs both state is still a criterion served.
968
+ const allIds = answerableIds(sweep);
969
+
970
+ // The existing decider, not a second one — the same call the board renders
971
+ // from. A decline and a populated criteria cell are states the board cannot
972
+ // hold at once, and the board, not this module, is the one that decides.
973
+ const serves = criteriaNamedBy(input.issue, allIds);
974
+ if (serves.length > 0) {
975
+ out.push({
976
+ refusal: "ALREADY_SERVES",
977
+ why:
978
+ `#${input.issue.number} already names ${serves.join(", ")}, so a decline would make the ` +
979
+ "board say both that it serves a criterion and that it serves none",
980
+ });
981
+ }
982
+
983
+ // Same decider again, pointed at the text about to be written. A reason
984
+ // mentioning an id puts that id in the cell the moment this is appended,
985
+ // so the declaration would contradict itself in the bytes it is made of.
986
+ const namedByWhy = criteriaNamedBy({ title: "", body: input.why }, allIds);
987
+ if (namedByWhy.length > 0) {
988
+ out.push({
989
+ refusal: "WHY_NAMES_CRITERION",
990
+ why:
991
+ `--why names ${namedByWhy.join(", ")}, and criteriaNamedBy reads the body this would be ` +
992
+ "appended to, so the issue would declare no criterion in text that names one",
993
+ });
994
+ }
995
+
996
+ const body = input.issue.body ?? "";
997
+
998
+ // The one decider for the declaration (#2020), not a third copy of it.
999
+ if (criterionAnswer(input.issue, allIds).servesNone) {
1000
+ out.push({
1001
+ refusal: "ALREADY_DECLINED",
1002
+ why:
1003
+ `#${input.issue.number} already declares it serves no criterion, and a second ` +
1004
+ "declaration would give board-snapshot two reasons it cannot tell apart",
1005
+ });
1006
+ }
1007
+
1008
+ // Where the declaration would go. Both readings below are about the
1009
+ // WRITE, so they live here rather than in `bodyWithDecline`: a refusal
1010
+ // discovered by the writer is a refusal discovered after the caller was
1011
+ // told it would work.
1012
+ const headings = headingOccurrencesOf(body, CRITERIA_HEADING);
1013
+ const ambiguity = criteriaHeadingAmbiguity(body, `#${input.issue.number}`);
1014
+ if (ambiguity !== null) {
1015
+ out.push({ refusal: "AMBIGUOUS_HEADING", why: ambiguity });
1016
+ } else if (headings.length === 1 && hasTextUnder(body, headings[0]!)) {
1017
+ out.push({
1018
+ refusal: "CRITERIA_SECTION_OCCUPIED",
1019
+ why:
1020
+ `#${input.issue.number}'s criteria section already says something that names no ` +
1021
+ "criterion, and overwriting it would delete what the author wrote while declaring " +
1022
+ "the opposite of it",
1023
+ });
1024
+ }
1025
+
1026
+ return out;
1027
+ }
1028
+
1029
+ /**
1030
+ * Why `body` has no one criteria section to write into, or null when it has
1031
+ * zero or one. The one decider for the decline path, the promote path and
1032
+ * the link (review of #2065), so the three cannot disagree about the shape.
1033
+ */
1034
+ export function criteriaHeadingAmbiguity(body: string, who: string): string | null {
1035
+ const count = headingOccurrencesOf(body, CRITERIA_HEADING).length;
1036
+ if (count <= 1) return null;
1037
+ return (
1038
+ `${who} opens "${CRITERIA_HEADING}" ${count} times, so there is ` +
1039
+ "no one section to write into and a reader cannot tell which one the board read"
1040
+ );
1041
+ }
1042
+
1043
+ /** Non-blank text between the heading at `at` and the next heading. */
1044
+ function hasTextUnder(body: string, at: number): boolean {
1045
+ for (const line of body.slice(at).split("\n").slice(1)) {
1046
+ if (/^#{1,6}\s+\S/.test(line)) return false;
1047
+ if (line.trim() !== "") return true;
1048
+ }
1049
+ return false;
1050
+ }
1051
+
1052
+ /**
1053
+ * `body` with the declaration in the section the readers parse.
1054
+ *
1055
+ * Two shapes, because issues arrive in both: an `everyday-work` body has no
1056
+ * criteria heading and gains the whole section, and a `spec-work` body
1057
+ * filed through the form carries the heading with nothing under it and
1058
+ * gains only the line. Appending blindly in the second case puts the
1059
+ * declaration under whatever heading happens to be last — `Files this will
1060
+ * change`, in the form's own order — where `missingSections` still reports
1061
+ * the criteria section empty and the author sees a stray sentence in the
1062
+ * wrong place.
1063
+ *
1064
+ * Fence-aware through `headingOccurrencesOf`, which is the whole reason that
1065
+ * function was generalised out of `lib/issue-repair.ts`: these bodies quote
1066
+ * the template constantly, and a fence-blind insert lands inside a code
1067
+ * block where no reader of the rendered issue ever sees it.
1068
+ *
1069
+ * The ambiguous and occupied cases are refused upstream by
1070
+ * {@link declineViolations}, so this handles zero or one empty heading.
1071
+ */
1072
+ export function bodyWithDecline(body: string, why: string): string {
1073
+ const at = headingOccurrencesOf(body, CRITERIA_HEADING)[0];
1074
+ const line = `${NAMES_NONE} — ${why.trim()}`;
1075
+ if (at === undefined) return `${body.trimEnd()}\n\n${declineSection(why)}`;
1076
+ const headingEnd = body.indexOf("\n", at);
1077
+ const cut = headingEnd === -1 ? body.length : headingEnd;
1078
+ return `${body.slice(0, cut)}\n\n${line}\n${body.slice(cut).replace(/^\n+/, "\n")}`;
1079
+ }
1080
+
1081
+ /**
1082
+ * The issue body with `id` named under its `## Criteria this serves` heading
1083
+ * (#2060). A promotion used to print "now make #N name it" and leave the
1084
+ * edit to a person; ADR-015 linked twelve issues through repair rows
1085
+ * instead. Unchanged when the body already names `id`.
1086
+ *
1087
+ * Refuses a body with two criteria headings rather than picking the first.
1088
+ * `promote` refuses that shape before the spec is written; this catches a
1089
+ * body that gained one between that check and the re-read.
1090
+ */
1091
+ export type CriterionLink =
1092
+ | { readonly linked: true; readonly body: string }
1093
+ | { readonly linked: false; readonly why: string };
1094
+
1095
+ export function withCriterionLinked(body: string, id: string): CriterionLink {
1096
+ if (criteriaNamedBy({ title: "", body }, [id]).length > 0) return { linked: true, body };
1097
+ // The number is not known here; the CLI names the issue in its message.
1098
+ const ambiguity = criteriaHeadingAmbiguity(body, "the issue");
1099
+ if (ambiguity !== null) return { linked: false, why: ambiguity };
1100
+ const at = headingOccurrencesOf(body, CRITERIA_HEADING)[0];
1101
+ if (at === undefined) return { linked: true, body: `${body.trimEnd()}\n\n${CRITERIA_HEADING}\n\n${id}\n` };
1102
+ const headingEnd = body.indexOf("\n", at);
1103
+ const cut = headingEnd === -1 ? body.length : headingEnd;
1104
+ return { linked: true, body: `${body.slice(0, cut)}\n\n${id}${body.slice(cut).replace(/^\n+/, "\n")}` };
1105
+ }
1106
+
1107
+ /**
1108
+ * Decline on an issue's behalf, or refuse and say which refusal it was.
1109
+ *
1110
+ * Pure: it returns the markdown and writes nothing. The write is the
1111
+ * caller's, so a dry run and a real run compute the same answer.
1112
+ */
1113
+ export function decline(input: DeclineInput): Decline {
1114
+ const violations = declineViolations(input);
1115
+ const first = violations[0];
1116
+ if (first) return { declined: false, refusal: first.refusal, why: first.why };
1117
+ return {
1118
+ declined: true,
1119
+ body: bodyWithDecline(input.issue.body ?? "", input.why),
1120
+ section: declineSection(input.why),
1121
+ issue: input.issue.number,
1122
+ };
1123
+ }