rungate 0.8.28 → 0.8.29

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.
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- 545e0acc9e8aaebb75f5345bedfc501cbc22cbbef652611467898dcd4736a772
1
+ fa34c4041cab9c794b569ed4daed02557ad6f40c70974e16108c7011328b5ce0
@@ -24,6 +24,7 @@
24
24
  * two that only a live fork or a line outside a hunk would otherwise produce.
25
25
  */
26
26
  import type { ThreadReading } from "./ai-review-rounds";
27
+ import { nextCursor } from "./graphql-cursor";
27
28
  import { escapeAnnotation, reviewThreadRequests, threadKeyFrom } from "./scaffold/ai-review-findings";
28
29
  import type { AiReviewFindingsReading, AiReviewThreadRequest } from "./scaffold/ai-review-findings";
29
30
 
@@ -549,3 +550,108 @@ export function threadsDetailLines(result: AiReviewThreadsResult, command: strin
549
550
  export function aiReviewThreadsExitCode(result: AiReviewThreadsResult): number {
550
551
  return result.outcome === "FAILED" ? AI_REVIEW_THREADS_REFUSAL : 0;
551
552
  }
553
+
554
+ /**
555
+ * #2306 — CRC-C3's clearing half. *A false positive clears by closing the
556
+ * thread with a short reason.* A thread the review opened and somebody
557
+ * resolved with no reply reads exactly like one nobody read: the merge is
558
+ * unblocked and the record says nothing (`reference/clearing-a-false-positive.md`,
559
+ * *What this procedure refuses*). So each review round names those threads on
560
+ * the pull request.
561
+ *
562
+ * It runs on the NEXT round, because GitHub offers no workflow event for a
563
+ * thread being resolved. A thread resolved after the last push is reported
564
+ * only if another push follows — a nudge with a known blind spot, not a gate.
565
+ */
566
+ export const UNREASONED_MARKER = "rungate:unreasoned-resolution:v1";
567
+
568
+ /** One thread resolved with no stated reason. */
569
+ export interface UnreasonedResolution {
570
+ id: string;
571
+ path: string | null;
572
+ /** The opening comment's link, when GitHub returned one. */
573
+ url: string | null;
574
+ }
575
+
576
+ export type UnreasonedReading =
577
+ | { status: "MEASURED"; unreasoned: UnreasonedResolution[] }
578
+ | { status: "UNMEASURED"; reason: string };
579
+
580
+ /** `{ author: { login }, body, url }`, asserted field by field. */
581
+ function commentOf(c: unknown): { login: string | null; body: string; url: string | null } | null {
582
+ if (c === null || typeof c !== "object") return null;
583
+ const o = c as { author?: unknown; body?: unknown; url?: unknown };
584
+ const author = o.author !== null && typeof o.author === "object" ? (o.author as { login?: unknown }).login : null;
585
+ return {
586
+ login: typeof author === "string" ? author : null,
587
+ body: typeof o.body === "string" ? o.body : "",
588
+ url: typeof o.url === "string" ? o.url : null,
589
+ };
590
+ }
591
+
592
+ /**
593
+ * The resolved threads that carry no reason.
594
+ *
595
+ * A thread counts only if it is resolved (the literal `true`, as in
596
+ * `threadReading`), its FIRST comment carries the finding-key marker — so it
597
+ * is the review's thread, not a person's — and no later comment is a reason.
598
+ * A reason is a non-blank reply by anybody other than the thread's opener: the
599
+ * bot answering itself is not somebody stating why the finding was cleared.
600
+ *
601
+ * A node that cannot be read is skipped, as `threadReading` skips it; a list
602
+ * that could not be read at all is UNMEASURED, never "none".
603
+ */
604
+ export function unreasonedResolutions(raw: readonly unknown[] | null | undefined, reason: string): UnreasonedReading {
605
+ if (raw === null || raw === undefined) return { status: "UNMEASURED", reason };
606
+ const unreasoned: UnreasonedResolution[] = [];
607
+ for (const t of raw) {
608
+ if (t === null || typeof t !== "object") continue;
609
+ const node = t as { id?: unknown; isResolved?: unknown; path?: unknown; comments?: unknown };
610
+ if (node.isResolved !== true || typeof node.id !== "string") continue;
611
+ const nodes =
612
+ node.comments !== null && typeof node.comments === "object"
613
+ ? (node.comments as { nodes?: unknown }).nodes
614
+ : undefined;
615
+ if (!Array.isArray(nodes) || nodes.length === 0) continue;
616
+ // Review of #2378: a thread whose comments were not read to their end —
617
+ // a second page, or a page that cannot say — may hold its reason past
618
+ // what was read. It is not reported: under-reporting is the safe
619
+ // direction for a record. `nextCursor` is the one reader (SC-2721).
620
+ if (nextCursor((node.comments as { pageInfo?: unknown }).pageInfo).kind !== "done") continue;
621
+ const first = commentOf(nodes[0]);
622
+ if (first === null || threadKeyFrom(first.body) === null) continue;
623
+ const answered = nodes
624
+ .slice(1)
625
+ .map(commentOf)
626
+ .some(c => c !== null && c.login !== first.login && c.body.trim() !== "");
627
+ if (answered) continue;
628
+ unreasoned.push({ id: node.id, path: typeof node.path === "string" ? node.path : null, url: first.url });
629
+ }
630
+ return { status: "MEASURED", unreasoned };
631
+ }
632
+
633
+ /**
634
+ * The conversation comment naming every unreasoned thread no earlier report
635
+ * named, or `null` when there is nothing new. Each thread carries its own
636
+ * marker, so a later round reports only threads resolved since.
637
+ */
638
+ export function unreasonedReport(list: readonly UnreasonedResolution[], existing: readonly string[]): string | null {
639
+ const reported = (id: string) => existing.some(b => b.includes(`<!-- ${UNREASONED_MARKER} ${id} -->`));
640
+ const fresh = list.filter(u => !reported(u.id));
641
+ if (fresh.length === 0) return null;
642
+ const lines = fresh.map(u => {
643
+ const where = u.path === null ? "a thread on the pull request" : `\`${u.path}\``;
644
+ return u.url === null ? `- ${where}` : `- ${where} — ${u.url}`;
645
+ });
646
+ return [
647
+ `**${fresh.length === 1 ? "A review thread was" : `${fresh.length} review threads were`} resolved with no stated reason** (CRC-C3).`,
648
+ "",
649
+ "The AI review opened these and they were resolved with no reply. A resolved thread with no reason reads " +
650
+ "the same as one nobody read. Reply in each thread with the reason, in one or two sentences naming the " +
651
+ "evidence. The procedure is `reference/clearing-a-false-positive.md`.",
652
+ "",
653
+ ...lines,
654
+ "",
655
+ ...fresh.map(u => `<!-- ${UNREASONED_MARKER} ${u.id} -->`),
656
+ ].join("\n");
657
+ }
@@ -44,7 +44,8 @@
44
44
  * unrelated reason is distinguishable from one genuinely caught.
45
45
  */
46
46
  import { existsSync, readFileSync } from "fs";
47
- import { resolve, sep } from "path";
47
+ import { join, resolve, sep } from "path";
48
+ import { writeSpec, type SpecWriteResult } from "./write-spec";
48
49
 
49
50
  import { NAMES_NONE, answerableIds, criteriaNamedBy, criterionAnswer, specCriteriaIn } from "./board-mirror";
50
51
  import { allocateScNumber, formatSCLine } from "./create-sc";
@@ -831,8 +832,40 @@ export function bankAfterAppend(
831
832
  return bankWithPromotion(bankText, specPath, was.criteria, now.criteria);
832
833
  }
833
834
 
835
+ /**
836
+ * The ONE write of the deferral bank (#2300). `finding-promotion`,
837
+ * `create-sc` and the scaffold's spec-scope step all move it through here.
838
+ *
839
+ * Two reasons it is one function. Write accountability (#624) resolves the
840
+ * literal path below to the bank, so a writer that goes through it needs no
841
+ * entry of its own, and one that writes around it is a new site and goes red.
842
+ * And `read`, the bank text the caller computed from, makes the write refuse
843
+ * when another session moved the bank in between, instead of dropping that
844
+ * move and leaving it for `BANK_DRIFT` to find later.
845
+ */
846
+ export function writeDeferralBank(root: string, text: string, read: string | null): SpecWriteResult {
847
+ // A named literal path: write accountability reads `writeSpec(<identifier>`
848
+ // back to its assignment, and that is how it resolves this write to the bank.
849
+ const bankPath = join(root, ".claude/spec-deferral-ratchet.json");
850
+ return writeSpec(bankPath, text, {
851
+ label: ".claude/spec-deferral-ratchet.json",
852
+ expected: read,
853
+ });
854
+ }
855
+
834
856
  /** The writer `writeSpecWithBank` writes through: `writeSpec`, or a stand-in in a test. */
835
- export type SpecWriter = (path: string, content: string) => { written: boolean; refusal?: string | null };
857
+ export type SpecWriter = (
858
+ path: string,
859
+ content: string,
860
+ /**
861
+ * #2300: the bytes the write expects to replace. The forward spec write
862
+ * expects the spec as read; the put-back expects the spec as this run wrote
863
+ * it, so a revert refuses rather than erase a write another session landed
864
+ * on top in between (review of #2381). Absent for the bank, whose writer
865
+ * already holds the bank it read.
866
+ */
867
+ expected?: string,
868
+ ) => { written: boolean; refusal?: string | null };
836
869
 
837
870
  /**
838
871
  * Write the spec and then the bank, both or neither (review of #2298).
@@ -849,12 +882,12 @@ export function writeSpecWithBank(
849
882
  spec: { path: string; before: string; after: string },
850
883
  bank: { path: string; text: string | null },
851
884
  ): { ok: true } | { ok: false; why: string; restored: boolean } {
852
- const specWrite = write(spec.path, spec.after);
885
+ const specWrite = write(spec.path, spec.after, spec.before);
853
886
  if (!specWrite.written) return { ok: false, why: `the spec was not written (${specWrite.refusal ?? "no reason given"})`, restored: true };
854
887
  if (bank.text === null) return { ok: true };
855
888
  const bankWrite = write(bank.path, bank.text);
856
889
  if (bankWrite.written) return { ok: true };
857
- const undo = write(spec.path, spec.before);
890
+ const undo = write(spec.path, spec.before, spec.after);
858
891
  return {
859
892
  ok: false,
860
893
  why: `the deferral bank could not be written (${bankWrite.refusal ?? "no reason given"})`,
@@ -868,5 +868,73 @@ make the problem go away it is upstream, and if it would not it is yours.
868
868
  `,
869
869
  });
870
870
 
871
+ // #2375: the claim convention `sync-sc-status` enforces, in consumer
872
+ // wording. rungate's own `.claude/rules/claiming-sc-coverage.md` carries
873
+ // the incident history and is hand-maintained; this one carries the forms.
874
+ // Its examples are run through `commentClaimForm` and `titleCall` by
875
+ // test/gen-agents-md.test.ts, so a form it promises is a form the scanner
876
+ // honours. Path-scoped, so it loads when a test or spec is touched and costs
877
+ // nothing on the always-loaded surface. Every profile: a minimal consumer
878
+ // runs `sync-sc-status` too.
879
+ rules.push({
880
+ filename: "claiming-sc-coverage.md",
881
+ content: `---
882
+ description: Which mention of a criterion id in a test is a claim that ticks it, and which is only a citation
883
+ paths:
884
+ - "test/**"
885
+ - "tests/**"
886
+ - "**/*.test.*"
887
+ - "**/*.spec.*"
888
+ - "specs/**"
889
+ ---
890
+
891
+ ## A test claims a criterion from a declaring position, and nowhere else
892
+
893
+ \`rungate sync-sc-status\` ticks a spec's \`- [ ] SC-N\` when a passing test
894
+ claims \`SC-N\`. It decides what a claim is by WHERE the id sits, not by what
895
+ the words around it mean. So put an id in one of these positions only when
896
+ the test proves the whole criterion.
897
+
898
+ Counts as a claim — the criterion is ticked once the test passes:
899
+
900
+ | Position | Example |
901
+ |---|---|
902
+ | a \`describe\`/\`test\`/\`it\` title that runs | \`describe("SC-9012: the export is complete", () => {})\` |
903
+ | a coverage verb before the id | \`// covers SC-9012\` |
904
+ | a label: ids, then a colon | \`// SC-9012: the export is complete\` |
905
+ | an issue heading with a label | \`// #81 / SC-9012: the export is complete\` |
906
+ | the id opening a comment line | \`// SC-9012 and SC-9013 (EXPORT-SPEC.md)\` |
907
+ | a \`SPEC-REF:\` line | \`// SPEC-REF: EXPORT-SPEC.md (SC-9012)\` |
908
+ | a parenthetical holding only ids | \`// the export is complete (SC-9012).\` |
909
+
910
+ Does not count — write it one of these ways when the test only works toward
911
+ a criterion:
912
+
913
+ | Position | Example |
914
+ |---|---|
915
+ | the id mid-sentence in a comment | \`// part of the work toward SC-9012\` |
916
+ | the issue number in the title instead of the id | \`describe("#81: the export writes its header", () => {})\` |
917
+ | a title that never runs | \`test.todo("SC-9012: the export is complete")\` |
918
+
919
+ ## A test that works toward a criterion
920
+
921
+ A criterion with open issues left is not done, and the tick tool cannot see
922
+ your tracker. If a test covers one piece of the work, name the piece's issue
923
+ number in its title and leave the criterion's id out of every declaring
924
+ position until the last piece lands. Then the test that proves the whole of
925
+ it carries the id, and \`sync-sc-status --only SC-N\` ticks it.
926
+
927
+ Run \`sync-sc-status --dry-run\` first: it lists every criterion it would tick,
928
+ so a test that claims more than it proves shows up before anything is written.
929
+
930
+ ## The direction this is allowed to be wrong in
931
+
932
+ Toward not crediting. A claim written in a form the scanner does not know
933
+ costs an unticked checkbox, which one \`// covers SC-N\` line fixes. The other
934
+ direction ticks a criterion nothing proves, and nobody looks at a ticked box
935
+ again.
936
+ `,
937
+ });
938
+
871
939
  return rules;
