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,547 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * finding-promotion CLI — turn a review finding into a spec criterion.
4
+ *
5
+ * Usage:
6
+ * bun scripts/finding-promotion.ts --issue 1678 \
7
+ * --spec specs/SPEC-TO-BOARD-PIPELINE-SPEC.md \
8
+ * --symbol promote --module lib/finding-promotion.ts \
9
+ * --outcome "a review finding that names real work becomes a criterion"
10
+ *
11
+ * …and add --write to append it. Without --write it prints and exits 0,
12
+ * having changed nothing.
13
+ *
14
+ * A spec keeping its criteria in more than one section also needs
15
+ * --section, and the line goes after that section's last criterion;
16
+ * without it the run refuses SECTION_REQUIRED and lists the sections
17
+ * (#2110). Name a section by its heading, by its path of parent headings
18
+ * ("Feature A > Success Criteria") when the heading text repeats, or by its
19
+ * heading line ("line 7802"); a name matching several is SECTION_AMBIGUOUS.
20
+ *
21
+ * The OTHER outcome — this finding serves no criterion, deliberately:
22
+ *
23
+ * bun scripts/finding-promotion.ts --issue 1934 \
24
+ * --declines "a worktree tidy-up; no criterion is made true or false" --write
25
+ *
26
+ * which writes the phrase `scripts/board-snapshot.ts` reads, interpolated
27
+ * from the constant rather than retyped. It refuses when the board can
28
+ * already see a criterion on the issue, so the declaration is an OUTCOME of
29
+ * the router and not a self-declaration — #1940.
30
+ *
31
+ * `--outcome` and `--symbol` are the caller's judgement and this script does
32
+ * not supply them — see the docblock of `lib/finding-promotion.ts` for why
33
+ * there is no `--auto` that sweeps the backlog. `--declines` is the same
34
+ * kind of input for the same reason.
35
+ *
36
+ * Thin CLI consumer — all logic lives in lib/finding-promotion.ts.
37
+ */
38
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
39
+ import { tmpdir } from "os";
40
+ import { join, relative, sep } from "path";
41
+
42
+ import {
43
+ bankForRetry,
44
+ bankWithPromotion,
45
+ decline,
46
+ placementCount,
47
+ promote,
48
+ specPath,
49
+ specWithCriterion,
50
+ type PromotableIssue,
51
+ withCriterionLinked,
52
+ } from "../lib/finding-promotion";
53
+ import { readScRegistry } from "./sync-sc-status";
54
+ import { currentScOwner } from "../lib/sc-reservations";
55
+ import { ghWithoutGhToken } from "../lib/live-issues";
56
+ import { skipLine } from "../lib/derived-spec";
57
+ import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
58
+
59
+ /** Routed through one constant so a test can prove the refusal is observed. */
60
+ export const PROMOTION_EXIT = 1;
61
+
62
+ const args = process.argv.slice(2);
63
+
64
+ /**
65
+ * What argv says about one flag — FOUR states, enumerated, never collapsed.
66
+ *
67
+ * The reader used to return `string | undefined` and folded two different
68
+ * facts into that `undefined`: the flag is **absent**, and the flag is the
69
+ * **last token in argv** so `args[idx + 1]` does not exist. `optional()`
70
+ * read both as "the caller did not pass it" and took the default, so
71
+ * `--project-root` with the path typo'd away resolved ROOT to
72
+ * `node_modules/rungate` — #363, reintroduced silently through the guard
73
+ * added to prevent it.
74
+ *
75
+ * Rounds 2 through 4 of this pull request each repaired one FLAG, and every
76
+ * one of them handed the parser the same SHAPE of input ("the value is the
77
+ * next flag"). The defect sat on the axis nobody varied —
78
+ * `.claude/rules/checks-must-be-able-to-fail.md`, the seventh shape. So the
79
+ * states are enumerated here, in the reader, where no caller can drop one:
80
+ * the union is exhaustive, and a `switch` that omits a case does not
81
+ * compile.
82
+ */
83
+ type FlagReading =
84
+ | { kind: "absent" }
85
+ | { kind: "novalue" }
86
+ | { kind: "nextflag"; value: string }
87
+ | { kind: "value"; value: string };
88
+
89
+ function readFlag(name: string): FlagReading {
90
+ const idx = args.indexOf(`--${name}`);
91
+ if (idx === -1) return { kind: "absent" };
92
+ if (idx + 1 >= args.length) return { kind: "novalue" };
93
+ const value = args[idx + 1]!;
94
+ return value.startsWith("--") ? { kind: "nextflag", value } : { kind: "value", value };
95
+ }
96
+
97
+ /**
98
+ * The refusal every present-but-valueless flag gets, by name. ONE binding,
99
+ * so both ways of passing no value produce the same outcome and differ only
100
+ * in the sentence that says which it was.
101
+ */
102
+ function refuseNoValue(name: string, reading: { kind: "novalue" } | { kind: "nextflag"; value: string }): never {
103
+ const detail =
104
+ reading.kind === "nextflag"
105
+ ? `was given '${reading.value}', which is the next flag`
106
+ : "was the last argument and was given no value at all";
107
+ console.error(
108
+ `ERROR: --${name} ${detail}. Its value is missing, and continuing would run ` +
109
+ "against a value nobody passed.",
110
+ );
111
+ process.exit(PROMOTION_EXIT);
112
+ }
113
+
114
+ /** An OPTIONAL flag: absent is fine, present-with-no-value is not. */
115
+ function optional(name: string): string | undefined {
116
+ const reading = readFlag(name);
117
+ switch (reading.kind) {
118
+ case "absent":
119
+ return undefined;
120
+ case "value":
121
+ return reading.value;
122
+ default:
123
+ refuseNoValue(name, reading);
124
+ }
125
+ }
126
+
127
+ /**
128
+ * A required flag's value, refused by NAME in all three ways it can be
129
+ * unusable: absent, last-with-no-value, and "its value is the next flag".
130
+ */
131
+ function required(name: string): string {
132
+ const reading = readFlag(name);
133
+ switch (reading.kind) {
134
+ case "absent":
135
+ console.error(`ERROR: --${name} is required`);
136
+ process.exit(PROMOTION_EXIT);
137
+ case "value":
138
+ return reading.value;
139
+ default:
140
+ refuseNoValue(name, reading);
141
+ }
142
+ }
143
+
144
+ /**
145
+ * The tree this run reads and writes — the CALLER's, never this script's.
146
+ *
147
+ * It was `join(import.meta.dir, "..")`, which is correct for `bun
148
+ * scripts/finding-promotion.ts` in this repository and wrong for every
149
+ * consumer: under `bunx rungate finding-promotion` that is
150
+ * `node_modules/rungate`, so `--spec specs/MY-SPEC.md` resolved inside the
151
+ * installed package. The consumer's spec sits right there and the command
152
+ * refuses SPEC_ABSENT; worse, a spec whose basename collides with one of
153
+ * rungate's own would have been APPENDED TO inside `node_modules`, printing
154
+ * "Appended to …" for a criterion the next install deletes. That is #363
155
+ * exactly, which `lib/cli-commands.ts` spends its first eighty lines
156
+ * warning about — reintroduced by registering a script that had never
157
+ * needed the flag because nothing could reach it.
158
+ *
159
+ * `bin/rungate.ts` appends `--project-root <cwd>` whenever the registry
160
+ * entry sets `projectRootFlag` and the caller did not pass one, so the
161
+ * default below is only reached by a direct `bun scripts/…` invocation.
162
+ */
163
+ const ROOT = optional("project-root") ?? join(import.meta.dir, "..");
164
+
165
+ /** A required flag that must be a positive integer, refused by name. */
166
+ function requiredPositiveInt(name: string): number {
167
+ const raw = required(name);
168
+ const n = Number(raw);
169
+ if (!Number.isInteger(n) || n <= 0) {
170
+ // Without this, `Number("abc")` is NaN, `String(NaN)` is "NaN", and the
171
+ // failure arrives as `gh`'s own error about issue #NaN — a downstream
172
+ // message about a tracker lookup, for what is a typo in an argument.
173
+ console.error(`ERROR: --${name} must be a positive integer, got '${raw}'`);
174
+ process.exit(PROMOTION_EXIT);
175
+ }
176
+ return n;
177
+ }
178
+
179
+ const issueNumber = requiredPositiveInt("issue");
180
+
181
+ /**
182
+ * Which outcome of the router this run is.
183
+ *
184
+ * Presence, not value — `--declines --write` must refuse by NAME rather than
185
+ * decline with the reason `"--write"`, which is what reading the value to
186
+ * decide the mode would do. `required` is what names it, and it is the same
187
+ * one binding every other flag goes through.
188
+ */
189
+ const declining = args.includes("--declines");
190
+ const declineWhy = declining ? required("declines") : "";
191
+
192
+ // The two modes are exclusive, and silence here was a real hazard: `--spec`,
193
+ // `--outcome`, `--symbol` and `--module` are read ONLY when `declining` is
194
+ // false, so a command line carrying both took the decline path and ignored
195
+ // four flags the caller passed. A half-edited copy-paste produces exactly
196
+ // that, and the result is indistinguishable from a deliberate decline.
197
+ if (declining) {
198
+ const promoteOnly = ["spec", "outcome", "symbol", "module", "group", "phase", "section"].filter(f => args.includes(`--${f}`));
199
+ if (promoteOnly.length > 0) {
200
+ console.error(
201
+ `ERROR: --declines cannot be combined with ${promoteOnly.map(f => `--${f}`).join(", ")}. ` +
202
+ "Promoting a finding into a criterion and declaring that it serves none are opposite " +
203
+ "outcomes; this command line asks for both and the promote flags would be ignored.",
204
+ );
205
+ process.exit(PROMOTION_EXIT);
206
+ }
207
+ }
208
+
209
+ const spec = declining ? "" : required("spec");
210
+ const outcome = declining ? "" : required("outcome");
211
+ const symbol = declining ? "" : required("symbol");
212
+ const module = declining ? "" : required("module");
213
+ const write = args.includes("--write");
214
+ // #2066: the letter group for a grouped id family, and the Phase row to place
215
+ // the id in. Both optional here; `promote` and `specWithCriterion` refuse by
216
+ // name when the spec needs one.
217
+ const group = declining ? undefined : optional("group");
218
+ // #2110: the heading a criterion goes under, when the spec keeps its criteria
219
+ // under more than one. `specWithCriterion` refuses by name when it is needed.
220
+ const section = declining ? undefined : optional("section");
221
+ const phaseRaw = declining ? undefined : optional("phase");
222
+ const phase = phaseRaw === undefined ? null : Number(phaseRaw);
223
+ if (phase !== null && (!Number.isInteger(phase) || phase < 0)) {
224
+ console.error(`ERROR: --phase must be a phase number, got '${phaseRaw}'`);
225
+ process.exit(PROMOTION_EXIT);
226
+ }
227
+
228
+ // The issue's own text decides ALREADY_SERVES, so a title typed by hand here
229
+ // would let a promotion through that the board can see is a second criterion
230
+ // for one piece of work. Read it from the tracker.
231
+ // `ghWithoutGhToken`, not a second spawn here. It DELETES the key rather
232
+ // than blanking it — `{ ...process.env, GH_TOKEN: "" }` leaves it present,
233
+ // which is the gotcha that helper exists to hold, and a second copy of this
234
+ // decision is a second place for it to be got wrong.
235
+ const issue: PromotableIssue = (() => {
236
+ try {
237
+ return JSON.parse(
238
+ ghWithoutGhToken(["issue", "view", String(issueNumber), "--json", "number,title,body"]),
239
+ ) as PromotableIssue;
240
+ } catch (e) {
241
+ console.error(`ERROR: could not read #${issueNumber} from the tracker`);
242
+ console.error(e instanceof Error ? e.message : String(e));
243
+ process.exit(PROMOTION_EXIT);
244
+ }
245
+ })();
246
+
247
+ if (declining) {
248
+ const declined = decline({ issue, why: declineWhy, projectRoot: ROOT });
249
+ if (!declined.declined) {
250
+ console.error(`REFUSED ${declined.refusal}: ${declined.why}`);
251
+ process.exit(PROMOTION_EXIT);
252
+ }
253
+ console.log(declined.body);
254
+
255
+ if (!write) {
256
+ console.log(`\n(dry run — nothing written. Add --write to apply it to #${issueNumber}.)`);
257
+ process.exit(0);
258
+ }
259
+
260
+ // RE-READ before writing. The body above came from a snapshot taken
261
+ // before the refusal checks ran, and `gh issue edit --body-file`
262
+ // overwrites the WHOLE body — so a comment-free edit by anybody else in
263
+ // that window is silently destroyed. The promote path already does this:
264
+ // `writeSpec` re-reads the target and runs its own guard against those
265
+ // bytes rather than the ones the caller validated.
266
+ //
267
+ // Re-validating too, not just re-reading: the fresh body is what the
268
+ // decline is being written into, so ALREADY_DECLINED and the heading
269
+ // readings have to be taken against it. A re-read that skipped them
270
+ // would answer a different question from the one that was asked.
271
+ let fresh: PromotableIssue;
272
+ try {
273
+ fresh = JSON.parse(
274
+ ghWithoutGhToken(["issue", "view", String(issueNumber), "--json", "number,title,body"]),
275
+ ) as PromotableIssue;
276
+ } catch (e) {
277
+ console.error(`REFUSED: #${issueNumber} could not be re-read before the write`);
278
+ console.error(e instanceof Error ? e.message : String(e));
279
+ process.exit(PROMOTION_EXIT);
280
+ }
281
+
282
+ const recheck = decline({ issue: fresh, why: declineWhy, projectRoot: ROOT });
283
+ if (!recheck.declined) {
284
+ console.error(
285
+ `REFUSED ${recheck.refusal}: #${issueNumber} changed between the check and the write. ` +
286
+ recheck.why,
287
+ );
288
+ process.exit(PROMOTION_EXIT);
289
+ }
290
+
291
+ // Through a file, because the body is markdown with newlines and headings
292
+ // in it and an argv round-trip through a shell is where that gets eaten.
293
+ //
294
+ // The two failure modes are reported apart. One `catch` over both said
295
+ // "could not be updated on the tracker" for a local disk error too, which
296
+ // sends the reader to GitHub for a problem on their own filesystem.
297
+ // Bound out here: narrowing from the `recheck.declined` guard above does
298
+ // not reach inside the closure below, and the alternative — re-asserting
299
+ // the discriminant in there — is a second place for the two to disagree.
300
+ const declinedBody = recheck.body;
301
+
302
+ const scratch = mkdtempSync(join(tmpdir(), "rg-1940-decline-"));
303
+ const bodyFile = join(scratch, "body.md");
304
+
305
+ /**
306
+ * The guarded region RETURNS its failure. It never exits.
307
+ *
308
+ * `process.exit()` does not unwind the stack, so a `finally` wrapped
309
+ * around a block that exits from inside it never runs — both error paths
310
+ * here left the mkdtemp directory, and the rendered issue body inside it,
311
+ * on disk. Found on #1956.
312
+ *
313
+ * The fix is the shape, not the two call sites: with no exit anywhere in
314
+ * the region there is no second place for one to reappear, and
315
+ * `test/finding-promotion.test.ts` asserts the region stays exit-free
316
+ * rather than asserting these two lines in particular.
317
+ */
318
+ function writeAndEdit(): string[] | null {
319
+ try {
320
+ writeFileSync(bodyFile, declinedBody);
321
+ } catch (e) {
322
+ return [
323
+ `REFUSED: could not write the new body to ${bodyFile} — this is a LOCAL`,
324
+ `failure, not a tracker one. #${issueNumber} was not touched.`,
325
+ e instanceof Error ? e.message : String(e),
326
+ ];
327
+ }
328
+ try {
329
+ ghWithoutGhToken(["issue", "edit", String(issueNumber), "--body-file", bodyFile]);
330
+ } catch (e) {
331
+ return [
332
+ `REFUSED: #${issueNumber} could not be updated on the tracker`,
333
+ e instanceof Error ? e.message : String(e),
334
+ ];
335
+ }
336
+ return null;
337
+ }
338
+
339
+ let failure: string[] | null;
340
+ try {
341
+ failure = writeAndEdit();
342
+ } finally {
343
+ rmSync(scratch, { recursive: true, force: true });
344
+ }
345
+
346
+ if (failure) {
347
+ for (const line of failure) console.error(line);
348
+ process.exit(PROMOTION_EXIT);
349
+ }
350
+
351
+ console.log(`#${issueNumber} now declares it serves no criterion.`);
352
+ console.log("board-snapshot reads it as a deliberate decline rather than a blank cell.");
353
+ process.exit(0);
354
+ }
355
+
356
+ const result = promote(
357
+ { issue, spec, outcome, symbol, module, projectRoot: ROOT, owner: currentScOwner(ROOT), group: group ?? null },
358
+ readScRegistry(),
359
+ );
360
+
361
+ if (!result.promoted) {
362
+ console.error(`REFUSED ${result.refusal}: ${result.why}`);
363
+ process.exit(PROMOTION_EXIT);
364
+ }
365
+
366
+ console.log(result.line);
367
+ for (const gap of result.unmeasured) console.log(` UNMEASURED: ${gap}`);
368
+
369
+ // `specPath` from the lib, not a second `join` here. They disagreed on an
370
+ // absolute --spec, so the file the guard validated and the file this wrote
371
+ // were different files.
372
+ const target = specPath({ spec, projectRoot: ROOT });
373
+
374
+ // Guarded, like BOTH reads of this same file in lib/finding-promotion.ts.
375
+ // The first version left this one bare — the third of three reads, the two
376
+ // named in review repaired and the sibling left, which is the same two-of-
377
+ // three the statement fields were.
378
+ let content: string;
379
+ try {
380
+ content = readFileSync(target, "utf8");
381
+ } catch (e) {
382
+ console.error(`REFUSED SPEC_UNREADABLE: ${spec} could not be read: ${e instanceof Error ? e.message : String(e)}`);
383
+ process.exit(PROMOTION_EXIT);
384
+ }
385
+
386
+ // #1286, the same refusal create-sc makes: appending to a spec a generator
387
+ // owns writes a criterion that disappears at the next regeneration, having
388
+ // consumed an id nothing then declares. One decider, called from both CLIs.
389
+ //
390
+ // BEFORE the dry-run exit, not after. A preview that reports success for a
391
+ // run that would immediately refuse is not a preview — it is a second
392
+ // answer to "will this work", given by a path that never asked the question.
393
+ const early = maySpecBeWritten(content);
394
+ if (!early.allowed) {
395
+ console.error(skipLine(target, early.reading));
396
+ process.exit(PROMOTION_EXIT);
397
+ }
398
+
399
+ // #2066: where the line goes, its phase, and the deferral bank — all decided
400
+ // BEFORE the dry-run exit, for the reason `maySpecBeWritten` is: a preview
401
+ // that succeeds where the write would refuse is a second answer.
402
+ const inserted = specWithCriterion(content, result.line, result.id, phase, section ?? null);
403
+ if (!inserted.ok) {
404
+ console.error(`REFUSED ${inserted.refusal}: ${inserted.why}`);
405
+ process.exit(PROMOTION_EXIT);
406
+ }
407
+ // A literal, so the spec-write sweep (#1584) can see this write targets the
408
+ // bank and not a spec. `test/finding-promotion.test.ts` holds it equal to
409
+ // `DEFERRAL_BANK`, the constant board-snapshot reads the bank from.
410
+ const DEFERRAL_BANK = ".claude/spec-deferral-ratchet.json";
411
+ const bankPath = join(ROOT, ".claude/spec-deferral-ratchet.json");
412
+ // The bank is keyed by the spec's path inside the project, never by however
413
+ // --spec was spelled (`./specs/X.md`, an absolute path): review of #2105.
414
+ const specKey = relative(ROOT, target).split(sep).join("/");
415
+ const counts = { before: placementCount(content), after: placementCount(inserted.text) };
416
+ let bankText: string | null = null;
417
+ // A new criterion moves the bank from its old count; a RETRY (the line is
418
+ // already written) checks it, and repairs it when an earlier run's bank
419
+ // write failed after its spec write landed (review of #2105).
420
+ const moved = counts.after.criteria !== counts.before.criteria;
421
+ if (counts.before.deferred && (moved || result.alreadyWritten)) {
422
+ let current: string;
423
+ try {
424
+ current = readFileSync(bankPath, "utf8");
425
+ } catch (e) {
426
+ console.error(`REFUSED BANK_DRIFT: ${spec} is deferred and ${DEFERRAL_BANK} could not be read: ${(e as Error).message}`);
427
+ process.exit(PROMOTION_EXIT);
428
+ }
429
+ const banked = moved
430
+ ? bankWithPromotion(current, specKey, counts.before.criteria, counts.after.criteria)
431
+ : bankForRetry(current, specKey, counts.after.criteria);
432
+ if (!banked.ok) {
433
+ console.error(`REFUSED ${banked.refusal}: ${banked.why}`);
434
+ process.exit(PROMOTION_EXIT);
435
+ }
436
+ bankText = banked.text;
437
+ }
438
+
439
+ if (!write) {
440
+ const where = phase === null ? "" : `, placed in Phase ${phase}`;
441
+ const bank = bankText === null ? "" : `, and ${DEFERRAL_BANK} moves to ${counts.after.criteria}`;
442
+ console.log(`\n(dry run — nothing written. Add --write to add it to ${spec}${where}${bank}.)`);
443
+ process.exit(0);
444
+ }
445
+
446
+ // KEEP the result. `writeSpec` re-reads the target and runs its own
447
+ // `mayWrite` against those bytes, so it can refuse after the early
448
+ // `maySpecBeWritten(content)` above passed — the file changed between the
449
+ // two reads, which is the concurrent-session window
450
+ // `.claude/rules/parallel-sessions.md` is about. Discarding it prints
451
+ // "Appended to …" for a write that did not happen, and a false success is
452
+ // the one report this repository exists to stop producing.
453
+ //
454
+ // 18 of the 22 `writeSpec` callers in this tree discard it, `create-sc.ts`
455
+ // among them. That population is out of this pull request's scope and is
456
+ // filed separately rather than fixed here.
457
+ // A retry after a failed link: the line is already there, so write nothing
458
+ // and go straight to the link (review of #2065).
459
+ if (result.alreadyWritten) {
460
+ console.log(`${spec} already states ${result.id}; not appending it again.`);
461
+ // A retry may still carry a placement the first run did not make. Write it,
462
+ // or --phase is computed and dropped while the run reports success
463
+ // (review of #2105).
464
+ if (inserted.text !== content) {
465
+ const placedOnly = writeSpec(target, inserted.text);
466
+ if (!placedOnly.written) {
467
+ console.error(`REFUSED: ${placedOnly.refusal ?? `${spec} was not written, and gave no reason`}`);
468
+ process.exit(PROMOTION_EXIT);
469
+ }
470
+ console.log(`Placed ${result.id} in Phase ${phase}.`);
471
+ }
472
+ } else {
473
+ const wrote = writeSpec(target, inserted.text);
474
+ if (!wrote.written) {
475
+ console.error(`REFUSED: ${wrote.refusal ?? `${spec} was not written, and gave no reason`}`);
476
+ process.exit(PROMOTION_EXIT);
477
+ }
478
+ console.log(`Added to ${spec}${phase === null ? "" : ` (Phase ${phase})`}: ${result.line}`);
479
+ console.log(` owner: ${currentScOwner(ROOT) ?? "(none — allocated above every reserved block)"}`);
480
+ }
481
+
482
+ // #2066: the bank moves in the same run as the spec, or `spec-placement`
483
+ // reads the deferred spec as disagreeing with it. The spec is already
484
+ // written, so a failure here names exactly what is left.
485
+ if (bankText !== null) {
486
+ // Through `writeSpec`, the one write path the spec-write sweep (#1552)
487
+ // allows for a file whose path matches /spec/i. The bank is JSON and
488
+ // carries no generated-file marker, so `writeSpec` writes it as authored.
489
+ let banked: { written: boolean; refusal: string | null };
490
+ try {
491
+ banked = writeSpec(bankPath, bankText);
492
+ } catch (e) {
493
+ banked = { written: false, refusal: (e as Error).message };
494
+ }
495
+ if (!banked.written) {
496
+ console.error(
497
+ `REFUSED: ${spec} now states ${result.id}, and ${DEFERRAL_BANK} could not be written (${banked.refusal ?? "no reason given"}). ` +
498
+ `Set ${specKey}'s count there to ${counts.after.criteria}.`,
499
+ );
500
+ process.exit(PROMOTION_EXIT);
501
+ }
502
+ console.log(`${DEFERRAL_BANK}: ${specKey} now ${counts.after.criteria} criteria.`);
503
+ }
504
+
505
+ // #2060: link the issue here rather than printing an instruction to do it.
506
+ // Re-read first, for the reason the decline path does: `--body-file`
507
+ // overwrites the whole body, and an edit made since the first read would be
508
+ // lost. The spec is already written, so a failure here says exactly what is
509
+ // left to do and exits non-zero.
510
+ // Bound out here: the `result.promoted` narrowing above does not reach
511
+ // inside the closure below.
512
+ const promotedId = result.id;
513
+ function linkIssue(): string | null {
514
+ let fresh: PromotableIssue;
515
+ try {
516
+ fresh = JSON.parse(
517
+ ghWithoutGhToken(["issue", "view", String(issueNumber), "--json", "number,title,body"]),
518
+ ) as PromotableIssue;
519
+ } catch (e) {
520
+ return `#${issueNumber} could not be re-read: ${e instanceof Error ? e.message : String(e)}`;
521
+ }
522
+ const before = fresh.body ?? "";
523
+ const link = withCriterionLinked(before, promotedId);
524
+ if (!link.linked) return link.why;
525
+ if (link.body === before) return null;
526
+ const linkScratch = mkdtempSync(join(tmpdir(), "rg-2060-link-"));
527
+ try {
528
+ const linkFile = join(linkScratch, "body.md");
529
+ writeFileSync(linkFile, link.body);
530
+ ghWithoutGhToken(["issue", "edit", String(issueNumber), "--body-file", linkFile]);
531
+ return null;
532
+ } catch (e) {
533
+ return `#${issueNumber} could not be updated: ${e instanceof Error ? e.message : String(e)}`;
534
+ } finally {
535
+ rmSync(linkScratch, { recursive: true, force: true });
536
+ }
537
+ }
538
+
539
+ const linkFailure = linkIssue();
540
+ if (linkFailure) {
541
+ console.error(
542
+ `REFUSED: ${spec} now states ${promotedId}, and the issue link failed — ${linkFailure}. ` +
543
+ `Add "${promotedId}" under #${issueNumber}'s "## Criteria this serves" heading.`,
544
+ );
545
+ process.exit(PROMOTION_EXIT);
546
+ }
547
+ console.log(`#${issueNumber} names ${promotedId} under its Criteria heading.`);
@@ -263,7 +263,7 @@ generator: rungate/scripts/generate-code-map.ts
263
263
 
264
264
  # Code Map — ${pkg.name}
265
265
 
266
- Auto-generated architecture snapshot. Re-run \`bun generate-code-map.ts ${projectPath}\` to refresh.
266
+ Auto-generated architecture snapshot. Re-run \`bun generate-code-map.ts .\` to refresh.
267
267
  Regenerate when src/ has commits since scanned-at-sha.
268
268
 
269
269
  ${FRESHNESS_NOTICE}`);