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
@@ -28,7 +28,8 @@
28
28
  * issues it is itself demoting, and touches no others. The cause and the
29
29
  * cleanup are one action.
30
30
  */
31
- import { existsSync, readFileSync } from "fs";
31
+ import { existsSync, readFileSync, readdirSync } from "fs";
32
+ import { spawnSync } from "child_process";
32
33
  import { isAbsolute, join, relative, sep } from "path";
33
34
  import { parseArgs } from "util";
34
35
  import {
@@ -37,10 +38,21 @@ import {
37
38
  annotatedBody,
38
39
  multiplyAnnotated,
39
40
  parseRepairPlan,
41
+ rowPlacement,
40
42
  } from "../lib/issue-repair";
41
43
  import type { RepairRow } from "../lib/issue-repair";
42
- import { parseDecompositionPlan, planDecomposition } from "../lib/issue-decomposition";
44
+ import {
45
+ closedIssueCounts,
46
+ hasDecompositionTable,
47
+ newlyAccepted,
48
+ parseDecompositionPlan,
49
+ planDecomposition,
50
+ } from "../lib/issue-decomposition";
43
51
  import { readQueueLabel } from "../lib/config-readers";
52
+ import { answerableIds, specCriteriaIn } from "../lib/board-mirror";
53
+ import { milestonePlan, placementReading } from "../lib/spec-placement";
54
+ import { readMilestonePrefix } from "../lib/live-issues";
55
+ import type { LiveMilestone, MilestoneAction } from "../lib/spec-placement";
44
56
 
45
57
  /**
46
58
  * THE one non-zero exit. One site, so `test/plan-issues.test.ts` can build a
@@ -63,6 +75,9 @@ export interface PlanIssuesGitHub {
63
75
  setBody: (repo: string, number: number, body: string) => Promise<void>;
64
76
  clearMilestone: (repo: string, number: number) => Promise<void>;
65
77
  removeBlockedBy: (repo: string, blocked: number, blocker: number) => Promise<void>;
78
+ /** Every milestone, for `--milestone-prefix` placement (#2042). */
79
+ milestones: (repo: string) => Promise<LiveMilestone[]>;
80
+ setMilestone: (repo: string, number: number, title: string) => Promise<void>;
66
81
  }
67
82
 
68
83
  /**
@@ -144,6 +159,27 @@ const LIVE_GITHUB: PlanIssuesGitHub = {
144
159
  removeBlockedBy: async (repo, blocked, blocker) => {
145
160
  gh(["issue", "edit", String(blocked), "--repo", repo, "--remove-blocked-by", String(blocker)]);
146
161
  },
162
+ // PAGINATED, for the reason `LIVE_DECOMPOSE.milestones` gives: a phase
163
+ // milestone on page two would read as absent and refuse the run.
164
+ milestones: async repo => {
165
+ const out = gh([
166
+ "api",
167
+ "--paginate",
168
+ `repos/${repo}/milestones?state=all&per_page=100`,
169
+ "--jq",
170
+ ".[] | [.number, .title, .description] | @json",
171
+ ]);
172
+ return out
173
+ .split("\n")
174
+ .filter(l => l.trim() !== "")
175
+ .map(l => {
176
+ const [number, title, description] = JSON.parse(l) as [number, string, string | null];
177
+ return { number, title, description };
178
+ });
179
+ },
180
+ setMilestone: async (repo, number, title) => {
181
+ gh(["issue", "edit", String(number), "--repo", repo, "--milestone", title]);
182
+ },
147
183
  };
148
184
 
149
185
  const USAGE = `rungate plan-issues (--repair | --decompose) <plan.md> --repo <owner/name> [--write] [--json]
@@ -151,17 +187,31 @@ const USAGE = `rungate plan-issues (--repair | --decompose) <plan.md> --repo <ow
151
187
  --repair an approved repair plan. A table of
152
188
  | Issue | Phase | Repair | Criteria | Confidence | Why |
153
189
  where Repair is (a) annotate or (b) demote.
190
+ --milestone-prefix <family> --spec <family spec>
191
+ with --repair: also move each (a) row's issue into
192
+ <family> Phase N, the phase its Phase column names. Only rows
193
+ whose criteria the family spec places are moved; a phase with
194
+ no milestone, or a Phase column the spec disagrees with,
195
+ refuses the run before anything is written.
154
196
  --decompose a decomposition plan — step 4 of ADR-003. A table of
155
197
  | Criterion | Outcome | Files | Milestone | Blocked by |
156
198
  where one row is one issue proving one criterion.
157
199
  --repo owner/name. Defaults to $GITHUB_REPOSITORY.
158
200
  --write apply it. Without this nothing is mutated.
159
- --json the whole reading.`;
201
+ --json the whole reading.
202
+
203
+ rungate plan-issues --accepted-since <commit> [--project-root <dir>]
204
+
205
+ Print each docs/adr/*.md that is accepted now and was not at <commit>, and
206
+ that carries a Decomposition table — one path per line, nothing else on
207
+ stdout. Reads git only; touches no tracker. Used by adr-accepted.yml.`;
160
208
 
161
209
  /** What creating issues from a plan needs. Injected so a test never shells out. */
