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
@@ -34,7 +34,7 @@
34
34
  * self-contained.
35
35
  */
36
36
  import { spawnSync } from "child_process";
37
- import { readFileSync } from "fs";
37
+ import { readFileSync, rmSync, writeFileSync } from "fs";
38
38
  import { join } from "path";
39
39
  import { parseArgs } from "util";
40
40
 
@@ -135,6 +135,182 @@ export interface BoardSnapshot {
135
135
  * RESOLVE to. See {@link resolvableBlocker}.
136
136
  */
137
137
  closedBlockers?: number[];
138
+
139
+ /**
140
+ * EVERY spec in the tree and whether its criteria are placed — SC-2615.
141
+ *
142
+ * The five readings above are engine-scoped: `phases` comes from the one
143
+ * spec named in `board.engineSpec`, so a spec with no `### Phase placement`
144
+ * table contributes no phases, raises no milestone, appears in no lane and
145
+ * is indistinguishable from a spec with no work left. That is the
146
+ * flattering reading of the two. 1 of 26 specs had a table on 2026-10-29.
147
+ *
148
+ * **Absent means the sweep was never taken**, and `spec-placement` goes
149
+ * UNMEASURED — same convention as {@link closedBlockers}, and for the same
150
+ * reason: an absent sweep and a tree of fully-placed specs produce the
151
+ * identical empty list.
152
+ */
153
+ specPlacements?: SpecPlacementRow[];
154
+
155
+ /**
156
+ * The deferral bank — SC-2734. **Absent means it was never read**, and
157
+ * `spec-placement` goes UNMEASURED as soon as any spec declares itself
158
+ * deferred: an unread bank is not an empty one.
159
+ */
160
+ specDeferrals?: SpecDeferral[];
161
+
162
+ /**
163
+ * EVERY open issue in the repository and what it says it serves — SC-2616.
164
+ *
165
+ * Distinct from {@link issues}, which is the engine milestone's issues. 25
166
+ * of 71 open issues named no criterion on 2026-10-30 and the two states —
167
+ * *has not said* and *says it serves none* — rendered identically, so the
168
+ * population that needs work could not be separated from the population
169
+ * that is finished thinking.
170
+ *
171
+ * **Absent means repository-wide issues were never read**, and
172
+ * `criteria-named` goes UNMEASURED.
173
+ */
174
+ repoIssues?: RepoIssueCriteria[];
175
+
176
+ /**
177
+ * The ordering the plan implies, and whether the tracker carries it — SC-2617.
178
+ *
179
+ * 0 of 71 open issues carried a `blocked by` edge on 2026-10-30, which
180
+ * makes every ordering claim prose. `blocked-by-edges` above asks the
181
+ * question of the five engine issues; this asks it of every edge the
182
+ * dependency plan derives.
183
+ *
184
+ * **Absent means the plan was never derived**, and `dependency-edges` goes
185
+ * UNMEASURED rather than reporting a tracker with no ordering as a tracker
186
+ * that needs none.
187
+ */
188
+ plannedEdges?: PlannedEdge[];
189
+
190
+ /**
191
+ * Work the repository DECLARES, and what each piece points at — SC-2752.
192
+ *
193
+ * Every unticked criterion in an in-scope spec (one that states criteria
194
+ * and is not deferred), and every open stage item in `project-state.json`.
195
+ * A commitment written into a file is indistinguishable from one never
196
+ * made until something reads the file and asks for its tracker object;
197
+ * thirteen were found by hand on 2026-11-09 (#1938-#1946, #1948-#1951).
198
+ *
199
+ * **Absent means the producer never read it**, and `declared-work` goes
200
+ * UNMEASURED — same convention as {@link closedBlockers}.
201
+ */
202
+ declaredWork?: DeclaredWork[];
203
+ }
204
+
205
+ /** One piece of declared work — SC-2752. */
206
+ export interface DeclaredWork {
207
+ /** `criterion`: an unticked criterion in an in-scope spec. `stage-item`: an open item in project-state.json. */
208
+ kind: "criterion" | "stage-item";
209
+ /** The criterion id, or the stage item id. */
210
+ id: string;
211
+ /** Where it is declared: the spec's repo-relative path, or `project-state.json`. */
212
+ source: string;
213
+ /**
214
+ * A stage item's own `issue` field, or `null` when it names none. Absent on
215
+ * a criterion, which is accounted for by an open issue NAMING it, read from
216
+ * {@link BoardSnapshot.repoIssues} — the one decider of what an issue names.
217
+ */
218
+ issue?: number | null;
219
+ }
220
+
221
+ /**
222
+ * The declared work no open issue accounts for, in declaration order — SC-2752.
223
+ *
224
+ * A criterion is accounted for when some open issue names it; a stage item
225
+ * when its `issue` is an OPEN issue. A stage item pointing at a closed or
226
+ * nonexistent issue names nothing: the work it declared is still not done and
227
+ * the tracker no longer says so, which is the `readsIssueRefs` battery's
228
+ * dangling reference.
229
+ */
230
+ export function declaredWorkUnaccounted(b: BoardSnapshot): DeclaredWork[] {
231
+ const open = new Set((b.repoIssues ?? []).map(i => i.number));
232
+ const named = new Set((b.repoIssues ?? []).flatMap(i => i.names));
233
+ return (b.declaredWork ?? []).filter(w =>
234
+ w.kind === "criterion" ? !named.has(w.id) : !(typeof w.issue === "number" && open.has(w.issue)),
235
+ );
236
+ }
237
+
238
+ /** One spec in the repository-wide placement sweep — SC-2615. */
239
+ export interface SpecPlacementRow {
240
+ /** Repo-relative, as `lib/spec-placement.ts`'s sweep spells it. */
241
+ path: string;
242
+ /**
243
+ * `NO_CRITERIA` is separate from `UNPLANNED` deliberately: a spec that
244
+ * states nothing to place genuinely has no work in it, and a spec that
245
+ * states twelve and places none has twelve. `UNREADABLE` makes the whole
246
+ * reading unmeasured rather than shortening the list, because a shorter
247
+ * list is exactly what a tree with fewer specs produces.
248
+ */
249
+ state: "PLANNED" | "UNPLANNED" | "NO_CRITERIA" | "UNREADABLE";
250
+ /** How many criteria the spec states, and how many its table places. */
251
+ criteria: number;
252
+ placed: number;
253
+ /** The spec declares `board-scope: deferred` in its frontmatter — SC-2734. */
254
+ deferred?: boolean;
255
+ }
256
+
257
+ /** One entry in the deferral bank, `.claude/spec-deferral-ratchet.json` — SC-2734. */
258
+ export interface SpecDeferral {
259
+ path: string;
260
+ criteria: number;
261
+ }
262
+
263
+ /**
264
+ * The deferred rows that disagree with the bank, by name — SC-2734.
265
+ *
266
+ * An EQUALITY in both directions and on the count: a spec deferred that the
267
+ * bank does not hold, a banked spec no longer deferred, and a deferred spec
268
+ * whose criteria count moved are each a difference. So a member swapped for
269
+ * another reads as two differences, never as an unchanged population.
270
+ */
271
+ export function deferralDifferences(rows: readonly SpecPlacementRow[], bank: readonly SpecDeferral[]): string[] {
272
+ const live = new Map(rows.filter(r => r.deferred === true).map(r => [r.path, r.criteria]));
273
+ const banked = new Map(bank.map(d => [d.path, d.criteria]));
274
+ const out: string[] = [];
275
+ // A path banked twice is a bank that disagrees with itself. The Map keeps
276
+ // only the last entry, so without this the other one vanishes unread.
277
+ const seen = new Set<string>();
278
+ for (const d of bank) {
279
+ if (seen.has(d.path)) out.push(`${d.path} is in the bank more than once`);
280
+ seen.add(d.path);
281
+ }
282
+ for (const [path, n] of live) {
283
+ if (!banked.has(path)) out.push(`${path} is deferred and not in the bank`);
284
+ else if (banked.get(path) !== n) out.push(`${path} states ${n} criteria and the bank holds ${banked.get(path)}`);
285
+ }
286
+ for (const path of banked.keys()) if (!live.has(path)) out.push(`${path} is in the bank and no longer deferred`);
287
+ return out;
288
+ }
289
+
290
+ /** One open issue, and the criteria it names — SC-2616. */
291
+ export interface RepoIssueCriteria {
292
+ number: number;
293
+ /** The criterion ids the issue names. Empty is a BLANK cell, not a denial. */
294
+ names: string[];
295
+ /**
296
+ * Set when the issue declares that it serves no criterion.
297
+ *
298
+ * This is the whole point of the criterion: `names: []` with this false is
299
+ * an issue nobody has answered for, and `names: []` with it true is a
300
+ * decision somebody made. Folding them together is what #1717 found
301
+ * already folded.
302
+ */
303
+ servesNone: boolean;
304
+ }
305
+
306
+ /** One edge the dependency plan derives, and whether the tracker has it — SC-2617. */
307
+ export interface PlannedEdge {
308
+ /** The issue that should carry the edge. */
309
+ blocked: number;
310
+ /** The issue it should be blocked by. */
311
+ blocker: number;
312
+ /** True when the tracker already carries this exact edge. */
313
+ present: boolean;
138
314
  }