872
940
  }
@@ -56,6 +56,13 @@ export interface DecompositionRow {
56
56
  * as another row's outcome in THIS plan, resolved after every row is read.
57
57
  */
58
58
  blockedBy: string[];
59
+ /**
60
+ * #2339: existing issues (`#<n>` only) that must wait on THIS row — the
61
+ * optional sixth column, so a later plan can order an earlier plan's issues
62
+ * behind its own work. Always set by the parser, `[]` when the table has no
63
+ * Blocks column; optional only so a hand-built row need not spell it.
64
+ */
65
+ blocks?: string[];
59
66
  /** 1-indexed line of the row, for a message somebody can act on. */
60
67
  line: number;
61
68
  }
@@ -71,6 +78,9 @@ export interface DecompositionReading {
71
78
  /** The header the table must open with, so another table is never read as one. */
72
79
  const HEADER = /^\|\s*Criterion\s*\|\s*Outcome\s*\|\s*Files\s*\|/;
73
80
 
81
+ /** An existing issue, as a cell names one. */
82
+ const ISSUE_REF = /^#\d+$/;
83
+
74
84
  /**
75
85
  * Split a row on its UNESCAPED pipes, and turn `\|` back into `|`.
76
86
  *
@@ -176,13 +186,23 @@ function blockingCycles(
176
186
  rows: readonly DecompositionRow[],
177
187
  byOutcome: ReadonlyMap<string, number>,
178
188
  ): string[][] {
189
+ // #2339: an existing issue IS a node once a row can block it. A row that
190
+ // waits on #77 and also blocks #77 closes a ring through the tracker that
191
+ // this file can see without reading it; edges already on the tracker are
192
+ // still out of view.
179
193
  const blockers = new Map<string, string[]>();
180
194
  for (const r of rows) {
181
195
  blockers.set(
182
196
  r.outcome,
183
- r.blockedBy.filter(b => !/^#\d+$/.test(b) && byOutcome.has(b)),
197
+ r.blockedBy.filter(b => ISSUE_REF.test(b) || byOutcome.has(b)),
184
198
  );
185
199
  }
200
+ for (const r of rows) {
201
+ for (const n of r.blocks ?? []) {
202
+ if (!ISSUE_REF.test(n)) continue;
203
+ blockers.set(n, [...(blockers.get(n) ?? []), r.outcome]);
204
+ }
205
+ }
186
206
 
187
207
  const found: string[][] = [];
188
208
  const reported = new Set<string>();
@@ -211,7 +231,7 @@ function blockingCycles(
211
231
  done.add(node);
212
232
  };
213
233
 
214
- for (const r of rows) if (!done.has(r.outcome)) walk(r.outcome);
234
+ for (const node of blockers.keys()) if (!done.has(node)) walk(node);
215
235
  return found;
216
236
  }
217
237
 
@@ -230,6 +250,13 @@ export function parseDecompositionPlan(content: string): DecompositionReading {
230
250
  };
231
251
  }
232
252
 
253
+ // #2339: an optional sixth column, Blocks, read only when the header names
254
+ // it. Every row is then held to six cells, so a five-cell row is refused
255
+ // rather than read as "blocks nothing" — the same reason `!== 5` refuses.
256
+ const head = rowCells(lines[start]);
257
+ const withBlocks = head.length === 6 && plain(head[5]).toLowerCase() === "blocks";
258
+ const width = withBlocks ? 6 : 5;
259
+
233
260
  const rows: DecompositionRow[] = [];
234
261
  const rejected: { line: number; text: string; why: string }[] = [];
235
262
  for (let i = start + 1; i < lines.length; i++) {
@@ -244,10 +271,10 @@ export function parseDecompositionPlan(content: string): DecompositionReading {
244
271
  // the tool creates one, which is this module's cardinal failure arriving
245
272
  // through whitespace an editor inserts. Found by the AI review of this
246
273
  // change.
247
- let width = 0;
274
+ let indent = 0;
248
275
  let pos = 0;
249
276
  for (; pos < lines[i].length && (lines[i][pos] === " " || lines[i][pos] === "\t"); pos++) {
250
- width += lines[i][pos] === "\t" ? 4 : 1;
277
+ indent += lines[i][pos] === "\t" ? 4 : 1;
251
278
  }
252
279
  const line = lines[i].slice(pos);
253
280
  // A table ends at a blank line or an indented code block — NOT at a row
@@ -257,22 +284,23 @@ export function parseDecompositionPlan(content: string): DecompositionReading {
257
284
  // leading pipe. Anything else non-blank is now READ and refused on its
258
285
  // cell count, because a loud refusal is recoverable and a silent drop is
259
286
  // the failure this module exists to prevent.
260
- if (width >= 4 || line.trim() === "") break;
287
+ if (indent >= 4 || line.trim() === "") break;
261
288
  if (/^\|[\s|:-]+\|$/.test(line)) continue;
262
289
  const c = rowCells(line);
263
290
  const at = i + 1;
264
291
  const reject = (why: string): void => {
265
292
  rejected.push({ line: at, text: line.slice(0, 70), why });
266
293
  };
267
- // Exactly five. `< 5` let a row with a leaked `|` — an unescaped pipe in
268
- // an outcome or a blocked-by — through, and only c[0]..c[4] are ever
269
- // read, so its tail was silently truncated. That is the one thing this
270
- // module promises not to do. Found by the AI review of this change.
271
- if (c.length !== 5) {
294
+ // Exactly the header's width — five, or six with a Blocks column (#2339).
295
+ // `< 5` let a row with a leaked `|` — an unescaped pipe in an outcome or
296
+ // a blocked-by — through, and only the first `width` cells are ever read,
297
+ // so its tail was silently truncated. That is the one thing this module
298
+ // promises not to do. Found by the AI review of this change.
299
+ if (c.length !== width) {
272
300
  reject(
273
- c.length < 5
274
- ? `only ${c.length} cells, need 5`
275
- : `${c.length} cells, need 5 — an unescaped \`|\` in a cell splits the row, and the ` +
301
+ c.length < width
302
+ ? `only ${c.length} cells, need ${width}`
303
+ : `${c.length} cells, need ${width} — an unescaped \`|\` in a cell splits the row, and the ` +
276
304
  `extra cells would be dropped without this refusal; write it as \`\\|\``,
277
305
  );
278
306
  continue;
@@ -329,6 +357,7 @@ export function parseDecompositionPlan(content: string): DecompositionReading {
329
357
  files,
330
358
  milestone: m === "" || m === "—" || m === "-" ? null : m,
331
359
  blockedBy: cells(c[4]),
360
+ blocks: withBlocks ? cells(c[5]) : [],
332
361
  line: at,
333
362
  });
334
363
  }
@@ -355,7 +384,7 @@ export function parseDecompositionPlan(content: string): DecompositionReading {
355
384
  // satisfied.
356
385
  for (const r of rows) {
357
386
  for (const b of r.blockedBy) {
358
- if (/^#\d+$/.test(b)) continue;
387
+ if (ISSUE_REF.test(b)) continue;
359
388
  if (byOutcome.has(b)) continue;
360
389
  reasons.push(
361
390
  `line ${r.line}: blocked by "${b}", which is neither #<issue> nor the outcome of another row`,
@@ -363,6 +392,19 @@ export function parseDecompositionPlan(content: string): DecompositionReading {
363
392
  }
364
393
  }
365
394
 
395
+ // #2339: Blocks names existing issues only. Two rows of one plan are
396
+ // ordered by Blocked by on the row that waits; a second spelling of the same
397
+ // edge would be a second decider for one fact.
398
+ for (const r of rows) {
399
+ for (const b of r.blocks ?? []) {
400
+ if (ISSUE_REF.test(b)) continue;
401
+ reasons.push(
402
+ `line ${r.line}: blocks "${b}" — the Blocks column takes #<issue> only; to order two rows ` +
403
+ `of this plan, write it as Blocked by on the row that waits`,
404
+ );
405
+ }
406
+ }
407
+
366
408
  // Then cycles, over the edges that resolved above. A plan that creates a
367
409
  // ring of issues each waiting on the next produces work that is on the
368
410
  // board, correctly linked, and permanently unstartable — which is worse
@@ -376,9 +418,9 @@ export function parseDecompositionPlan(content: string): DecompositionReading {
376
418
  );
377
419
  continue;
378
420
  }
379
- const chain = [...cycle, cycle[0]].map(o => `"${o}"`).join(" <- ");
421
+ const chain = [...cycle, cycle[0]].map(o => (ISSUE_REF.test(o) ? o : `"${o}"`)).join(" <- ");
380
422
  reasons.push(
381
- `lines ${cycle.map(o => byOutcome.get(o)).join(", ")}: a blocking CYCLE, ${chain} ` +
423
+ `lines ${cycle.filter(o => byOutcome.has(o)).map(o => byOutcome.get(o)).join(", ")}: a blocking CYCLE, ${chain} ` +
382
424
  `(<- reads "is blocked by") — none of these issues could ever start`,
383
425
  );
384
426
  }
@@ -408,6 +450,12 @@ export interface LiveTracker {
408
450
  milestones: Set<string>;
409
451
  /** Every criterion id a spec under `specs/` states. A row naming any other is refused (SC-2738). */
410
452
  statedCriteria: ReadonlySet<string>;
453
+ /**
454
+ * #2339: the state of each `#<n>` the plan names, as the tracker holds it.
455
+ * A number absent here is not an issue in the repository (or is a pull
456
+ * request), and the row naming it is refused by that number.
457
+ */
458
+ namedIssues: ReadonlyMap<number, "open" | "closed">;
411
459
  }