162
210
  export interface DecomposeGitHub {
163
211
  /** Title → number for every OPEN issue. The idempotence key. */
164
212
  openTitles: (repo: string) => Promise<Map<string, number>>;
213
+ /** Title → number for every CLOSED issue, so finished work is never re-filed (SC-2738). */
214
+ closedTitles: (repo: string) => Promise<Map<string, number>>;
165
215
  /** Milestone titles that exist. `plan-spec` makes them; this never does. */
166
216
  milestones: (repo: string) => Promise<Set<string>>;
167
217
  create: (
@@ -184,6 +234,32 @@ export interface DecomposeGitHub {
184
234
  blockedBy: (repo: string, issue: number) => Promise<number[]>;
185
235
  }
186
236
 
237
+ function issueTitles(repo: string, state: "open" | "closed"): Map<string, number> {
238
+ const out = gh([
239
+ "api",
240
+ "--paginate",
241
+ `repos/${repo}/issues?state=${state}&per_page=100`,
242
+ "--jq",
243
+ ".[] | select(.pull_request == null) | [.number, .title, .state_reason, .author_association] | @json",
244
+ ]);
245
+ const map = new Map<string, number>();
246
+ for (const line of out.split("\n")) {
247
+ if (line.trim() === "") continue;
248
+ const [number, title, state_reason, author_association] = JSON.parse(line) as [
249
+ number,
250
+ string,
251
+ string | null,
252
+ string,
253
+ ];
254
+ if (state === "closed" && !closedIssueCounts({ state_reason, author_association })) continue;
255
+ // The FIRST number seen for a title is kept. Two closed issues sharing a
256
+ // title are both finished work; which one a blocked row points at does
257
+ // not change what it waits for.
258
+ if (!map.has(title)) map.set(title, number);
259
+ }
260
+ return map;
261
+ }
262
+
187
263
  const LIVE_DECOMPOSE: DecomposeGitHub = {
188
264
  /**
189
265
  * Every open issue, PAGINATED.
@@ -200,22 +276,12 @@ const LIVE_DECOMPOSE: DecomposeGitHub = {
200
276
  * title matched a row would otherwise read as the issue already existing
201
277
  * and skip creating it.
202
278
  */
203
- openTitles: async repo => {
204
- const out = gh([
205
- "api",
206
- "--paginate",
207
- `repos/${repo}/issues?state=open&per_page=100`,
208
- "--jq",
209
- ".[] | select(.pull_request == null) | [.number, .title] | @json",
210
- ]);
211
- const map = new Map<string, number>();
212
- for (const line of out.split("\n")) {
213
- if (line.trim() === "") continue;
214
- const [number, title] = JSON.parse(line) as [number, string];
215
- map.set(title, number);
216
- }
217
- return map;
218
- },
279
+ openTitles: async repo => issueTitles(repo, "open"),
280
+ /**
281
+ * The same read, for closed issues, kept only where `closedIssueCounts`
282
+ * says the close is finished work by a trusted author.
283
+ */
284
+ closedTitles: async repo => issueTitles(repo, "closed"),
219
285
  /**
220
286
  * Every milestone, PAGINATED, for a worse reason than `openTitles` above.
221
287
  *
@@ -325,6 +391,39 @@ export function refusalReporter(
325
391
  };
326
392
  }
327
393
 
394
+ /**
395
+ * Which ADRs did the change since `since` accept? (SC-2738)
396
+ *
397
+ * A commit this clone cannot read REFUSES. A shallow checkout reading every
398
+ * ADR as absent at the earlier commit would list every accepted ADR in the
399
+ * repository, and the workflow would re-run all of their plans.
400
+ */
401
+ function acceptedSince(root: string, since: string): number {
402
+ const git = (...args: string[]) => spawnSync("git", ["-C", root, ...args], { encoding: "utf-8" });
403
+ if (git("cat-file", "-e", `${since}^{commit}`).status !== 0) {
404
+ console.error(
405
+ `plan-issues: UNMEASURED — commit ${since} is not in this clone, so what it held could not be read. ` +
406
+ `Nothing is listed. A shallow checkout needs fetch-depth: 0.`,
407
+ );
408
+ return REFUSAL_EXIT;
409
+ }
410
+ const dir = join(root, "docs", "adr");
411
+ const names = existsSync(dir) ? readdirSync(dir).filter(n => n.endsWith(".md")).sort() : [];
412
+ for (const name of names) {
413
+ const path = `docs/adr/${name}`;
414
+ const after = readFileSync(join(root, path), "utf-8");
415
+ const was = git("cat-file", "-e", `${since}:${path}`).status === 0 ? git("show", `${since}:${path}`) : null;
416
+ if (was !== null && was.status !== 0) {
417
+ console.error(`plan-issues: UNMEASURED — could not read ${path} at ${since}: ${was.stderr.trim()}`);
418
+ return REFUSAL_EXIT;
419
+ }
420
+ if (!newlyAccepted(was === null ? null : was.stdout, after)) continue;
421
+ if (hasDecompositionTable(after)) console.log(path);
422
+ else console.error(`plan-issues: ${path} was accepted, and carries no Decomposition table — nothing to place.`);
423
+ }
424
+ return 0;
425
+ }
426
+
328
427
  async function decompose(
329
428
  planPath: string,
330
429
  /**
@@ -344,6 +443,8 @@ async function decompose(
344
443
  * config fixture on disk.
345
444
  */
346
445
  queueLabel: string | null,
446
+ /** Where `specs/` is read from, for the criterion ids a row may name. */
447
+ root: string,
347
448
  ): Promise<number> {
348
449
  const refuse = refusalReporter(json);
349
450
 
@@ -362,9 +463,28 @@ async function decompose(
362
463
  // every other refusal here does. A command that crashes and a command that
363
464
  // refuses are different facts, and only one of them says what to do next.
364
465
  // Found by the AI review of this change.
466
+ // The ids a row may name. An unreadable sweep refuses: an empty id set is
467
+ // what a repository with no criteria produces, and reading it as one would
468
+ // refuse every row for the wrong reason (or, inverted, accept them all).
469
+ const sweep = specCriteriaIn(root);
470
+ if (sweep.reading === "UNMEASURED") {
471
+ return refuse(
472
+ `UNMEASURED — the criterion ids under ${join(root, "specs")} could not be read, so no row's criterion could be checked:`,
473
+ [...sweep.unmeasuredReasons],
474
+ );
475
+ }
476
+ // An id two specs both state is still STATED; it is ambiguous for the board
477
+ // column, not absent.
478
+ const statedCriteria = new Set(answerableIds(sweep));
479
+
365
480
  let live;
366
481
  try {
367
- live = { openTitles: await api.openTitles(repo), milestones: await api.milestones(repo) };
482
+ live = {
483
+ openTitles: await api.openTitles(repo),
484
+ closedTitles: await api.closedTitles(repo),
485
+ milestones: await api.milestones(repo),
486
+ statedCriteria,
487
+ };
368
488
  } catch (e) {
369
489
  return refuse(`UNMEASURED — could not read the tracker, so the plan was not applied:`, [
370
490
  (e as Error).message,
@@ -378,7 +498,7 @@ async function decompose(
378
498
 
379
499
  /** Outcome → number, grown as issues are created, so pass two can resolve. */
380
500
  const numbers = new Map<string, number>();
381
- for (const a of planned.actions) if (a.kind === "exists") numbers.set(a.row.outcome, a.number);
501
+ for (const a of planned.actions) if (a.kind !== "create") numbers.set(a.row.outcome, a.number);
382
502
 
383
503
  const created: { title: string; number: number }[] = [];
384
504
  const failed: string[] = [];
@@ -453,6 +573,7 @@ async function decompose(
453
573
  plan: planPath,
454
574
  wouldCreate: planned.actions.filter(a => a.kind === "create").length,
455
575
  alreadyOpen: planned.actions.filter(a => a.kind === "exists").length,
576
+ alreadyClosed: planned.actions.filter(a => a.kind === "closed").length,
456
577
  wrote: write,
457
578
  created,
458
579
  edges,
@@ -468,6 +589,7 @@ async function decompose(
468
589
 
469
590
  for (const a of planned.actions) {
470
591
  if (a.kind === "exists") console.log(` open #${a.number} ${a.row.outcome}`);
592
+ else if (a.kind === "closed") console.log(` closed #${a.number} ${a.row.outcome}`);
471
593
  else console.log(` create ${a.row.criterion.padEnd(8)} ${a.title}`);
472
594
  }
473
595
  for (const e of planned.edges) console.log(` order "${e.blocked}" blocked by "${e.blocker}"`);
@@ -487,8 +609,10 @@ async function decompose(
487
609
  /** What one row would do, resolved against the issue's live state. */
488
610
  interface Action {
489
611
  row: RepairRow;
490
- kind: "annotate" | "demote" | "unchanged" | "refused";
612
+ kind: "annotate" | "demote" | "unchanged" | "refused" | "place" | "skip";
491
613
  body?: string;
614
+ /** For a placement: the milestone title the issue moves into (#2042). */
615
+ milestone?: string;
492
616
  /** For a demotion: every edge the demotion orphans. */
493
617
  edges: { blocked: number; blocker: number }[];
494
618
  note: string;
@@ -510,6 +634,9 @@ export async function main(
510
634
  write: { type: "boolean", default: false },
511
635
  json: { type: "boolean", default: false },
512
636
  "project-root": { type: "string" },
637
+ "accepted-since": { type: "string" },
638
+ "milestone-prefix": { type: "string" },
639
+ spec: { type: "string" },
513
640
  },
514
641
  allowPositionals: true,
515
642
  });
@@ -518,6 +645,13 @@ export async function main(
518
645
  return REFUSAL_EXIT;
519
646
  }
520
647
  const { values } = parsed;
648
+ if (values["accepted-since"] !== undefined) {
649
+ if (values.repair || values.decompose) {
650
+ console.error(`plan-issues: --accepted-since lists plans; it applies none — pass it alone\n\n${USAGE}`);
651
+ return REFUSAL_EXIT;
652
+ }
653
+ return acceptedSince(values["project-root"] ?? process.cwd(), values["accepted-since"]);
654
+ }
521
655
  // Both would mean two plans in one run, and the second would be applied
522
656
  // against a tracker the first had already moved. One or the other.
523
657
  if (values.repair && values.decompose) {
@@ -529,6 +663,10 @@ export async function main(
529
663
  console.error(`plan-issues: --repair <plan.md> or --decompose <plan.md> is required\n\n${USAGE}`);
530
664
  return REFUSAL_EXIT;
531
665
  }
666
+ if ((values["milestone-prefix"] !== undefined || values.spec !== undefined) && !values.repair) {
667
+ console.error(`plan-issues: --milestone-prefix and --spec place a repair plan's rows — pass them with --repair\n\n${USAGE}`);
668
+ return REFUSAL_EXIT;
669
+ }
532
670
  const repo = values.repo ?? process.env.GITHUB_REPOSITORY;
533
671
  if (!repo) {
534
672
  console.error(`plan-issues: --repo is required (or set GITHUB_REPOSITORY)\n\n${USAGE}`);
@@ -554,7 +692,55 @@ export async function main(
554
692
  const within = relative(root, planPath);
555
693
  const escapes = within === ".." || within.startsWith(`..${sep}`);
556
694
  const planLabel = within === "" || escapes ? planPath : within;
557
- return await decompose(planPath, planLabel, repo, values.write, values.json, gh3, readQueueLabel(root));
695
+ return await decompose(planPath, planLabel, repo, values.write, values.json, gh3, readQueueLabel(root), root);
696
+ }
697
+
698
+ // #2042: placement is opt-in per family and needs that family's spec — the
699
+ // family names the milestones, the spec says which criteria each phase
700
+ // holds. Settled before any issue is read.
701
+ // The one reading of what a prefix argument said (`lib/live-issues.ts`),
702
+ // so blank and absent are decided where plan-deps decides them.
703
+ const prefixRead = readMilestonePrefix(values["milestone-prefix"]);
704
+ const prefix = prefixRead.kind === "given" ? prefixRead.prefix : undefined;
705
+ let familyPlan: MilestoneAction[] | null = null;
706
+ let familyStated: Set<string> = new Set();
707
+ if (prefixRead.kind !== "absent" || values.spec !== undefined) {
708
+ if (prefix === undefined || values.spec === undefined) {
709
+ console.error(
710
+ `plan-issues: --milestone-prefix <family> and --spec <family spec> go together — the family ` +
711
+ `names the milestones and the spec says which criteria each phase holds\n\n${USAGE}`,
712
+ );
713
+ return REFUSAL_EXIT;
714
+ }
715
+ const specPath = isAbsolute(values.spec) ? values.spec : join(root, values.spec);
716
+ if (!existsSync(specPath)) {
717
+ console.error(`plan-issues: no such spec: ${specPath}`);
718
+ return REFUSAL_EXIT;
719
+ }
720
+ const specText = readFileSync(specPath, "utf-8");
721
+ const placement = placementReading(specText);
722
+ if (placement.reading === "UNMEASURED") {
723
+ console.error(`plan-issues: UNMEASURED — ${values.spec} cannot place a row:`);
724
+ for (const r of placement.unmeasuredReasons) console.error(` - ${r}`);
725
+ return REFUSAL_EXIT;
726
+ }
727
+ // #2072: the three readings plan-spec and board-snapshot already refuse.
728
+ // A doubled id would go to whichever phase row comes last, and an
729
+ // unknown one reads as two families at once. `unplaced` is left out on
730
+ // purpose: a criterion in no row has no phase, and `rowPlacement`
731
+ // already skips or refuses a row naming one.
732
+ const unsound = [
733
+ ...placement.doubled.map(d => `${d.id} is placed twice: ${d.placements.join(" and ")}`),
734
+ ...placement.unknown.map(id => `${id} is placed but stated nowhere in the spec`),
735
+ ...placement.unrecognised.map(p => `"${p}" is neither a phase nor a known non-phase placement`),
736
+ ];
737
+ if (unsound.length > 0) {
738
+ console.error(`plan-issues: ${values.spec}'s placement table is unsound, so no row can be placed from it:`);
739
+ for (const u of unsound) console.error(` - ${u}`);
740
+ return REFUSAL_EXIT;
741
+ }
742
+ familyStated = new Set(placement.criteria);
743
+ familyPlan = milestonePlan(specText, await gh2.milestones(repo), prefix).actions;
558
744
  }
559
745
 
560
746
  const reading = parseRepairPlan(readFileSync(planPath, "utf-8"));
@@ -570,31 +756,58 @@ export async function main(
570
756
  }
571
757
 
572
758
  const actions: Action[] = [];
759
+ // A placement refusal stops the WHOLE run before any write, unlike a body
760
+ // refusal, which stops only its row (#2042: "refused before anything is
761
+ // written").
762
+ const placementRefusals: Action[] = [];
573
763
  for (const row of reading.rows) {
574
764
  const live = await gh2.readIssue(repo, row.issue);
575
765
  if (row.kind === "annotate") {
576
766
  // Two sections means editing the first is a guess, and the second keeps
577
767
  // whatever stale ids it holds. Refuse the row by name.
578
- if (multiplyAnnotated(live.body)) {
768
+ const bodyRefused = multiplyAnnotated(live.body);
769
+ if (bodyRefused) {
579
770
  actions.push({
580
771
  row,
581
772
  kind: "refused",
582
773
  edges: [],
583
774
  note: `body carries "${CRITERIA_HEADING}" more than once — resolve it by hand`,
584
775
  });
585
- continue;
586
- }
587
- if (alreadyAnnotated(live.body, row.criteria)) {
776
+ } else if (alreadyAnnotated(live.body, row.criteria)) {
588
777
  actions.push({ row, kind: "unchanged", edges: [], note: `already names ${row.criteria.join(", ")}` });
589
- continue;
778
+ } else {
779
+ actions.push({
780
+ row,
781
+ kind: "annotate",
782
+ body: annotatedBody(live.body, row.criteria),
783
+ edges: [],
784
+ note: `+ ${row.criteria.join(", ")}`,
785
+ });
786
+ }
787
+ if (familyPlan !== null && bodyRefused) {
788
+ // Review of #2069: moving the milestone while the criteria section
789
+ // stays ambiguous leaves the tracker half-applied.
790
+ actions.push({ row, kind: "skip", edges: [], note: "not placed: its body was refused above" });
791
+ } else if (familyPlan !== null) {
792
+ const p = rowPlacement(row, familyPlan, prefix!, familyStated);
793
+ if (p.kind === "refuse") {
794
+ const refused: Action = { row, kind: "refused", edges: [], note: `cannot place: ${p.why}` };
795
+ actions.push(refused);
796
+ placementRefusals.push(refused);
797
+ } else if (p.kind === "skip") {
798
+ actions.push({ row, kind: "skip", edges: [], note: p.why });
799
+ } else if (live.milestone === p.milestone) {
800
+ actions.push({ row, kind: "unchanged", edges: [], note: `already in "${p.milestone}"` });
801
+ } else {
802
+ actions.push({
803
+ row,
804
+ kind: "place",
805
+ milestone: p.milestone,
806
+ edges: [],
807
+ note: `${live.milestone === null ? "no milestone" : `"${live.milestone}"`} → "${p.milestone}"`,
808
+ });
809
+ }
590
810
  }
591
- actions.push({
592
- row,
593
- kind: "annotate",
594
- body: annotatedBody(live.body, row.criteria),
595
- edges: [],
596
- note: `+ ${row.criteria.join(", ")}`,
597
- });
598
811
  continue;
599
812
  }
600
813
  if (live.milestone === null) {
@@ -618,25 +831,34 @@ export async function main(
618
831
  // swallowed every failure into a string nothing read — so a run that
619
832
  // failed on all eleven rows emitted "yes" and exited 0. Fail-open status
620
833
  // reporting, caught by the security review of this PR.
621
- const results = values.write && !refuseWrite ? await apply(gh2, repo, actions) : [];
834
+ const blocked = refuseWrite || placementRefusals.length > 0;
835
+ const results = values.write && !blocked ? await apply(gh2, repo, actions) : [];
622
836
  const failures = results.filter(r => r.startsWith("FAILED"));
623
837
  const refusedRows = actions.filter(a => a.kind === "refused");
624
838
  const wrote = !values.write
625
839
  ? "not-requested"
626
- : refuseWrite
840
+ : blocked
627
841
  ? "refused"
628
842
  : failures.length > 0 || refusedRows.length > 0
629
843
  ? "partial"
630
844
  : "yes";
631
- console.log(JSON.stringify({ ...reading, actions, results, wrote }, null, 2));
632
- return refuseWrite || failures.length > 0 || refusedRows.length > 0 ? REFUSAL_EXIT : 0;
845
+ const placement = familyPlan === null ? "not-requested" : prefix;
846
+ console.log(JSON.stringify({ ...reading, actions, results, wrote, placement }, null, 2));
847
+ return blocked || failures.length > 0 || refusedRows.length > 0 ? REFUSAL_EXIT : 0;
633
848
  }
634
849
 
635
850
  const edges = actions.reduce((n, a) => n + a.edges.length, 0);
636
851
  console.log(`${values.repair} — ${reading.rows.length} row(s)\n`);
637
852
  console.log(`ACTIONS`);
638
853
  for (const a of actions) {
639
- const mark = { annotate: "ANNOTATE", demote: "DEMOTE ", unchanged: "ok ", refused: "REFUSED " }[a.kind];
854
+ const mark = {
855
+ annotate: "ANNOTATE",
856
+ demote: "DEMOTE ",
857
+ unchanged: "ok ",
858
+ refused: "REFUSED ",
859
+ place: "PLACE ",
860
+ skip: "skip ",
861
+ }[a.kind];
640
862
  console.log(` ${mark} #${a.row.issue} ${a.note}`);
641
863
  if (a.edges.length > 0) {
642
864
  console.log(` and remove ${a.edges.length} edge(s) the demotion orphans:`);
@@ -646,8 +868,22 @@ export async function main(
646
868
  console.log(
647
869
  `\n ${actions.filter(a => a.kind === "annotate").length} annotate, ` +
648
870
  `${actions.filter(a => a.kind === "demote").length} demote, ` +
871
+ `${actions.filter(a => a.kind === "place").length} place, ` +
649
872
  `${actions.filter(a => a.kind === "unchanged").length} already correct, ${edges} edge(s) to remove`,
650
873
  );
874
+ if (familyPlan === null && reading.rows.some(r => r.kind === "annotate")) {
875
+ console.log(
876
+ `\n The Phase column was not applied — no milestone is moved without ` +
877
+ `--milestone-prefix <family> --spec <family spec>.`,
878
+ );
879
+ }
880
+ if (placementRefusals.length > 0) {
881
+ console.error(
882
+ `\nplan-issues: ${placementRefusals.length} row(s) cannot be placed, so nothing was written. ` +
883
+ `Fix the plan or the spec and re-run.`,
884
+ );
885
+ return REFUSAL_EXIT;
886
+ }
651
887
 
652
888
  if (!values.write) {
653
889
  console.log(`\nNothing written. Re-run with --write to apply.`);
@@ -708,6 +944,9 @@ async function apply(gh2: PlanIssuesGitHub, repo: string, actions: readonly Acti
708
944
  for (const e of a.edges) await gh2.removeBlockedBy(repo, e.blocked, e.blocker);
709
945
  await gh2.clearMilestone(repo, a.row.issue);
710
946
  done.push(`demoted #${a.row.issue} and removed ${a.edges.length} edge(s)`);
947
+ } else if (a.kind === "place") {
948
+ await gh2.setMilestone(repo, a.row.issue, a.milestone!);
949
+ done.push(`placed #${a.row.issue} in "${a.milestone}"`);
711
950
  }
712
951
  } catch (e) {
713
952
  done.push(`FAILED #${a.row.issue}: ${(e as Error).message}`);
@@ -49,9 +49,11 @@ import {
49
49
  import {
50
50
  milestoneBody,
51
51
  milestonePlan,
52
+ placementCoverage,
52
53
  placementReading,
53
54
  uncoveredByMilestone,
54
55
  } from "../lib/spec-placement";
56
+ import { specPathSweep } from "../lib/board-mirror";
55
57
  import { readMilestonePrefix } from "../lib/live-issues";
56
58
 
57
59
  /**
@@ -127,14 +129,61 @@ const LIVE_GITHUB: PlanSpecGitHub = {
127
129
  renameMilestone,
128
130
  };
129
131
 
130
- const USAGE = `rungate plan-spec <spec.md> --repo <owner/name> --prefix <name> [--write] [--json]
132
+ const USAGE = `rungate plan-spec <spec.md> --repo <owner/name> --prefix <name> [--rename-from <old name>] [--write] [--json]
133
+ rungate plan-spec --coverage [--project-root <dir>] [--json]
131
134
 
132
135
  --repo owner/name. Defaults to $GITHUB_REPOSITORY.
133
136
  --prefix the milestone name prefix, e.g. "Convergence" gives
134
137
  "Convergence Phase 1 — stop the repeats". Required: deriving it
135
138
  from the filename would call the live milestones something else.
139
+ --rename-from
140
+ the family the milestones are called today, when --prefix is
141
+ their new name. Each phase's old milestone is renamed in place,
142
+ keeping its number and its issues, instead of a new one being
143
+ created. A phase both families hold is refused (#2124).
136
144
  --write create and rename milestones. Without it, nothing is mutated.
137
- --json the whole reading, for something other than a person.`;
145
+ --json the whole reading, for something other than a person.
146
+ --coverage every spec in the tree and whether its criteria are placed,
147
+ instead of one spec. Takes no spec, reaches no network and
148
+ writes nothing. A spec with no placement table is named as
149
+ UNPLANNED rather than contributing nothing (SC-2611).`;
150
+
151
+ /**
152
+ * The repo-wide reading, printed. Reaches no network and writes nothing.
153
+ *
154
+ * It exits non-zero on UNMEASURED and on nothing else. An unplanned spec is
155
+ * a FINDING, not a refusal: 25 of 26 were unplanned when this was written, so
156
+ * a non-zero exit would be a gate nobody could ever get green and everybody
157
+ * would learn to pass `|| true`.
158
+ */
159
+ function reportCoverage(root: string, asJson: boolean): number {
160
+ const r = placementCoverage(root, specPathSweep, (base, path) =>
161
+ readFileSync(join(base, path), "utf-8"),
162
+ );
163
+ if (asJson) {
164
+ console.log(JSON.stringify(r, null, 2));
165
+ return r.reading === "UNMEASURED" ? REFUSAL_EXIT : 0;
166
+ }
167
+ if (r.reading === "UNMEASURED") {
168
+ return refuse(false, `UNMEASURED — ${r.unmeasuredReasons.join("; ")}`);
169
+ }
170
+ console.log(`placement coverage — ${r.specs.length} spec(s) under ${join(root, "specs")}\n`);
171
+ console.log(` PLANNED ${r.planned.length}`);
172
+ console.log(` UNPLANNED ${r.unplanned.length}`);
173
+ console.log(` NO_CRITERIA ${r.noCriteria.length}\n`);
174
+ // `r.unplanned`, never a second `state === "UNPLANNED"` filter here. The
175
+ // roll-up already decides which specs are unplanned, and a filter of my
176
+ // own is a second decider answering the same question: found by the
177
+ // mutation battery, which blanked `unplanned` and left these rows printing
178
+ // (`.claude/rules/checks-must-be-able-to-fail.md`, *two deciders agree*).
179
+ for (const path of r.unplanned) {
180
+ const s = r.specs.find(s => s.path === path)!;
181
+ console.log(` UNPLANNED ${s.path} — ${s.criteria} criteria, ${s.placed} placed`);
182
+ for (const why of s.reasons) console.log(` ${why}`);
183
+ }
184
+ if (r.unplanned.length === 0) console.log(" every spec stating criteria places them.");
185
+ return 0;
186
+ }
138
187
 
139
188
  export async function main(argv: string[], gh: PlanSpecGitHub = LIVE_GITHUB): Promise<number> {
140
189
  let parsed;
@@ -144,8 +193,10 @@ export async function main(argv: string[], gh: PlanSpecGitHub = LIVE_GITHUB): Pr
144
193
  options: {
145
194
  repo: { type: "string" },
146
195
  prefix: { type: "string" },
196
+ "rename-from": { type: "string" },
147
197
  write: { type: "boolean", default: false },
148
198
  json: { type: "boolean", default: false },
199
+ coverage: { type: "boolean", default: false },
149
200
  "project-root": { type: "string" },
150
201
  },
151
202
  allowPositionals: true,
@@ -159,6 +210,18 @@ export async function main(argv: string[], gh: PlanSpecGitHub = LIVE_GITHUB): Pr
159
210
  }
160
211
 
161
212
  const { values, positionals } = parsed;
213
+ // Before the spec argument is demanded: --coverage is the whole-tree
214
+ // reading and there is no one spec it could be given.
215
+ if (values.coverage) {
216
+ if (positionals.length > 0) {
217
+ return refuse(
218
+ values.json,
219
+ `--coverage reads every spec, so it takes none; got ${JSON.stringify(positionals[0])}`,
220
+ true,
221
+ );
222
+ }
223
+ return reportCoverage(values["project-root"] ?? process.cwd(), values.json);
224
+ }
162
225
  const specArg = positionals[0];
163
226
  if (!specArg) {
164
227
  return refuse(values.json, `no spec given`, true);
@@ -180,6 +243,28 @@ export async function main(argv: string[], gh: PlanSpecGitHub = LIVE_GITHUB): Pr
180
243
  );
181
244
  }
182
245
  const prefix = prefixRead.prefix;
246
+ // #2124: the old family is read exactly as --prefix is, because it is one.
247
+ // Blank would adopt nothing and plan the creates a rename exists to avoid.
248
+ // Equal to --prefix would adopt nothing either, and say it had renamed.
249
+ let renameFrom: string | undefined;
250
+ if (values["rename-from"] !== undefined) {
251
+ const fromRead = readMilestonePrefix(values["rename-from"]);
252
+ if (fromRead.kind !== "given") {
253
+ return refuse(
254
+ values.json,
255
+ `--rename-from was given as ${JSON.stringify(values["rename-from"])}, which is blank.`,
256
+ true,
257
+ );
258
+ }
259
+ if (fromRead.prefix === prefix) {
260
+ return refuse(
261
+ values.json,
262
+ `--rename-from ${JSON.stringify(fromRead.prefix)} names the same family as --prefix; there is nothing to rename.`,
263
+ true,
264
+ );
265
+ }
266
+ renameFrom = fromRead.prefix;
267
+ }
183
268
  const repo = values.repo ?? process.env.GITHUB_REPOSITORY;
184
269
  if (!repo) {
185
270
  return refuse(values.json, `--repo is required (or set GITHUB_REPOSITORY)`, true);
@@ -243,7 +328,24 @@ export async function main(argv: string[], gh: PlanSpecGitHub = LIVE_GITHUB): Pr
243
328
  // ── Step 2: what the milestones should be ────────────────────────────────
244
329
  const client = gh.createClient();
245
330
  const live = await gh.listMilestones(client, repo);
246
- const { actions, unmanaged } = milestonePlan(content, live, prefix);
331
+ const { actions, unmanaged, conflicts } = milestonePlan(content, live, prefix, renameFrom);
332
+ // #2124: a phase both families hold cannot be renamed into without
333
+ // stranding one milestone's issues, and which to keep is a person's call.
334
+ // Refused before the coverage read and before any write.
335
+ if (conflicts.length > 0) {
336
+ return refuse(
337
+ values.json,
338
+ `${conflicts.length} phase(s) have a milestone in both ${JSON.stringify(prefix)} and ` +
339
+ `${JSON.stringify(renameFrom)}, so neither can be picked. Nothing was written:\n` +
340
+ conflicts
341
+ .map(
342
+ c =>
343
+ ` Phase ${c.phase}: #${c.current.number} ${c.current.title} and ` +
344
+ `#${c.previous.number} ${c.previous.title}`,
345
+ )
346
+ .join("\n"),
347
+ );
348
+ }
247
349
 
248
350
  // ── Step 3, reported not enforced: what no open issue names ──────────────
249
351
  const open = await gh.listOpenIssues(client, repo, 100);