139
315
 
140
316
  export type ReadingStatus = "met" | "short" | "unmeasured";
@@ -148,6 +324,17 @@ export interface Reading {
148
324
  measured: number;
149
325
  target: number;
150
326
  why: string;
327
+ /**
328
+ * The rows that are short, by name. Empty when the reading is met, and
329
+ * empty for a reading that has no way to name them.
330
+ *
331
+ * A ratio is not a refusal somebody can act on. SC-2615 and SC-2616 both
332
+ * say so in their own words — *"or the spec is reported UNPLANNED by
333
+ * name"*, *"reported as a refusal naming the issue"* — and `23 of 26`
334
+ * names nothing. Computed only when the reading is short, so a met
335
+ * reading cannot pay for a list nobody reads.
336
+ */
337
+ offenders: string[];
151
338
  }
152
339
 
153
340
  interface ReadingSpec {
@@ -184,6 +371,15 @@ interface ReadingSpec {
184
371
  unreadable?: (board: BoardSnapshot) => string | null;
185
372
  /** How many of `target` are conformant, and out of how many. */
186
373
  measure: (board: BoardSnapshot) => { measured: number; target: number };
374
+ /**
375
+ * The non-conformant rows, named. Consulted ONLY when the reading is
376
+ * short, so it never costs a met run and can never change a verdict.
377
+ *
378
+ * A reading with no `offenders` of its own prints a ratio, which is what
379
+ * the five engine readings did and still do. The three repository-wide
380
+ * ones have populations in the dozens, where a ratio is unactionable.
381
+ */
382
+ offenders?: (board: BoardSnapshot) => string[];
187
383
  }
188
384
 
189
385
  /** The issue numbers actually on the board, for resolving a reference. */
@@ -347,6 +543,162 @@ export const READINGS: readonly ReadingSpec[] = [
347
543
  return { measured: b.issues.filter(i => i.labels.includes(label)).length, target: b.issues.length };
348
544
  },
349
545
  },