412
460
 
413
461
  export type DecomposeAction =
@@ -491,6 +539,26 @@ export function planDecomposition(
491
539
  }
492
540
  }
493
541
 
542
+ // #2339: every #<n> must be an issue the tracker holds. A closed one may be
543
+ // waited on — a row whose title only a closed issue holds resolves the same
544
+ // way (SC-2738) — but it cannot be made to wait: it is finished.
545
+ for (const r of rows) {
546
+ for (const b of r.blockedBy) {
547
+ if (ISSUE_REF.test(b) && !live.namedIssues.has(Number(b.slice(1)))) {
548
+ reasons.push(`line ${r.line}: blocked by ${b}, which is not an issue in this repository`);
549
+ }
550
+ }
551
+ for (const b of r.blocks ?? []) {
552
+ if (!ISSUE_REF.test(b)) continue;
553
+ const state = live.namedIssues.get(Number(b.slice(1)));
554
+ if (state === undefined) {
555
+ reasons.push(`line ${r.line}: blocks ${b}, which is not an issue in this repository`);
556
+ } else if (state === "closed") {
557
+ reasons.push(`line ${r.line}: blocks ${b}, which is closed — a finished issue cannot wait on a new row`);
558
+ }
559
+ }
560
+ }
561
+
494
562
  const actions: DecomposeAction[] = [];