546
+ {
547
+ name: "spec-placement",
548
+ item: "E1",
549
+ what: "every criterion in every testable spec sits in a phase, or its spec is named UNPLANNED",
550
+ readsIssueRefs: false,
551
+ // Counted in CRITERIA, not specs — the same choice B1 makes and for the
552
+ // same reason. A spec stating fourteen unplaced criteria and one stating
553
+ // a single unplaced criterion are not the same amount of plan with no
554
+ // home, and `25 of 26 specs` would call a tree conformant while the
555
+ // largest body of unplanned work in it sat outside every phase.
556
+ //
557
+ // `NO_CRITERIA` specs contribute 0 to both sides. A spec with nothing to
558
+ // place is neither conformant nor short; putting it in the denominator
559
+ // would make the reading unsatisfiable, and putting it in the numerator
560
+ // would let a tree of empty specs read as fully planned.
561
+ unreadable: b => {
562
+ if (b.specPlacements === undefined) {
563
+ return "the specs/ sweep was never taken, so no spec's placement was read — that is a " +
564
+ "producer that did not look, not a tree whose specs are all placed";
565
+ }
566
+ // ONE unreadable spec makes the whole reading unmeasured, not a
567
+ // shorter list — `lib/spec-placement.ts` takes the same position, and
568
+ // a shorter list is exactly what a tree with fewer specs produces.
569
+ const broken = b.specPlacements.filter(s => s.state === "UNREADABLE").map(s => s.path);
570
+ if (broken.length > 0) {
571
+ return `${broken.length} spec(s) could not be read (${broken.slice(0, 5).join(", ")}` +
572
+ `${broken.length > 5 ? ", …" : ""}), so the sweep covers an unknown fraction of the tree`;
573
+ }
574
+ // SC-2734. A deferred spec leaves the measure only when the bank agrees
575
+ // with it exactly; otherwise the population is not one anybody banked.
576
+ const anyDeferred = b.specPlacements.some(s => s.deferred === true);
577
+ if (anyDeferred && b.specDeferrals === undefined) {
578
+ return "specs declare themselves deferred and the deferral bank (.claude/spec-deferral-ratchet.json) " +
579
+ "was not read, so the population being measured is not one anybody banked";
580
+ }
581
+ const diff = deferralDifferences(b.specPlacements, b.specDeferrals ?? []);
582
+ return diff.length === 0
583
+ ? null
584
+ : `the deferred specs disagree with .claude/spec-deferral-ratchet.json: ${diff.join("; ")}`;
585
+ },
586
+ measure: b => {
587
+ const specs = b.specPlacements!.filter(s => s.state !== "NO_CRITERIA" && s.deferred !== true);
588
+ return {
589
+ measured: specs.reduce((n, s) => n + s.placed, 0),
590
+ target: specs.reduce((n, s) => n + s.criteria, 0),
591
+ };
592
+ },
593
+ offenders: b =>
594
+ b.specPlacements!
595
+ .filter(s => s.state === "UNPLANNED" && s.deferred !== true)
596
+ .map(s => `${s.path} — ${s.criteria - s.placed} of ${s.criteria} criteria in no phase`),
597
+ },
598
+ {
599
+ name: "criteria-named",
600
+ item: "E2",
601
+ what: "every open issue names the criteria it serves, or declares that it serves none",
602
+ readsIssueRefs: false,
603
+ // A DECLARED `servesNone` counts; a blank cell does not. Those are the
604
+ // two states SC-2616 exists to separate, and the whole criterion is that
605
+ // they rendered identically — 25 of 71 open issues named nothing on
606
+ // 2026-10-30 and nothing could say which of them had been decided.
607
+ //
608
+ // Reading `names.length > 0 || servesNone` rather than `names.length > 0
609
+ // || names !== undefined` on purpose: an issue whose body says nothing
610
+ // is not an issue that says it serves nothing, and a normaliser cannot
611
+ // invent the difference.
612
+ unreadable: b =>
613
+ b.repoIssues === undefined
614
+ ? "the repository's open issues were never read, so no issue's criteria were seen — " +
615
+ "`issues` above is the engine milestone only, which is a different population"
616
+ : null,
617
+ measure: b => ({
618
+ measured: b.repoIssues!.filter(i => i.names.length > 0 || i.servesNone).length,
619
+ target: b.repoIssues!.length,
620
+ }),
621
+ offenders: b =>
622
+ b.repoIssues!
623
+ .filter(i => i.names.length === 0 && !i.servesNone)
624
+ .map(i => `#${i.number} — names no criterion and does not declare that it serves none`),
625
+ },
626
+ {
627
+ name: "dependency-edges",
628
+ item: "E3",
629
+ what: "every ordering the plan derives is a blocked-by edge on the tracker, so what is next is computed",
630
+ readsIssueRefs: true,
631
+ // #2024: the plan is repository-wide and chains phases WITHIN each
632
+ // milestone family (`familyOf`, `lib/spec-placement.ts`). #1903 wrote
633
+ // this reading over a family-blind plan, measured 129 of 154 because
634
+ // `Convergence Phase N` was chained to `Pipeline Phase N-1`, and withdrew
635
+ // it at review round 3. Family-aware it read 180 of 191, all eleven gaps
636
+ // on one Convergence issue, and `plan-deps --milestone-prefix Convergence
637
+ // --write` closed them.
638
+ //
639
+ // BOTH endpoints have to resolve, and that is why this carries
640
+ // `readsIssueRefs`. An edge naming an issue that is not in the open
641
+ // population points at something that can never close, so the blocked
642
+ // issue never surfaces as next — the graph is wrong in the one direction
643
+ // this reading exists to rule out. Rounds 1, 2 and 5 of #1697 were that
644
+ // hole found three times, once per reading that resolved a number
645
+ // without checking it.
646
+ //
647
+ // Resolved against `repoIssues`, not `onBoard`: the plan is repo-wide
648
+ // and `issues` is the engine milestone, so resolving against the engine
649
+ // population would report every edge outside it as dangling.
650
+ unreadable: b => {
651
+ if (b.plannedEdges === undefined) {
652
+ return "the dependency plan was never derived, so no ordering was compared against the " +
653
+ "tracker — a tracker with no edges is not a tracker that needs none";
654
+ }
655
+ return b.repoIssues === undefined
656
+ ? "the repository's open issues were never read, so an edge pointing at a number cannot " +
657
+ "be told from an edge pointing at nothing"
658
+ : null;
659
+ },
660
+ measure: b => {
661
+ const open = new Set(b.repoIssues!.map(i => i.number));
662
+ return {
663
+ measured: b.plannedEdges!.filter(e => e.present && open.has(e.blocked) && open.has(e.blocker)).length,
664
+ target: b.plannedEdges!.length,
665
+ };
666
+ },
667
+ offenders: b => {
668
+ const open = new Set(b.repoIssues!.map(i => i.number));
669
+ return b.plannedEdges!
670
+ .filter(e => !(e.present && open.has(e.blocked) && open.has(e.blocker)))
671
+ .map(e =>
672
+ !open.has(e.blocked) || !open.has(e.blocker)
673
+ ? `#${e.blocked} blocked by #${e.blocker} — ${!open.has(e.blocked) ? `#${e.blocked}` : `#${e.blocker}`} is not an open issue, so this edge resolves to nothing`
674
+ : `#${e.blocked} blocked by #${e.blocker} — the plan derives it and the tracker does not carry it`,
675
+ );
676
+ },
677
+ },
678
+ {
679
+ name: "declared-work",
680
+ item: "SC-2752",
681
+ what: "every unticked criterion in an in-scope spec and every open stage item names an open issue",
682
+ // A stage item's `issue` is an issue number, validated against the OPEN
683
+ // set in `declaredWorkUnaccounted` — so this joins the battery's
684
+ // dangling-reference sweep rather than crediting a pointer to nothing.
685
+ readsIssueRefs: true,
686
+ // Both halves of the question must have been read. Declared work with no
687
+ // issue set to resolve it against would blame every row on a lookup that
688
+ // never happened; an issue set with no declared work has nothing to ask.
689
+ unreadable: b =>
690
+ b.declaredWork === undefined
691
+ ? "declared work was never read — no unticked criteria and no stage items reached the snapshot, " +
692
+ "which is not the same as a repository that declares none"
693
+ : b.repoIssues === undefined
694
+ ? "open issues were never read, so whether any of them accounts for the declared work is unknown"
695
+ : null,
696
+ measure: b => {
697
+ const total = b.declaredWork!.length;
698
+ return { measured: total - declaredWorkUnaccounted(b).length, target: total };
699
+ },
700
+ offenders: b => declaredWorkUnaccounted(b).map(w => `${w.id} (${w.source}) names no open issue`),
701
+ },
350
702
  ];
351
703
 
352
704
  export const READING_NAMES: readonly string[] = READINGS.map(r => r.name);
@@ -365,16 +717,32 @@ export const READING_NAMES: readonly string[] = READINGS.map(r => r.name);
365
717
  export function takeReading(spec: ReadingSpec, board: BoardSnapshot | null): Reading {
366
718
  const base = { name: spec.name, item: spec.item, what: spec.what };
367
719
  if (board === null) {
368
- return { ...base, status: "unmeasured", measured: 0, target: 0, why: `no board snapshot — ${spec.item} has not wired this reading's source yet` };
720
+ // **THE REASON NAMES THE CALLER, NOT THE READING.** This said
721
+ // `${spec.item} has not wired this reading's source yet` — a claim that
722
+ // the reading is unimplemented — for every caller that simply had no
723
+ // board to hand it. `main` can no longer reach this arm at all (#1718:
724
+ // every source either produces a board or returns a reason), so the one
725
+ // way here is an API caller passing null, and that is what it now says.
726
+ return { ...base, status: "unmeasured", measured: 0, target: 0, why: "no board snapshot was passed to this reading, so nothing was measured — that is a caller with no board, not a board with nothing on it", offenders: [] };
369
727
  }
370
728
  const why = spec.unreadable?.(board) ?? null;
371
- if (why !== null) return { ...base, status: "unmeasured", measured: 0, target: 0, why };
729
+ if (why !== null) return { ...base, status: "unmeasured", measured: 0, target: 0, why, offenders: [] };
372
730
  const { measured, target } = spec.measure(board);
373
731
  if (target === 0) {
374
- return { ...base, status: "unmeasured", measured, target, why: "the board carries nothing for this reading to count, so 0 of 0 is not a pass" };
732
+ return { ...base, status: "unmeasured", measured, target, why: "the board carries nothing for this reading to count, so 0 of 0 is not a pass", offenders: [] };
375
733
  }
376
- if (measured >= target) return { ...base, status: "met", measured, target, why: `${measured} of ${target}` };
377
- return { ...base, status: "short", measured, target, why: `${measured} of ${target} — ${target - measured} short` };
734
+ if (measured >= target) return { ...base, status: "met", measured, target, why: `${measured} of ${target}`, offenders: [] };
735
+ // Named only here. A met reading never pays for the list, and an
736
+ // UNMEASURED one must not print rows — it did not read the population it
737
+ // would be naming them out of.
738
+ return {
739
+ ...base,
740
+ status: "short",
741
+ measured,
742
+ target,
743
+ why: `${measured} of ${target} — ${target - measured} short`,
744
+ offenders: spec.offenders?.(board) ?? [],
745
+ };
378
746
  }
379
747
 