495
563
  for (const r of rows) {
496
564
  const existing = live.openTitles.get(r.outcome);
@@ -514,6 +582,7 @@ export function planDecomposition(
514
582
  const edges: { blocked: string; blocker: string }[] = [];
515
583
  for (const r of rows) {
516
584
  for (const b of r.blockedBy) edges.push({ blocked: r.outcome, blocker: b });
585
+ for (const b of r.blocks ?? []) edges.push({ blocked: b, blocker: r.outcome });
517
586
  }
518
587
 
519
588
  return {
@@ -0,0 +1,176 @@
1
+ /**
2
+ * `.github/workflows/consumer-intake.yml`, generated — SC-2784, ADR-020
3
+ * Decision 2.
4
+ *
5
+ * A consumer's issue gets its triage verdict with no command typed by hand:
6
+ * when it is opened, when it is labelled `from-consumer`, and once a day, so
7
+ * an issue whose event was missed is triaged within a day. The work is
8
+ * `rungate consumer-triage --write` (SC-2782), the one decider.
9
+ *
10
+ * ## An outside reporter's label is put back first
11
+ *
12
+ * GitHub silently drops the labels on a new issue whose author has no push
13
+ * access, so `--label from-consumer` never arrives from a real outside
14
+ * consumer. On `opened`, an issue whose author association is not one the
15
+ * triage trusts (`TRUSTED_ASSOCIATIONS`, the same list that decides whose
16
+ * marker counts) is given the label before the triage reads the tracker. A
17
+ * label written with the job's own token fires no further run, so this run
18
+ * is the one that triages it.
19
+ *
20
+ * ## The daily run catches an `opened` run that never happened (#2379)
21
+ *
22
+ * The triage reads only labelled issues, so an outside reporter's issue whose
23
+ * `opened` run was missed would never be triaged. The schedule therefore
24
+ * labels open issues from the last `CONSUMER_INTAKE_SWEEP_DAYS` by an author
25
+ * outside the trusted set that carry no label yet. The window is the board's
26
+ * grace period, and keeping it short means a label a maintainer took off an
27
+ * older issue on purpose is not put back. Issues filed before this workflow
28
+ * existed are labelled by hand, once.
29
+ *
30
+ * The window is computed inside the `--jq` filter (`now - seconds | todate`),
31
+ * not with `date -d`: that is GNU-only, and `ci.runner` may name a macOS or
32
+ * self-hosted runner (review of #2380). gh carries its own jq, so the filter
33
+ * runs wherever gh does.
34
+ *
35
+ * ## It calls the published CLI
36
+ *
37
+ * Like every generated workflow it runs `bunx rungate@<version>`, so
38
+ * `consumer-triage` must be in a published release before this file is
39
+ * (`docs/guides/RELEASING.md`).
40
+ */
41
+
42
+ import { CONSUMER_LABEL, TRUSTED_ASSOCIATIONS } from "../consumer-triage";
43
+
44
+ /** The file this module generates, under `.github/workflows/`. */
45
+ export const CONSUMER_INTAKE_WORKFLOW_FILE = "consumer-intake.yml";
46
+
47
+ /** The one job in it. */
48
+ export const CONSUMER_INTAKE_JOB = "triage";
49
+
50
+ /** Every command the job calls. Each must be registered in `lib/cli-commands.ts`. */
51
+ export const CONSUMER_INTAKE_COMMANDS = ["consumer-triage"] as const;
52
+
53
+ /** Its own group, never cancelling: each run re-reads the whole tracker. */
54
+ export const CONSUMER_INTAKE_GROUP = "consumer-intake";
55
+
56
+ /**
57
+ * How far back the daily run looks for a missed outside reporter's issue. It
58
+ * equals `CONSUMER_INTAKE_GRACE_MS` in scripts/board-conformance.ts, which
59
+ * test/intake-triage-workflow.test.ts asserts: an issue the board would call
60
+ * overdue is one this run had a day to label.
61
+ */
62
+ export const CONSUMER_INTAKE_SWEEP_DAYS = 2;
63
+
64
+ /** Once a day, off the hour so it does not queue behind every other scheduled job. */
65
+ export const CONSUMER_INTAKE_CRON = "17 6 * * *";
66
+
67
+ export interface ConsumerIntakeWorkflowOptions {
68
+ /** The `runs-on:` value, already JSON-quoted by the caller. */
69
+ runsOn: string;
70
+ /** The pinned `actions/checkout` reference. */
71
+ checkout: string;
72
+ /** The pinned `oven-sh/setup-bun` reference. */
73
+ setupBun: string;
74
+ /** The `with:` body of that step, at ten spaces — the project's single bun declaration (#622). */
75
+ setupBunWith: string;
76
+ /** The step's `env:` block, from `setupBunEnv` (#2039). */
77
+ setupBunEnv: string;
78
+ /** The published harness version every step runs through `bunx`. */
79
+ version: string;
80
+ }
81
+
82
+ /**
83
+ * The daily sweep's \`--jq\` filter over a page of open issues: recent, not a
84
+ * pull request, an author outside the trusted set, and not labelled yet. Its
85
+ * window is computed in jq, not by \`date -d\`, which is GNU-only (review of
86
+ * #2380). Exported so a test runs it through \`jq\`.
87
+ */
88
+ export const SWEEP_FILTER =
89
+ `.[] | select(.pull_request == null) | select(.created_at >= (now - ${CONSUMER_INTAKE_SWEEP_DAYS * 86400} | todate)) | ` +
90
+ `select(.author_association as $a | env.TRUSTED | fromjson | index($a) | not) | ` +
91
+ `select([.labels[].name] | index("${CONSUMER_LABEL}") | not) | .number`;
92
+
93
+ /**
94
+ * Over an issue's events: whether anyone took the label off. A label a person
95
+ * removed is a decision, and the sweep does not reverse it (review of #2380).
96
+ */
97
+ export const REMOVED_FILTER = `.[] | select(.event == "unlabeled" and .label.name == "${CONSUMER_LABEL}") | .id`;
98
+
99
+ /** The whole `consumer-intake.yml` body. */
100
+ export function buildConsumerIntakeWorkflow(opts: ConsumerIntakeWorkflowOptions): string {
101
+ const cli = `bunx rungate@${opts.version}`;
102
+ const trusted = JSON.stringify(TRUSTED_ASSOCIATIONS);
103
+ return `# Managed by rungate — do not edit the generated job.
104
+ #
105
+ # SC-2784 (ADR-020 Decision 2): a consumer's issue is triaged when it is filed
106
+ # or labelled ${CONSUMER_LABEL}, and every day, by consumer-triage --write.
107
+ # An outside reporter's new issue is given ${CONSUMER_LABEL} first, because
108
+ # GitHub drops the labels an author without push access sets.
109
+ name: Consumer issues — give each one a triage verdict
110
+
111
+ on:
112
+ issues:
113
+ types: [opened, labeled]
114
+ schedule:
115
+ - cron: "${CONSUMER_INTAKE_CRON}"
116
+
117
+ permissions:
118
+ contents: read
119
+ # Milestones, labels and the verdict comment.
120
+ issues: write
121
+ # The triage reads open pull requests for shared files.
122
+ pull-requests: read
123
+
124
+ concurrency:
125
+ group: ${CONSUMER_INTAKE_GROUP}
126
+ cancel-in-progress: false
127
+
128
+ jobs:
129
+ ${CONSUMER_INTAKE_JOB}:
130
+ if: \${{ github.event_name == 'schedule' || github.event.action == 'opened' || (github.event.action == 'labeled' && github.event.label.name == '${CONSUMER_LABEL}') }}
131
+ runs-on: ${opts.runsOn}
132
+ steps:
133
+ - name: Give an outside reporter's issue the ${CONSUMER_LABEL} label
134
+ if: \${{ !contains(fromJSON('${trusted}'), github.event.issue.author_association) && github.event.action == 'opened' }}
135
+ env:
136
+ GH_TOKEN: \${{ github.token }}
137
+ NUMBER: \${{ github.event.issue.number }}
138
+ run: gh issue edit "$NUMBER" --repo "$GITHUB_REPOSITORY" --add-label ${CONSUMER_LABEL}
139
+
140
+ - name: Give an outside reporter's recent issue the ${CONSUMER_LABEL} label, if its opened run was missed
141
+ if: \${{ github.event_name == 'schedule' }}
142
+ # A failed sweep is shown, and the triage below still runs on the
143
+ # issues that already carry the label (review of #2380).
144
+ continue-on-error: true
145
+ env:
146
+ GH_TOKEN: \${{ github.token }}
147
+ TRUSTED: '${trusted}'
148
+ run: |
149
+ # An unspecified run shell is \`bash -e\` with no pipefail, so a failed
150
+ # read would end in a clean exit with nothing labelled.
151
+ set -o pipefail
152
+ gh api --paginate "repos/$GITHUB_REPOSITORY/issues?state=open&per_page=100" --jq '${SWEEP_FILTER}' \\
153
+ | while read -r n; do
154
+ # A person took the label off: leave it off (review of #2380).
155
+ # An unreadable history labels nothing, rather than guessing.
156
+ removed="$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$n/events?per_page=100" --jq '${REMOVED_FILTER}')" \\
157
+ || { echo "::warning title=consumer-intake::could not read #$n's history; not labelled this run"; continue; }
158
+ if [ -n "$removed" ]; then
159
+ echo "#$n: ${CONSUMER_LABEL} was removed by hand, not put back"
160
+ continue
161
+ fi
162
+ gh issue edit "$n" --repo "$GITHUB_REPOSITORY" --add-label ${CONSUMER_LABEL} \\
163
+ || echo "::warning title=consumer-intake::could not label #$n; the next run tries again"
164
+ done
165
+
166
+ - uses: ${opts.checkout}
167
+ - uses: ${opts.setupBun}
168
+ with:
169
+ ${opts.setupBunWith}
170
+ ${opts.setupBunEnv}
171
+ - name: Triage every consumer issue that has no verdict
172
+ env:
173
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
174
+ run: ${cli} consumer-triage --repo "$GITHUB_REPOSITORY" --write
175
+ `;
176
+ }
@@ -230,6 +230,16 @@ export const OWNED_FILES: OwnedFile[] = [
230
230
  customize: "Opt specs in with a `board:` block; add jobs beside `run-the-engine`",
231
231
  avoid: "Don't edit `run-the-engine` or share adr-accepted's group",
232
232
  },
233
+ {
234
+ // SC-2784, ADR-020 Decision 2: a consumer's issue is triaged when filed
235
+ // and every day. A consumer has no scripts/, so the generator writes it
236
+ // and calls the published CLI.
237
+ path: ".github/workflows/consumer-intake.yml",
238
+ strategy: "job-preserving",
239
+ servedBy: "writeManagedFile (lib/scaffold/steps.ts) via mergeManagedWorkflow — the harness owns named jobs, not the file",
240
+ customize: "Add jobs beside `triage`",
241
+ avoid: "Don't edit `triage`",
242
+ },
233
243
  {
234
244
  // `regenerate` until #655, and the declaration was never consulted:
235
245
  // `generateAgentBriefsStep` called `writeFileSync` directly, so the row
@@ -30,6 +30,7 @@ import { readBoardInputs } from "../config-readers";
30
30
  import { isTemplateSpec } from "../sc-ids";
31
31
  import { boardDeclaration, placementReading } from "../spec-placement";
32
32
  import { maySpecBeWritten, writeSpec } from "../write-spec";
33
+ import { writeDeferralBank } from "../finding-promotion";
33
34
 
34
35
  /** The one line this step writes. */
35
36
  export const DEFERRED_LINE = "board: { scope: deferred }";
@@ -148,7 +149,17 @@ export function bankWithNewDeferrals(
148
149
  * declare a scope writes nothing and reports nothing.
149
150
  */
150
151
  /** The writer the step writes through: `writeSpec`, or a stand-in in a test. */
151
- export type ScopeWriter = (path: string, content: string) => { written: boolean; refusal?: string | null };
152
+ /**
153
+ * `expected` (#2300, review of #2381): the bytes a spec write expects to
154
+ * replace. The forward write expects the spec as planned from; the put-back
155
+ * expects the spec as this run wrote it, so neither erases a change another
156
+ * session landed in between. Absent for the bank, whose writer holds its read.
157
+ */
158
+ export type ScopeWriter = (
159
+ path: string,
160
+ content: string,
161
+ expected?: string,
162
+ ) => { written: boolean; refusal?: string | null };
152
163
 
153
164
  export function deferUndeclaredSpecs(root: string, actions: string[], writer?: ScopeWriter): void {
154
165
  if (!existsSync(join(root, "specs"))) return;
@@ -163,14 +174,16 @@ export function deferUndeclaredSpecs(root: string, actions: string[], writer?: S
163
174
  // A literal path, so the spec-write sweep (#1584) resolves this write to
164
175
  // the bank rather than reading an opaque target.
165
176
  const bankPath = join(root, ".claude/spec-deferral-ratchet.json");
166
- const banked = bankWithNewDeferrals(existsSync(bankPath) ? readFileSync(bankPath, "utf-8") : null, plan.writes);
177
+ const bankRead = existsSync(bankPath) ? readFileSync(bankPath, "utf-8") : null;
178
+ const banked = bankWithNewDeferrals(bankRead, plan.writes);
167
179
  if (!banked.ok) {
168
180
  actions.push(`REFUSED: spec board scopes (${banked.why}) — nothing was written`);
169
181
  return;
170
182
  }
171
- // Spelled `writeSpec(bankPath, …)` so write accountability (#624) resolves
172
- // the bank write to the bank, as create-sc's does.
173
- const write: ScopeWriter = writer ?? ((p, c) => (p === bankPath ? writeSpec(bankPath, c) : writeSpec(p, c)));
183
+ // #2300: the bank through its one write path, refusing a bank another
184
+ // session moved since `bankRead`.
185
+ const write: ScopeWriter =
186
+ writer ?? ((p, c, e) => (p === bankPath ? writeDeferralBank(root, c, bankRead) : writeSpec(p, c, { expected: e })));
174
187
 
175
188
  // All or nothing: a spec written without its bank row reddens SC-2734, so a
176
189
  // failed write puts back every spec already written.
@@ -182,7 +195,7 @@ export function deferUndeclaredSpecs(root: string, actions: string[], writer?: S
182
195
  // (review of #2335).
183
196
  const putBack = (w: ScopeWrite) => {
184
197
  try {
185
- return write(join(root, w.path), w.before).written;
198
+ return write(join(root, w.path), w.before, w.after).written;
186
199
  } catch {
187
200
  return false;
188
201
  }
@@ -200,7 +213,7 @@ export function deferUndeclaredSpecs(root: string, actions: string[], writer?: S
200
213
  try {
201
214
  mkdirSync(dirname(bankPath), { recursive: true });
202
215
  for (const w of plan.writes) {
203
- const r = write(join(root, w.path), w.after);
216
+ const r = write(join(root, w.path), w.after, w.before);
204
217
  if (!r.written) return undo(`${w.path} was not written: ${r.refusal ?? "no reason given"}`);
205
218
  written.push(w);
206
219
  }
@@ -50,6 +50,7 @@ import {
50
50
  } from "./ai-review-unmeasured-workflow";
51
51
  import { buildAdrAcceptedWorkflow } from "./adr-accepted-workflow";
52
52
  import { buildSpecsPlacedWorkflow } from "./specs-placed-workflow";
53
+ import { buildConsumerIntakeWorkflow } from "./consumer-intake-workflow";
53
54
  import { buildClosingReferencesWorkflow } from "./closing-references-workflow";
54
55
  import { buildIntakeWorkflow } from "./intake-workflow";
55
56
  import { buildBoardReadyWorkflow } from "./board-ready-workflow";
@@ -4517,6 +4518,17 @@ ${buildAuthDetectStep(vertex)}${buildReviewRunStep(
4517
4518
  version: harnessVersion(),
4518
4519
  });
4519
4520
 
4521
+ // SC-2784, ADR-020 Decision 2: a consumer's issue is triaged when it is
4522
+ // filed or labelled, and every day, through the published CLI.
4523
+ const consumerIntakeYml = buildConsumerIntakeWorkflow({
4524
+ runsOn,
4525
+ checkout: actionRef("actions/checkout"),
4526
+ setupBun: actionRef("oven-sh/setup-bun"),
4527
+ setupBunWith: bunStep,
4528
+ setupBunEnv: setupBunEnv(" "),
4529
+ version: harnessVersion(),
4530
+ });
4531
+
4520
4532
  // #2045, ADR-014 row 2: the closing-references check, generated so a
4521
4533
  // consumer gets ADR-013 rule 9 step 4 and this repository's copy is the
4522
4534
  // generated one. It calls the published CLI, at the generating version.
@@ -4580,7 +4592,7 @@ ${buildAuthDetectStep(vertex)}${buildReviewRunStep(
4580
4592
  // lib/conformity.ts reads back, and the two are held together by
4581
4593
  // test/ai-review-workflow.test.ts AC-1, which looks for the constant's
4582
4594
  // filename in what this loop actually wrote.
4583
- for (const [name, content] of [["ci.yml", ciYml], ["gates.yml", gatesYml], ["ai-review.yml", aiReviewYml], ["ai-review-unmeasured.yml", aiReviewUnmeasuredYml], ["adr-accepted.yml", adrAcceptedYml], ["closing-references.yml", closingReferencesYml], ["board-ready.yml", boardReadyYml], ["board-intake.yml", boardIntakeYml], ["intake.yml", intakeYml], ["specs-placed.yml", specsPlacedYml]] as const) {
4595
+ for (const [name, content] of [["ci.yml", ciYml], ["gates.yml", gatesYml], ["ai-review.yml", aiReviewYml], ["ai-review-unmeasured.yml", aiReviewUnmeasuredYml], ["adr-accepted.yml", adrAcceptedYml], ["closing-references.yml", closingReferencesYml], ["board-ready.yml", boardReadyYml], ["board-intake.yml", boardIntakeYml], ["intake.yml", intakeYml], ["specs-placed.yml", specsPlacedYml], ["consumer-intake.yml", consumerIntakeYml]] as const) {
4584
4596
  const label = `.github/workflows/${name}`;
4585
4597
  try {
4586
4598
  // Keyed by FILE, and the lookup is here because this loop is the only
package/lib/write-spec.ts CHANGED
@@ -61,6 +61,14 @@ export interface WriteSpecOptions {
61
61
  * matches the rest of their output.
62
62
  */
63
63
  label?: string;
64
+ /**
65
+ * #2300: the bytes the caller read and computed its new content from, or
66
+ * `null` when the file did not exist. When given, the write is refused if
67
+ * the file now holds anything else: another writer got there between the
68
+ * read and this write, and writing would drop its change silently. Absent
69
+ * (`undefined`) keeps the old behaviour for callers that read nothing.
70
+ */
71
+ expected?: string | null;
64
72
  }
65
73
 
66
74
  /**
@@ -77,14 +85,26 @@ export function writeSpec(
77
85
  content: string,
78
86
  opts?: WriteSpecOptions,
79
87
  ): SpecWriteResult {
80
- const reading: DerivedReading = existsSync(specPath)
81
- ? readDerivedDeclaration(readFileSync(specPath, "utf-8"))
82
- : { status: "authored" };
88
+ const current = existsSync(specPath) ? readFileSync(specPath, "utf-8") : null;
89
+ const reading: DerivedReading = current === null ? { status: "authored" } : readDerivedDeclaration(current);
83
90
 
84
91
  if (!mayWrite(reading)) {
85
92
  return { written: false, reading, refusal: skipLine(opts?.label ?? specPath, reading) };
86
93
  }
87
94
 
95
+ // #2300: a read-modify-write is only safe if nothing wrote in between.
96
+ if (opts?.expected !== undefined && current !== opts.expected) {
97
+ const what =
98
+ current === null ? "it no longer exists" : opts.expected === null ? "it was created since" : "its bytes differ";
99
+ return {
100
+ written: false,
101
+ reading,
102
+ refusal:
103
+ `${opts.label ?? specPath} changed on disk since it was read (${what}) — another writer got there first, ` +
104
+ `and this write would drop its change; re-run so the change is computed from what is there now`,
105
+ };
106
+ }
107
+
88
108
  writeFileSync(specPath, content);
89
109
  return { written: true, reading, refusal: null };
90
110
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rungate",
3
- "version": "0.8.28",
3
+ "version": "0.8.29",
4
4
  "type": "module",
5
5
  "description": "Ship harness — conformity tests, scaffold, and agent briefs for AI-first development",
6
6
  "repository": {
@@ -31,6 +31,7 @@
31
31
  * behavioural test could tell which of them was holding the gate up.
32
32
  */
33
33
  import { createGitHubClient } from "../lib/github";
34
+ import { nextCursor } from "../lib/graphql-cursor";
34
35
  import {
35
36
  AI_REVIEW_PR_IS_FORK_VAR,
36
37
  aiReviewThreadsExitCode,
@@ -39,6 +40,8 @@ import {
39
40
  refusalFrom,
40
41
  threadsDetailLines,
41
42
  threadsLandedPhrase,
43
+ unreasonedReport,
44
+ unreasonedResolutions,
42
45
  type AiReviewThreadPoster,
43
46
  type AiReviewPullCommenter,
44
47
  type AiReviewThreadResponse,
@@ -262,4 +265,61 @@ if (result.outcome === "FAILED") {
262
265
  );
263
266
  }
264
267
 
268
+ // #2306 — CRC-C3: a thread this review opened and somebody resolved with no
269
+ // reply is named on the conversation, once per thread. It never changes the
270
+ // exit code: the report is a record, and the round's outcome is above.
271
+ const THREADS_QUERY = `query($owner:String!,$name:String!,$pr:Int!,$after:String){
272
+ repository(owner:$owner,name:$name){ pullRequest(number:$pr){
273
+ reviewThreads(first:100, after:$after){ pageInfo{ hasNextPage endCursor }
274
+ nodes{ id isResolved path comments(first:100){ pageInfo{ hasNextPage } nodes{ author{ login } body url } } } } } } }`;
275
+ let threadNodes: unknown[] | null = null;
276
+ let threadsError = "the review threads were not read";
277
+ try {
278
+ const nodes: unknown[] = [];
279
+ for (let after: string | null = null; ; ) {
280
+ const page = (await client.graphql(THREADS_QUERY, {
281
+ owner: parsed.owner,
282
+ name: parsed.repo,
283
+ pr: parsed.pr,
284
+ after,
285
+ })) as {
286
+ repository?: { pullRequest?: { reviewThreads?: { nodes?: unknown[]; pageInfo?: unknown } } };
287
+ };
288
+ const conn = page.repository?.pullRequest?.reviewThreads;
289
+ if (!Array.isArray(conn?.nodes)) throw new Error("the response carried no review-thread list");
290
+ nodes.push(...conn.nodes);
291
+ // SC-2721: the one reader of "is there another page".
292
+ const next = nextCursor(conn.pageInfo);
293
+ if (next.kind === "done") break;
294
+ if (next.kind === "unreadable") throw new Error(next.why);
295
+ after = next.cursor;
296
+ }
297
+ threadNodes = nodes;
298
+ } catch (e) {
299
+ threadsError = `the review threads could not be read (${escapeAnnotation((e as Error).message)})`;
300
+ }
301
+ const unreasoned = unreasonedResolutions(threadNodes, threadsError);
302
+ if (unreasoned.status === "UNMEASURED") {
303
+ console.log(`${COMMAND}: UNMEASURED — ${unreasoned.reason}, so a thread resolved with no reason is not reported this round`);
304
+ } else if (unreasoned.unreasoned.length === 0) {
305
+ console.log(`${COMMAND}: no review thread is resolved without a stated reason`);
306
+ } else if (comment === undefined) {
307
+ console.log(
308
+ `${COMMAND}: ${unreasoned.unreasoned.length} thread(s) resolved with no stated reason, and the conversation ` +
309
+ `could not be read, so they are not reported this round`,
310
+ );
311
+ } else {
312
+ const report = unreasonedReport(unreasoned.unreasoned, comment.existing);
313
+ if (report === null) {
314
+ console.log(`${COMMAND}: ${unreasoned.unreasoned.length} thread(s) resolved with no stated reason, all reported already`);
315
+ } else {
316
+ const sent = await comment.post(report);
317
+ console.log(
318
+ sent.ok
319
+ ? `${COMMAND}: reported thread(s) resolved with no stated reason on the conversation`
320
+ : `${COMMAND}: could not report thread(s) resolved with no stated reason: ${escapeAnnotation(sent.message)}`,
321
+ );
322
+ }
323
+ }
324
+
265
325
  process.exit(aiReviewThreadsExitCode(result));
@@ -24,7 +24,7 @@ import { readDerivedDeclaration } from "../lib/derived-spec";
24
24
  import { isTemplateSpec } from "../lib/sc-ids";
25
25
  import { parseCriteria } from "../lib/spec-evidence";
26
26
  import { boardDeclaration, onboardingHint, parsePlacementRows, tracksOnBoard, type OnboardingHint } from "../lib/spec-placement";
27
- import { claimedScKeys, scopedKey } from "./sync-sc-status";
27
+ import { authoredSpecs, claimedScKeys, scopedKey } from "./sync-sc-status";
28
28
 
29
29
  /** The one exit code every refusal routes through. */
30
30
  export const REFUSE_EXIT = 1;
@@ -73,8 +73,11 @@ export function boardScope(root: string, only?: string): { specs: SpecScope[] }
73
73
 
74
74
  const texts = new Map(sweep.paths.map(p => [p, readFileSync(join(root, p), "utf-8")]));
75
75
  const declaredBy = new Map<string, string[]>();
76
- for (const [p, text] of texts) {
77
- for (const c of parseCriteria(text)) declaredBy.set(c.id, [...(declaredBy.get(c.id) ?? []), p]);
76
+ // #2333: a generated copy states its source's ids without authoring them,
77
+ // so it is left out here exactly as the credit rule leaves it out.
78
+ const authored = authoredSpecs([...texts].map(([p, content]) => ({ p, content })));
79
+ for (const { p, content } of authored) {
80
+ for (const c of parseCriteria(content)) declaredBy.set(c.id, [...(declaredBy.get(c.id) ?? []), p]);
78
81
  }
79
82
  const claimed = claimedScKeys(join(root, "specs"), join(root, "test"));
80
83
 
@@ -27,7 +27,7 @@ import { currentScOwner } from "../lib/sc-reservations";
27
27
  import { skipLine } from "../lib/derived-spec";
28
28
  import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
29
29
  import { join, relative, resolve, sep } from "path";
30
- import { bankAfterAppend, writeSpecWithBank } from "../lib/finding-promotion";
30
+ import { bankAfterAppend, writeDeferralBank, writeSpecWithBank } from "../lib/finding-promotion";
31
31
 
32
32
  /** Same resolution sync-sc-status uses, so both halves read one tree. */
33
33
  const ROOT = join(import.meta.dir, "..");
@@ -134,7 +134,8 @@ try {
134
134
  // (#1584) can see this write targets the bank and not a spec.
135
135
  const bankPath = join(ROOT, ".claude/spec-deferral-ratchet.json");
136
136
  const specKey = relative(ROOT, resolve(specPath)).split(sep).join("/");
137
- const banked = bankAfterAppend(existsSync(bankPath) ? readFileSync(bankPath, "utf-8") : null, specKey, content, newContent);
137
+ const bankRead = existsSync(bankPath) ? readFileSync(bankPath, "utf-8") : null;
138
+ const banked = bankAfterAppend(bankRead, specKey, content, newContent);
138
139
  if (!banked.ok) {
139
140
  console.error(`ERROR: ${banked.refusal}: ${banked.why}`);
140
141
  process.exit(1);
@@ -142,11 +143,12 @@ try {
142
143
  // Both through `writeSpec`, as finding-promotion does: the one write path
143
144
  // the spec-write sweep (#1552) allows for a path matching /spec/i. Both
144
145
  // or neither: a failed bank write puts the spec back.
145
- // The bank write is spelled `writeSpec(bankPath, …)` so write
146
- // accountability (#624) resolves it to the bank, as it does
147
- // finding-promotion's, rather than reading an opaque `writeSpec(p)`.
146
+ // #2300: the bank through its one write path, refusing if another session
147
+ // moved it since `bankRead`. Each spec write carries the bytes it expects
148
+ // to replace, which `writeSpecWithBank` supplies, so neither the write nor
149
+ // its put-back can erase another session's change.
148
150
  const wrote = writeSpecWithBank(
149
- (p, c) => (p === bankPath ? writeSpec(bankPath, c) : writeSpec(p, c)),
151
+ (p, c, e) => (p === bankPath ? writeDeferralBank(ROOT, c, bankRead) : writeSpec(p, c, { expected: e })),
150
152
  { path: specPath, before: content, after: newContent },
151
153
  { path: bankPath, text: banked.text },
152
154
  );
@@ -43,6 +43,7 @@ import {
43
43
  bankForRetry,
44
44
  bankWithPromotion,
45
45
  decline,
46
+ writeDeferralBank,
46
47
  placementCount,
47
48
  promote,
48
49
  specPath,
@@ -414,6 +415,9 @@ const bankPath = join(ROOT, ".claude/spec-deferral-ratchet.json");
414
415
  const specKey = relative(ROOT, target).split(sep).join("/");
415
416
  const counts = { before: placementCount(content), after: placementCount(inserted.text) };
416
417
  let bankText: string | null = null;
418
+ // #2300: the bank bytes `bankText` was computed from, so its write refuses
419
+ // if another session moved the bank in between.
420
+ let bankRead: string | null = null;
417
421
  // A new criterion moves the bank from its old count; a RETRY (the line is
418
422
  // already written) checks it, and repairs it when an earlier run's bank
419
423
  // write failed after its spec write landed (review of #2105).
@@ -434,6 +438,7 @@ if (counts.before.deferred && (moved || result.alreadyWritten)) {
434
438
  process.exit(PROMOTION_EXIT);
435
439
  }
436
440
  bankText = banked.text;
441
+ bankRead = current;
437
442
  }
438
443
 
439
444
  if (!write) {
@@ -462,7 +467,7 @@ if (result.alreadyWritten) {
462
467
  // or --phase is computed and dropped while the run reports success
463
468
  // (review of #2105).
464
469
  if (inserted.text !== content) {
465
- const placedOnly = writeSpec(target, inserted.text);
470
+ const placedOnly = writeSpec(target, inserted.text, { expected: content });
466
471
  if (!placedOnly.written) {
467
472
  console.error(`REFUSED: ${placedOnly.refusal ?? `${spec} was not written, and gave no reason`}`);
468
473
  process.exit(PROMOTION_EXIT);
@@ -470,7 +475,7 @@ if (result.alreadyWritten) {
470
475
  console.log(`Placed ${result.id} in Phase ${phase}.`);
471
476
  }
472
477
  } else {
473
- const wrote = writeSpec(target, inserted.text);
478
+ const wrote = writeSpec(target, inserted.text, { expected: content });
474
479
  if (!wrote.written) {
475
480
  console.error(`REFUSED: ${wrote.refusal ?? `${spec} was not written, and gave no reason`}`);
476
481
  process.exit(PROMOTION_EXIT);
@@ -483,12 +488,11 @@ if (result.alreadyWritten) {
483
488
  // reads the deferred spec as disagreeing with it. The spec is already
484
489
  // written, so a failure here names exactly what is left.
485
490
  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.
491
+ // Through `writeDeferralBank`, the bank's one write path (#2300), which
492
+ // writes through `writeSpec` and refuses a bank moved since `bankRead`.
489
493
  let banked: { written: boolean; refusal: string | null };
490
494
  try {
491
- banked = writeSpec(bankPath, bankText);
495
+ banked = writeDeferralBank(ROOT, bankText, bankRead);
492
496
  } catch (e) {
493
497
  banked = { written: false, refusal: (e as Error).message };
494
498
  }
@@ -254,6 +254,12 @@ export interface DecomposeGitHub {
254
254
  * safe half and one unsafe one. See the edge pass in `decompose`.
255
255
  */
256
256
  blockedBy: (repo: string, issue: number) => Promise<number[]>;
257
+ /**
258
+ * #2339: the state of each issue a plan names by `#<n>`. A number that is
259
+ * not an issue — never existed, deleted, or a pull request — is absent from
260
+ * the map; any other failed read throws, and the run refuses UNMEASURED.
261
+ */
262
+ issueStates: (repo: string, numbers: readonly number[]) => Promise<Map<number, "open" | "closed">>;
257
263
  }
258
264
 
259
265
  function issueTitles(repo: string, state: "open" | "closed"): Map<string, number> {
@@ -349,6 +355,30 @@ const LIVE_DECOMPOSE: DecomposeGitHub = {
349
355
  if (!Number.isInteger(n) || n <= 0) throw new Error(`created, but could not read a number from: ${url}`);
350
356
  return n;
351
357
  },
358
+ issueStates: async (repo, numbers) => {
359
+ const out = new Map<number, "open" | "closed">();
360
+ for (const n of numbers) {
361
+ let raw: string;
362
+ try {
363
+ raw = gh([
364
+ // single resource: one issue by its number, not a list — there is no second page.
365
+ "api",
366
+ `repos/${repo}/issues/${n}`,
367
+ "--jq",
368
+ "[.state, (.pull_request != null)] | @json",
369
+ ]);
370
+ } catch (e) {
371
+ // Absent (404) and deleted (410) both mean "not an issue here"; a
372
+ // rate limit or a network error is not an answer and must throw.
373
+ if (/HTTP 404|HTTP 410|Not Found/i.test((e as Error).message)) continue;
374
+ throw e;
375
+ }
376
+ const [state, isPull] = JSON.parse(raw) as [string, boolean];
377
+ if (isPull) continue;
378
+ out.set(n, state === "closed" ? "closed" : "open");
379
+ }
380
+ return out;
381
+ },
352
382
  addBlockedBy: async (repo, blocked, blocker) => {
353
383
  // REST, not `issue edit --add-blocked-by`, which an older runner's gh lacks (#2345).
354
384
  addBlockers(repo, blocked, [blocker], args => gh([...args]), BLOCKER_IDS);
@@ -500,6 +530,15 @@ async function decompose(
500
530
  // column, not absent.
501
531
  const statedCriteria = new Set(answerableIds(sweep));
502
532
 
533
+ // #2339: only the numbers this plan names, and only when it names any.
534
+ const named = [
535
+ ...new Set(
536
+ reading.rows
537
+ .flatMap(r => [...r.blockedBy, ...(r.blocks ?? [])])
538
+ .filter(b => /^#\d+$/.test(b))
539
+ .map(b => Number(b.slice(1))),
540
+ ),
541
+ ];
503
542
  let live;
504
543
  try {
505
544
  live = {
@@ -507,6 +546,7 @@ async function decompose(
507
546
  closedTitles: await api.closedTitles(repo),
508
547
  milestones: await api.milestones(repo),
509
548
  statedCriteria,
549
+ namedIssues: named.length > 0 ? await api.issueStates(repo, named) : new Map<number, "open" | "closed">(),
510
550
  };
511
551
  } catch (e) {
512
552
  return refuse(`UNMEASURED — could not read the tracker, so the plan was not applied:`, [
@@ -560,9 +600,12 @@ async function decompose(
560
600
  const alreadyWired: string[] = [];
561
601
  const existing = new Map<number, Set<number>>();
562
602
  if (write) {
603
+ // Either end may be an existing issue (#2339: a Blocks cell puts one on
604
+ // the BLOCKED end), so both ends resolve the same way.
605
+ const end = (x: string): number | undefined => (/^#\d+$/.test(x) ? Number(x.slice(1)) : numbers.get(x));
563
606
  for (const e of planned.edges) {
564
- const blocked = numbers.get(e.blocked);
565
- const blocker = /^#(\d+)$/.exec(e.blocker) ? Number(e.blocker.slice(1)) : numbers.get(e.blocker);
607
+ const blocked = end(e.blocked);
608
+ const blocker = end(e.blocker);
566
609
  if (blocked === undefined || blocker === undefined) {
567
610
  // One end was never created, because its creation failed above. Say
568
611
  // so: a missing edge that nothing reports is an order silently lost.
@@ -615,7 +658,8 @@ async function decompose(
615
658
  else if (a.kind === "closed") console.log(` closed #${a.number} ${a.row.outcome}`);
616
659
  else console.log(` create ${a.row.criterion.padEnd(8)} ${a.title}`);
617
660
  }
618
- for (const e of planned.edges) console.log(` order "${e.blocked}" blocked by "${e.blocker}"`);
661
+ const shown = (x: string): string => (/^#\d+$/.test(x) ? x : `"${x}"`);
662
+ for (const e of planned.edges) console.log(` order ${shown(e.blocked)} blocked by ${shown(e.blocker)}`);
619
663
  if (!write) {
620
664
  console.log(`\nNothing written. Re-run with --write to apply.`);
621
665
  return 0;
@@ -25,7 +25,7 @@ import { join } from "path";
25
25
  import { execSync } from "child_process";
26
26
  import { matchPattern, isBehavioralSC, type ParsedSC } from "../lib/conformity";
27
27
  import { behavioralCachePath, readFreshCache } from "../lib/behavioral-cache";
28
- import { skipLine } from "../lib/derived-spec";
28
+ import { readDerivedDeclaration, skipLine } from "../lib/derived-spec";
29
29
  import { maySpecBeWritten, writeSpec } from "../lib/write-spec";
30
30
  import { detectDrift } from "./detect-sc-drift";
31
31
  import {
@@ -180,7 +180,23 @@ export interface UncheckedSC {
180
180
  * ids. A fix on the reading side alone cannot see this: the registry leg
181
181
  * would faithfully report an enumeration flag nobody had ever set wrong.
182
182
  */
183
- export function readScRegistry(specsDir?: string): ScRegistry {
183
+ /**
184
+ * The specs that AUTHOR their criteria — every spec but a `generated-by:` copy
185
+ * (#2333). A copy repeats its source's ids; counted as a second author it made
186
+ * each of them ambiguous, so a test claiming the source's criterion credited
187
+ * no spec at all. The one decider for the credit rule and for board-scope's
188
+ * who-states-this-id map, so the two cannot disagree.
189
+ */
190
+ export function authoredSpecs<T extends { content: string }>(specs: readonly T[]): T[] {
191
+ return specs.filter(s => readDerivedDeclaration(s.content).status !== "derived");
192
+ }
193
+
194
+ /**
195
+ * `authoredOnly` (#2333): leave generated copies out, for the CREDIT rule. The
196
+ * allocator (`scripts/create-sc.ts`) reads every spec, copies included, so an
197
+ * id a stale copy still states is never handed out again.
198
+ */
199
+ export function readScRegistry(specsDir?: string, opts: { authoredOnly?: boolean } = {}): ScRegistry {
184
200
  const dir = specsDir || SPECS_DIR;
185
201
  if (!existsSync(dir)) return unenumeratedScRegistry(`${dir} does not exist`);
186
202
  const specs: Array<{ file: string; content: string }> = [];
@@ -193,10 +209,16 @@ export function readScRegistry(specsDir?: string): ScRegistry {
193
209
  // absent one from the allocator's side, and a different reason.
194
210
  return unenumeratedScRegistry(`${dir} could not be enumerated: ${(err as Error).message}`);
195
211
  }
196
- return buildScRegistry(specs);
212
+ return buildScRegistry(opts.authoredOnly === true ? authoredSpecs(specs) : specs);
197
213
  }
198
214
 
199
- export function findUncheckedSCs(specsDir?: string): UncheckedSC[] {
215
+ /**
216
+ * `authoredOnly` (#2333): leave generated copies out. The credit list and the
217
+ * registry beside it must agree on who the authors are — filtering only the
218
+ * registry made a copy's id unambiguous while the copy still sat in the credit
219
+ * list, so a claim was credited to both and `--only` refused the source.
220
+ */
221
+ export function findUncheckedSCs(specsDir?: string, opts: { authoredOnly?: boolean } = {}): UncheckedSC[] {
200
222
  const dir = specsDir || SPECS_DIR;
201
223
  const unchecked: UncheckedSC[] = [];
202
224
  if (!existsSync(dir)) return unchecked;
@@ -204,6 +226,7 @@ export function findUncheckedSCs(specsDir?: string): UncheckedSC[] {
204
226
  for (const file of new Bun.Glob("**/*.md").scanSync({ cwd: dir, absolute: false })) {
205
227
  if (isTemplateSpec(file)) continue;
206
228
  const content = readFileSync(join(dir, file), "utf-8");
229
+ if (opts.authoredOnly === true && authoredSpecs([{ content }]).length === 0) continue;
207
230
  // #330: was `/^- \[ \] (SC-\d+):/`, the fourth copy of this pattern in the
208
231
  // tree and the second that could not see an anti-criterion. One owner now.
209
232
  for (const match of content.matchAll(scDeclarationPattern())) {
@@ -716,10 +739,12 @@ export function claimedScKeys(specsDir: string, testDir?: string): Set<string> {
716
739
  const specs = readdirSync(specsDir, { recursive: true, encoding: "utf-8" })
717
740
  .filter((f): f is string => typeof f === "string" && f.endsWith(".md"))
718
741
  .map(f => ({ file: f, content: readFileSync(join(specsDir, f), "utf-8") }));
719
- const declarations = specs
742
+ // #2333: generated copies are not authors, at either half of the credit.
743
+ const authored = authoredSpecs(specs);
744
+ const declarations = authored
720
745
  .filter(s => !isTemplateSpec(s.file))
721
746
  .flatMap(s => parseScDeclarations(s.content, s.file));
722
- const credits = findTestFilesForSCs(declarations, buildScRegistry(specs), testDir);
747
+ const credits = findTestFilesForSCs(declarations, buildScRegistry(authored), testDir);
723
748
  return new Set([...credits.values()].flat().map(c => scopedKey(c.specFile, c.id)));
724
749
  }
725
750
 
@@ -923,7 +948,11 @@ if (isDirectExecution) {
923
948
  );
924
949
  process.exit(1);
925
950
  }
926
- const unchecked = findUncheckedSCs();
951
+ // #2333: generated copies are not authors, so they enter NO leg of this
952
+ // run — not the credit, the conformity check, the duplicate warning or the
953
+ // per-spec tally. Filtering one leg at a time left the next one reading
954
+ // them (review rounds 2 and 3 of #2372); this is the one site upstream.
955
+ const unchecked = findUncheckedSCs(undefined, { authoredOnly: true });
927
956
  if (unchecked.length === 0) {
928
957
  console.log("All SCs are already checked off");
929
958
  process.exit(0);
@@ -969,7 +998,8 @@ if (isDirectExecution) {
969
998
  // Step 2: Find SCs covered by hand-written test files.
970
999
  // Scoped to (spec, id) since #330 — see findTestFilesForSCs. The old bare-id
971
1000
  // credit ticked the id in every spec declaring it.
972
- const registry = readScRegistry();
1001
+ // #2333: the credit rule's registry leaves generated copies out.
1002
+ const registry = readScRegistry(undefined, { authoredOnly: true });
973
1003
  const testFileMap = findTestFilesForSCs(unchecked, registry);
974
1004
  const testedKeys = new Set(
975
1005
  [...testFileMap.values()].flat().map(c => scopedKey(c.specFile, c.id)),
@@ -57,7 +57,10 @@ the whole plan if any row breaks a rule, so check each one:
57
57
  - **Milestone**: the exact title of a milestone that exists, or `—` for
58
58
  none.
59
59
  - **Blocked by**: `#<issue>`, or another row's Outcome word for word, or `—`.
60
- A cycle is refused.
60
+ A cycle is refused, and so is a `#<issue>` this repository does not hold.
61
+ - **Blocks** (optional sixth column): existing issues, `#<issue>` only, that
62
+ wait on this row once it exists. To use it, add `| Blocks |` to the header;
63
+ every row then has six cells. An unknown or closed issue is refused.
61
64
 
62
65
  Keep the table outside code fences and comments. The filing tool reads only
63
66
  live table rows.