380
748
  export function takeReadings(board: BoardSnapshot | null): Reading[] {
@@ -386,9 +754,23 @@ export function conformant(readings: readonly Reading[]): boolean {
386
754
  return readings.length > 0 && readings.every(r => r.status === "met");
387
755
  }
388
756
 
757
+ /**
758
+ * How many offending rows a short reading prints before it stops.
759
+ *
760
+ * A cap, not a sample: the line below says how many were withheld, so the
761
+ * reader is never told a truncated list is the whole one.
762
+ */
763
+ export const OFFENDERS_SHOWN = 10;
764
+
389
765
  export function formatReading(r: Reading): string {
390
766
  const mark = r.status === "met" ? "MET " : r.status === "short" ? "SHORT " : "UNMEASURED ";
391
- return `${mark} ${r.name.padEnd(20)} ${r.why}\n ${r.what} [${r.item}]`;
767
+ const head = `${mark} ${r.name.padEnd(20)} ${r.why}\n ${r.what} [${r.item}]`;
768
+ if (r.offenders.length === 0) return head;
769
+ const shown = r.offenders.slice(0, OFFENDERS_SHOWN).map(o => `\n ${o}`).join("");
770
+ const rest = r.offenders.length > OFFENDERS_SHOWN
771
+ ? `\n … and ${r.offenders.length - OFFENDERS_SHOWN} more`
772
+ : "";
773
+ return `${head}${shown}${rest}`;
392
774
  }
393
775
 
394
776
  /**
@@ -461,6 +843,58 @@ const normalisePhase = (v: unknown): BoardPhase | null => {
461
843
  };
462
844
  };
463
845
 
846
+ /**
847
+ * The four states `placementCoverage` emits, spelled out for the same reason
848
+ * {@link MILESTONE_STATES} is: an unknown fifth would fall into the
849
+ * not-PLANNED bucket and read as an honest UNPLANNED instead of the row
850
+ * nobody can interpret that it is.
851
+ */
852
+ const PLACEMENT_STATES = ["PLANNED", "UNPLANNED", "NO_CRITERIA", "UNREADABLE"] as const;
853
+
854
+ const normaliseSpecPlacement = (v: unknown): SpecPlacementRow | null => {
855
+ if (typeof v !== "object" || v === null) return null;
856
+ const s = v as Partial<SpecPlacementRow>;
857
+ if (typeof s.path !== "string") return null;
858
+ const state = PLACEMENT_STATES.find(x => x === s.state);
859
+ if (state === undefined) return null;
860
+ const criteria = typeof s.criteria === "number" ? s.criteria : 0;
861
+ const placed = typeof s.placed === "number" ? s.placed : 0;
862
+ // A row claiming more placed than stated would let one spec carry another
863
+ // spec's shortfall, and the sum is the whole reading.
864
+ if (criteria < 0 || placed < 0 || placed > criteria) return null;
865
+ return { path: s.path, state, criteria, placed, ...(s.deferred === true ? { deferred: true } : {}) };
866
+ };
867
+
868
+ const normaliseDeferral = (v: unknown): SpecDeferral | null => {
869
+ if (typeof v !== "object" || v === null) return null;
870
+ const d = v as Partial<SpecDeferral>;
871
+ return typeof d.path === "string" && Number.isInteger(d.criteria) ? { path: d.path, criteria: d.criteria as number } : null;
872
+ };
873
+
874
+ const normaliseRepoIssue = (v: unknown): RepoIssueCriteria | null => {
875
+ if (typeof v !== "object" || v === null) return null;
876
+ const i = v as Partial<RepoIssueCriteria>;
877
+ if (typeof i.number !== "number") return null;
878
+ return {
879
+ number: i.number,
880
+ names: asList<string>(i.names).filter(n => typeof n === "string" && n.trim() !== ""),
881
+ // `=== true`, so a producer that omits the key produces a BLANK cell
882
+ // rather than a declaration. The omission must not be able to say
883
+ // something the issue did not.
884
+ servesNone: i.servesNone === true,
885
+ };
886
+ };
887
+
888
+ const normalisePlannedEdge = (v: unknown): PlannedEdge | null => {
889
+ if (typeof v !== "object" || v === null) return null;
890
+ const e = v as Partial<PlannedEdge>;
891
+ if (typeof e.blocked !== "number" || typeof e.blocker !== "number") return null;
892
+ // `=== true` again: an edge whose presence nobody recorded has not been
893
+ // found on the tracker, and reading the omission as present would credit
894
+ // the reading for an ordering that is not there.
895
+ return { blocked: e.blocked, blocker: e.blocker, present: e.present === true };
896
+ };
897
+
464
898
  /**
465
899
  * A board, or the reason there is not one. Never a bare null.
466
900
  *
@@ -600,6 +1034,46 @@ export function readSnapshotText(text: string): SnapshotRead {
600
1034
  // reports on, so writing the key unconditionally would make a tree that
601
1035
  // never configured a queue indistinguishable from one that did.
602
1036
  const queue = typeof raw.queueLabel === "string" ? { queueLabel: raw.queueLabel.trim() } : {};
1037
+
1038
+ // The three repository-wide populations, carried the same present-only
1039
+ // way and for the same reason: absence IS the reading. They are NOT in
1040
+ // the required list above, because adding a required population makes
1041
+ // every snapshot written before today unreadable BY NAME — which is the
1042
+ // documented behaviour and the right one for a population every reading
1043
+ // depends on, and the wrong one here, where exactly one reading does.
1044
+ //
1045
+ // Each is validated into its own shape rather than trusted. A row this
1046
+ // command cannot identify is DROPPED from the population rather than
1047
+ // refusing the board, which is deliberate and is the opposite of the rule
1048
+ // for `issues`: a dropped row shortens a denominator, so the reading gets
1049
+ // EASIER — and that is why `specPlacements` carries `UNREADABLE` as a
1050
+ // state rather than relying on the row vanishing. A producer emitting
1051
+ // malformed rows is caught by its own tests, not by shortening a ratio
1052
+ // here where no reader would see it.
1053
+ const placements = Array.isArray(raw.specPlacements)
1054
+ ? { specPlacements: raw.specPlacements.map(normaliseSpecPlacement).filter((s): s is SpecPlacementRow => s !== null) }
1055
+ : {};
1056
+ // SC-2734. A malformed bank entry is DROPPED, which can only add a
1057
+ // difference, so it refuses rather than shortening the comparison.
1058
+ const deferrals = Array.isArray(raw.specDeferrals)
1059
+ ? { specDeferrals: raw.specDeferrals.map(normaliseDeferral).filter((d): d is SpecDeferral => d !== null) }
1060
+ : {};
1061
+ const repoIssues = Array.isArray(raw.repoIssues)
1062
+ ? { repoIssues: raw.repoIssues.map(normaliseRepoIssue).filter((i): i is RepoIssueCriteria => i !== null) }
1063
+ : {};
1064
+ const edges = Array.isArray(raw.plannedEdges)
1065
+ ? { plannedEdges: raw.plannedEdges.map(normalisePlannedEdge).filter((e): e is PlannedEdge => e !== null) }
1066
+ : {};
1067
+ // SC-2752. ONE malformed row makes the whole population unread, the
1068
+ // opposite of the drop rule above, because here a dropped row shortens
1069
+ // exactly the list the reading blames: a declared item the parser could not
1070
+ // identify would vanish from `declared-work` and the reading would get
1071
+ // easier. Omitting the key is UNMEASURED, which is the honest reading of a
1072
+ // population this command could not fully identify.
1073
+ const declaredRows = Array.isArray(raw.declaredWork) ? raw.declaredWork.map(normaliseDeclaredWork) : null;
1074
+ const declared =
1075
+ declaredRows !== null && declaredRows.every(w => w !== null) ? { declaredWork: declaredRows as DeclaredWork[] } : {};
1076
+
603
1077
  return {
604
1078
  board: {
605
1079
  issues: issues as BoardIssue[],
@@ -607,11 +1081,29 @@ export function readSnapshotText(text: string): SnapshotRead {
607
1081
  phases: phases as BoardPhase[],
608
1082
  ...closed,
609
1083
  ...queue,
1084
+ ...placements,
1085
+ ...deferrals,
1086
+ ...repoIssues,
1087
+ ...edges,
1088
+ ...declared,
610
1089
  },
611
1090
  why: null,
612
1091
  };
613
1092
  }
614
1093
 
1094
+ /** One declared-work row, or `null` for one this command cannot identify — SC-2752. */
1095
+ function normaliseDeclaredWork(raw: unknown): DeclaredWork | null {
1096
+ if (raw === null || typeof raw !== "object") return null;
1097
+ const r = raw as Record<string, unknown>;
1098
+ if (typeof r.id !== "string" || r.id === "" || typeof r.source !== "string") return null;
1099
+ if (r.kind === "criterion") return { kind: "criterion", id: r.id, source: r.source };
1100
+ if (r.kind !== "stage-item") return null;
1101
+ if (r.issue === null || r.issue === undefined) return { kind: "stage-item", id: r.id, source: r.source, issue: null };
1102
+ return typeof r.issue === "number" && Number.isInteger(r.issue)
1103
+ ? { kind: "stage-item", id: r.id, source: r.source, issue: r.issue }
1104
+ : null;
1105
+ }
1106
+
615
1107
  /**
616
1108
  * Run the producer and read what it wrote — SPAWNED, never imported.
617
1109
  *
@@ -625,17 +1117,72 @@ export function readSnapshotText(text: string): SnapshotRead {
625
1117
  * Which also means a mutant cannot use this: its `import.meta.dir` is the
626
1118
  * temp directory and the spawn fails. The battery uses `--snapshot`, which
627
1119
  * is why that stays the only source the negative cases touch.
1120
+ *
1121
+ * ## `notes` exists because the producer's stderr used to be thrown away
1122
+ *
1123
+ * Every failure arm below quotes `r.stderr`; the SUCCESS arm read `r.stdout`
1124
+ * and dropped the rest on the floor. So on the one path anybody runs daily,
1125
+ * the producer's provenance — which tree the spec came from (D3), which
1126
+ * inputs were resolved from config rather than typed, which readings it
1127
+ * could not take — was written, captured, and discarded.
1128
+ *
1129
+ * It is RETURNED rather than written here so a case can assert on it. A
1130
+ * `process.stderr.write` inside this function is invisible to an in-process
1131
+ * test, which is how it would have gone uncovered a second time.
1132
+ *
1133
+ * `producer` is a parameter for the same reason: pointed at a stub, a case
1134
+ * can drive the success arm without a network, which no case could do while
1135
+ * the path was a constant.
628
1136
  */
629
- function produceBoard(flags: Flags): { board: BoardSnapshot | null; error: string | null } {
630
- const { spec, prefix, repo } = flags;
631
- // `=== undefined` is not enough: an empty `--prefix ""` reaches the
632
- // producer, which refuses it, and the reader then reports the CHILD's
633
- // refusal for an argument this command was handed. Same population as
634
- // plan-deps' --milestone-prefix and board-snapshot's own --prefix.
635
- if (spec === undefined || prefix === undefined || spec.trim() === "" || prefix.trim() === "") {
636
- return { board: null, error: "--produce needs a non-empty --spec <path> and --prefix <name>" };
1137
+ export const DEFAULT_PRODUCER = join(import.meta.dir, "board-snapshot.ts");
1138
+
1139
+ export function produceBoard(
1140
+ flags: Flags,
1141
+ producer: string = DEFAULT_PRODUCER,
1142
+ ): { board: BoardSnapshot | null; error: string | null; notes: string } {
1143
+ const { spec, prefix, repo, specGiven, prefixGiven, repoGiven } = flags;
1144
+ // **GIVEN-AND-BLANK REFUSES. ABSENT FORWARDS NOTHING.** These used to be
1145
+ // one case and #1718 split them, because they carry opposite
1146
+ // instructions. `--prefix ""` is somebody typing a value, and reaching
1147
+ // past it to a configured default would override a person with a file.
1148
+ // Omitting the flag entirely carries no instruction at all, so the
1149
+ // producer resolves it from `board.engineSpec` / `board.milestonePrefix`
1150
+ // and refuses by name when the config has not got it — which is how
1151
+ // `rungate board-conformance` with no arguments became a command that
1152
+ // takes its own reading instead of five UNMEASURED rows blaming itself.
1153
+ //
1154
+ // The blank arm stays for the reason it was written: an empty value
1155
+ // reaching the producer makes the reader report the CHILD's refusal for
1156
+ // an argument this command was handed. Same population as plan-deps'
1157
+ // --milestone-prefix and board-snapshot's own --prefix.
1158
+ //
1159
+ // **WRITTEN AS A SWEEP OVER EVERY FORWARDED INPUT, not a case per
1160
+ // flag.** Review of #1890 found `--repo` left out of a two-row version
1161
+ // of this list: `"" ?? env` keeps the empty string and `resolveRepoSlug`
1162
+ // reads it as "not given", so a blank reached the producer and resolved
1163
+ // this checkout's own origin. A list that enumerates the inputs cannot
1164
+ // be short by one the way three hand-written conditions can — adding a
1165
+ // fourth forwarded flag without a row here is a visible omission.
1166
+ const blank = ([
1167
+ ["--spec", specGiven, spec],
1168
+ ["--prefix", prefixGiven, prefix],
1169
+ ["--repo", repoGiven, repo],
1170
+ ] as [string, boolean, string | undefined][])
1171
+ .filter(([, given, value]) => given && (value === undefined || value.trim() === ""))
1172
+ .map(([flag]) => flag);
1173
+ if (blank.length > 0) {
1174
+ return {
1175
+ board: null,
1176
+ notes: "",
1177
+ error:
1178
+ `${blank.join(" and ")} was given with no usable value. Pass a value, or omit the flag ` +
1179
+ `entirely and the spec and prefix are read from \`board.engineSpec\` and ` +
1180
+ `\`board.milestonePrefix\` in this project's rungate config.`,
1181
+ };
637
1182
  }
638
- const args = [join(import.meta.dir, "board-snapshot.ts"), spec, "--prefix", prefix];
1183
+ const args = [producer];
1184
+ if (spec !== undefined) args.push(spec);
1185
+ if (prefix !== undefined) args.push("--prefix", prefix);
639
1186
  if (repo !== undefined) args.push("--repo", repo);
640
1187
  // A TIMEOUT, because a hang is the one failure mode every other branch
641
1188
  // here turns into a crisp refusal and this one did not. `listMilestones`
@@ -654,11 +1201,21 @@ function produceBoard(flags: Flags): { board: BoardSnapshot | null; error: strin
654
1201
  // half no input here can reach, and a clause nothing can exercise is
655
1202
  // not a guard.
656
1203
  if (r.signal !== null && r.signal !== undefined) {
1204
+ // AND WHAT THE CHILD ALREADY SAID. This was the one arm reaching
1205
+ // neither `error` nor `notes`, so the producer's provenance — the
1206
+ // `board-snapshot: resolved from…` lines, and how far it got before
1207
+ // it stuck — was discarded on exactly the failure where knowing WHERE
1208
+ // it stuck is the whole question. Every other arm below quotes it.
1209
+ // The producer redacts its own credentials before writing, so this
1210
+ // relays an already-redacted reading. Review of #1896 round 12.
1211
+ const said = (r.stderr ?? "").trim();
657
1212
  return {
658
1213
  board: null,
1214
+ notes: "",
659
1215
  error:
660
1216
  `board-snapshot was killed by ${r.signal ?? "the timeout"} after ${PRODUCE_TIMEOUT_MS}ms. A producer ` +
661
- `that hangs is UNMEASURED, not a board — an unattended loop cannot observe a wedge.`,
1217
+ `that hangs is UNMEASURED, not a board — an unattended loop cannot observe a wedge.` +
1218
+ (said === "" ? " It wrote nothing before it was killed." : ` It got as far as: ${said}`),
662
1219
  };
663
1220
  }
664
1221
  // Then a spawn that never started — no `bun` on PATH. It sets `error`
@@ -666,18 +1223,27 @@ function produceBoard(flags: Flags): { board: BoardSnapshot | null; error: strin
666
1223
  // those reports "exit none: no output" for the one failure whose cause
667
1224
  // is already in hand.
668
1225
  if (r.error) {
669
- return { board: null, error: `board-snapshot could not be started: ${r.error.message}` };
1226
+ return { board: null, notes: "", error: `board-snapshot could not be started: ${r.error.message}` };
670
1227
  }
671
1228
  if (r.status !== 0) {
1229
+ // `notes` stays EMPTY on this arm, not a second copy of the same bytes:
1230
+ // the refusal message already quotes `r.stderr`, and printing both puts
1231
+ // the producer's reason on screen twice with nothing saying they are one
1232
+ // reading.
672
1233
  return {
673
1234
  board: null,
1235
+ notes: "",
674
1236
  error: `board-snapshot refused (exit ${r.status ?? "none"}): ${(r.stderr || r.stdout || "no output").trim()}`,
675
1237
  };
676
1238
  }
1239
+ // PAST THE EXIT CODE, so `notes` carries what the producer said on the
1240
+ // path where nothing else quotes it. This is the daily path, and it is the
1241
+ // one that used to be silent.
1242
+ const notes = (r.stderr ?? "").trim();
677
1243
  const read = readSnapshotText(r.stdout);
678
1244
  return read.board === null
679
- ? { board: null, error: `board-snapshot exited 0 and what it emitted is unreadable — ${read.why}` }
680
- : { board: read.board, error: null };
1245
+ ? { board: null, notes, error: `board-snapshot exited 0 and what it emitted is unreadable — ${read.why}` }
1246
+ : { board: read.board, notes, error: null };
681
1247
  }
682
1248
 
683
1249
  /**
@@ -693,7 +1259,7 @@ function produceBoard(flags: Flags): { board: BoardSnapshot | null; error: strin
693
1259
  */
694
1260
  export const PRODUCE_TIMEOUT_MS = Number(process.env.RUNGATE_PRODUCE_TIMEOUT_MS) || 60_000;
695
1261
 
696
- interface Flags {
1262
+ export interface Flags {
697
1263
  listReadings: boolean;
698
1264
  produce: boolean;
699
1265
  snapshot?: string;
@@ -701,8 +1267,26 @@ interface Flags {
701
1267
  reading?: string;
702
1268
  readingGiven: boolean;
703
1269
  spec?: string;
1270
+ /** The flag APPEARED, whatever its value — `--spec ""` is given. */
1271
+ specGiven: boolean;
704
1272
  prefix?: string;
1273
+ prefixGiven: boolean;
705
1274
  repo?: string;
1275
+ repoGiven: boolean;
1276
+ /**
1277
+ * Where to write the readings as JSON, for a consumer that must not
1278
+ * parse this command's prose — #1889.
1279
+ *
1280
+ * `scripts/check-state-claims.ts` re-derives the figures
1281
+ * `project-state.json` states about the board, and it needs `measured`
1282
+ * and `target` as numbers. Reading them back out of `formatReading`'s
1283
+ * output would be a detector narrower than what it detects: a change to
1284
+ * the padding or the wording there would silently stop the state check
1285
+ * from seeing anything, and an extractor that matches nothing certifies
1286
+ * by counting nothing.
1287
+ */
1288
+ emitReadings?: string;
1289
+ emitReadingsGiven: boolean;
706
1290
  }
707
1291
 
708
1292
  /**
@@ -731,6 +1315,7 @@ function readFlags(argv: readonly string[]): Flags {
731
1315
  spec: { type: "string" },
732
1316
  prefix: { type: "string" },
733
1317
  repo: { type: "string" },
1318
+ "emit-readings": { type: "string" },
734
1319
  },
735
1320
  strict: false,
736
1321
  allowPositionals: true,
@@ -748,8 +1333,13 @@ function readFlags(argv: readonly string[]): Flags {
748
1333
  reading: str(values.reading),
749
1334
  readingGiven: values.reading !== undefined,
750
1335
  spec: str(values.spec),
1336
+ specGiven: values.spec !== undefined,
751
1337
  prefix: str(values.prefix),
1338
+ prefixGiven: values.prefix !== undefined,
752
1339
  repo: str(values.repo),
1340
+ repoGiven: values.repo !== undefined,
1341
+ emitReadings: str(values["emit-readings"]),
1342
+ emitReadingsGiven: values["emit-readings"] !== undefined,
753
1343
  };
754
1344
  }
755
1345
 
@@ -762,6 +1352,83 @@ export function main(argv: readonly string[]): number {
762
1352
  return REFUSE_EXIT;
763
1353
  }
764
1354
 
1355
+ // #1889, and ABOVE every early return rather than beside the write.
1356
+ //
1357
+ // `--reading` and `--list-readings` both answer and return before the
1358
+ // readings are taken as a set, so either combined with --emit-readings
1359
+ // wrote nothing — and `--list-readings` exits ZERO, so a caller running
1360
+ // `board-conformance … && check-state-claims …` proceeds onto whatever
1361
+ // that path held from an earlier run. A stale artefact consumed as live
1362
+ // is the exact defect `scripts/check-state-claims.ts` exists to catch,
1363
+ // so this command must not be the thing that creates one.
1364
+ //
1365
+ // The rule this encodes: every exit from `main` that was given
1366
+ // --emit-readings either writes the file or refuses. There is no third
1367
+ // outcome, because a caller cannot tell the third from success.
1368
+ if (flags.emitReadingsGiven && (flags.readingGiven || flags.listReadings)) {
1369
+ console.error(
1370
+ "board-conformance: --emit-readings writes the whole set; --reading takes one and " +
1371
+ "--list-readings takes none. Pass one. Combined, the file is not written, and a consumer " +
1372
+ "cannot tell that from a file written by an earlier run.",
1373
+ );
1374
+ return REFUSE_EXIT;
1375
+ }
1376
+ if (flags.emitReadingsGiven && flags.emitReadings === undefined) {
1377
+ console.error("board-conformance: --emit-readings needs a path");
1378
+ return REFUSE_EXIT;
1379
+ }
1380
+ // THE TARGET IS REMOVED BEFORE ANY SOURCE IS RESOLVED, so that no
1381
+ // refusal below can leave an earlier run's file sitting at the path.
1382
+ //
1383
+ // The flag-combination guard above only covered the combinations. The
1384
+ // likelier failure is a source that will not read — `produceBoard`
1385
+ // throwing, a snapshot that is not a board — and every one of those
1386
+ // returns before the write. A caller that logs the non-zero exit and
1387
+ // feeds the old file onward is the stale-artefact hazard this flag
1388
+ // exists to avoid creating, and "gate on the exit code" is a rule for
1389
+ // somebody else's script.
1390
+ //
1391
+ // Absent is now the only other state: a consumer reads a fresh file or
1392
+ // no file, and no file is loud.
1393
+ //
1394
+ // **The clear is also the writability probe, and that is deliberate.**
1395
+ // `rmSync(..., { force: true })` on a path whose directory does not exist
1396
+ // succeeds silently — ENOENT is exactly what `force` suppresses — so
1397
+ // clearing alone proved nothing about whether the write at the end of
1398
+ // `main` can land. A directory that is absent, read-only, or actually a
1399
+ // directory was discovered at the LAST line of a run that had already
1400
+ // produced the board: several API calls and tens of seconds spent to
1401
+ // learn something knowable in the first millisecond.
1402
+ //
1403
+ // An `existsSync(dirname(...))` would be the narrower detector: it names
1404
+ // the absent directory and misses every permission case. Writing a byte
1405
+ // and removing it asks the question that is actually being asked.
1406
+ //
1407
+ // The cost, stated: between the two calls an EMPTY file exists at the
1408
+ // path. A process killed in that window leaves one behind — and an empty
1409
+ // file is not readable JSON, so `scripts/check-state-claims.ts` refuses
1410
+ // it rather than reading it as a board. That is the direction this is
1411
+ // allowed to be wrong in.
1412
+ if (flags.emitReadingsGiven && flags.emitReadings !== undefined) {
1413
+ // Its own name, not `flags.emitReadings` a second time. The two writes
1414
+ // in this file are two different acts — a zero-byte probe that is
1415
+ // removed, and the payload at the end of `main` — and the spec-write
1416
+ // registry keys on the symbol, so sharing one would file them under a
1417
+ // single explanation.
1418
+ const probeAt = flags.emitReadings;
1419
+ try {
1420
+ writeFileSync(probeAt, "");
1421
+ rmSync(probeAt, { force: true });
1422
+ } catch (e) {
1423
+ console.error(
1424
+ `board-conformance: cannot write ${flags.emitReadings}: ${(e as Error).message}. ` +
1425
+ `Refusing before taking any reading — the path is checked first so a run that cannot ` +
1426
+ `deliver its readings does not spend the board production to find out.`,
1427
+ );
1428
+ return REFUSE_EXIT;
1429
+ }
1430
+ }
1431
+
765
1432
  if (flags.listReadings) {
766
1433
  for (const r of READINGS) console.log(`${r.name.padEnd(20)} ${r.what} [${r.item}]`);
767
1434
  return 0;
@@ -773,14 +1440,51 @@ export function main(argv: readonly string[]): number {
773
1440
  return REFUSE_EXIT;
774
1441
  }
775
1442
 
1443
+ // **THE READING NAME IS VALIDATED BEFORE ANY SOURCE IS RESOLVED.** It
1444
+ // used to be checked after, which cost nothing while a source was always
1445
+ // a file somebody passed. Once a bare run produces its own board (#1718)
1446
+ // that ordering makes a typo spend a live board fetch — several API
1447
+ // calls, tens of seconds — before saying the word is misspelt. Nothing
1448
+ // about an unknown reading depends on the board, so nothing about it
1449
+ // should wait for one.
1450
+ const named = flags.readingGiven ? READINGS.find(r => r.name === flags.reading) : undefined;
1451
+ if (flags.readingGiven && named === undefined) {
1452
+ // A typo must never read as a pass. This is the first case the mutant
1453
+ // has to fail to catch, because it is the one an agent in a loop will
1454
+ // hit by writing a reading that does not exist yet.
1455
+ console.error(
1456
+ `board-conformance: unknown reading "${flags.reading ?? ""}". Known readings: ${READING_NAMES.join(", ")}.\n` +
1457
+ `Run \`rungate board-conformance --list-readings\` for what each one measures.`,
1458
+ );
1459
+ return REFUSE_EXIT;
1460
+ }
1461
+
776
1462
  let board: BoardSnapshot | null = null;
777
1463
  let sourceFailed: string | null = null;
778
- if (flags.produce) {
779
- if (flags.snapshotGiven) {
780
- console.error("board-conformance: --produce and --snapshot are two sources. Pass one.");
781
- return REFUSE_EXIT;
782
- }
1464
+ if (flags.produce && flags.snapshotGiven) {
1465
+ console.error("board-conformance: --produce and --snapshot are two sources. Pass one.");
1466
+ return REFUSE_EXIT;
1467
+ }
1468
+ // **NO SOURCE IS NOT A SOURCE, AND IT USED TO BE TREATED AS ONE.** With
1469
+ // neither flag this fell through with `board === null` and printed five
1470
+ // UNMEASURED rows whose stated reason was `B1 has not wired this
1471
+ // reading's source yet` — a sentence about an unfinished tool, emitted by
1472
+ // a finished one, because nobody had passed a spec. It exited 1, so the
1473
+ // terminal condition was right and the diagnosis was a fabrication, which
1474
+ // is the worse half: a reader acts on the reason, not the exit code.
1475
+ //
1476
+ // Taking its own reading is the fix, not a better sentence (#1718,
1477
+ // SC-2618/SC-2619). The producer resolves the spec, the prefix and the
1478
+ // repository from the project itself and refuses naming the config key it
1479
+ // could not find, so every outcome here is now a reading or a refusal
1480
+ // that says what is missing.
1481
+ if (flags.produce || !flags.snapshotGiven) {
783
1482
  const produced = produceBoard(flags);
1483
+ // WHAT THE PRODUCER SAID, on stderr, before any verdict. It names which
1484
+ // tree the spec came from (D3) and which inputs were resolved from
1485
+ // config rather than typed — both captured and discarded until
1486
+ // 2026-11-08, on the success path and only on the success path.
1487
+ if (produced.notes !== "") console.error(produced.notes);
784
1488
  if (produced.error !== null) sourceFailed = produced.error;
785
1489
  else board = produced.board;
786
1490
  } else if (snapshotPath !== undefined) {
@@ -793,25 +1497,28 @@ export function main(argv: readonly string[]): number {
793
1497
  return REFUSE_EXIT;
794
1498
  }
795
1499
 
796
- if (flags.readingGiven) {
797
- const name = flags.reading;
798
- const spec = READINGS.find(r => r.name === name);
799
- if (!spec) {
800
- // A typo must never read as a pass. This is the first case the
801
- // mutant has to fail to catch, because it is the one an agent in a
802
- // loop will hit by writing a reading that does not exist yet.
803
- console.error(
804
- `board-conformance: unknown reading "${name ?? ""}". Known readings: ${READING_NAMES.join(", ")}.\n` +
805
- `Run \`rungate board-conformance --list-readings\` for what each one measures.`,
806
- );
807
- return REFUSE_EXIT;
808
- }
809
- const reading = takeReading(spec, board);
1500
+ if (named !== undefined) {
1501
+ const reading = takeReading(named, board);
810
1502
  console.log(formatReading(reading));
811
1503
  return reading.status === "met" ? 0 : REFUSE_EXIT;
812
1504
  }
813
1505
 
814
1506
  const readings = takeReadings(board);
1507
+ // WRITTEN BEFORE THE VERDICT, and on every path that got this far. A
1508
+ // short reading is still a reading, and a consumer that only receives
1509
+ // the file when the board is fully conformant would be unmeasured for
1510
+ // exactly as long as anything is outstanding — which is now (#1889).
1511
+ // `flags.emitReadings` is known present: the flag-combination guard at
1512
+ // the top of `main` refused a bare `--emit-readings` before any source
1513
+ // was resolved, so nothing reaches here with the flag given and no path.
1514
+ if (flags.emitReadingsGiven && flags.emitReadings !== undefined) {
1515
+ try {
1516
+ writeFileSync(flags.emitReadings, `${JSON.stringify(readings, null, 2)}\n`);
1517
+ } catch (e) {
1518
+ console.error(`board-conformance: could not write ${flags.emitReadings}: ${(e as Error).message}`);
1519
+ return REFUSE_EXIT;
1520
+ }
1521
+ }
815
1522
  for (const r of readings) console.log(formatReading(r));
816
1523
  const outstanding = readings.filter(r => r.status !== "met");
817
1524
  if (outstanding.length > 0) {