rungate 0.8.13 → 0.8.14

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 (40) hide show
  1. package/README.md +82 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  4. package/lib/ai-review-rounds.ts +99 -0
  5. package/lib/ai-review-suppression.ts +200 -21
  6. package/lib/bash-write-guard.ts +50 -5
  7. package/lib/board-flow.ts +235 -0
  8. package/lib/board-lane-health.ts +381 -0
  9. package/lib/board-mirror.ts +53 -35
  10. package/lib/board-ready-fanout.ts +56 -13
  11. package/lib/board-ready-rule.ts +545 -0
  12. package/lib/board-throughput.ts +136 -0
  13. package/lib/board-walkthrough.ts +240 -0
  14. package/lib/body-evidence.ts +203 -0
  15. package/lib/branch-protection.ts +399 -9
  16. package/lib/conformity.ts +95 -2
  17. package/lib/filing-compliance.ts +367 -0
  18. package/lib/finding-arbiter.ts +79 -5
  19. package/lib/generators/agents-md.ts +149 -0
  20. package/lib/github.ts +79 -0
  21. package/lib/graphql-cursor.ts +80 -0
  22. package/lib/issue-create-override.ts +415 -3
  23. package/lib/issue-decomposition.ts +33 -3
  24. package/lib/issue-file-overlap.ts +340 -0
  25. package/lib/issue-filing-gate.ts +173 -8
  26. package/lib/issue-repair.ts +13 -9
  27. package/lib/issue-shape.ts +196 -0
  28. package/lib/scaffold/ai-review-findings.ts +9 -1
  29. package/lib/scaffold/ai-review-step.ts +35 -1
  30. package/lib/source-census.ts +108 -0
  31. package/lib/spec-deps.ts +34 -11
  32. package/lib/spec-placement.ts +108 -0
  33. package/lib/stage-ladder.ts +28 -3
  34. package/lib/work-status.ts +423 -0
  35. package/package.json +1 -1
  36. package/scripts/ai-review-findings.ts +8 -13
  37. package/scripts/ai-review-threads.ts +16 -17
  38. package/scripts/board-mirror.ts +221 -8
  39. package/scripts/generate-code-map.ts +1 -1
  40. package/scripts/plan-spec.ts +79 -1
@@ -0,0 +1,196 @@
1
+ /**
2
+ * #1741 — what a valid issue looks like, decided in one place.
3
+ *
4
+ * ## Why this file exists at all
5
+ *
6
+ * Before it there was no decider and two half-answers.
7
+ * `.github/ISSUE_TEMPLATE/spec-work.yml` asked for five fields and
8
+ * `rungate plan-issues --decompose` emitted two of them, so a gate requiring
9
+ * the other three would have refused every row of every plan. That is why the
10
+ * recorded agreement (2026-11-03, `project-state.json`, the priority opening
11
+ * *PATH B HAS NO INTAKE*) says the form, the gate and the generator must land
12
+ * together: built apart, each grows its own notion of valid, and
13
+ * `.claude/rules/checks-must-be-able-to-fail.md`'s *two deciders that agree*
14
+ * says no behavioural test can then tell which one is live.
15
+ *
16
+ * ## The one decider is `requiredSections`
17
+ *
18
+ * Everything else in this file reads it, and every consumer reads one of
19
+ * those. `test/issue-shape.test.ts` binds all four consumers with an
20
+ * **equality** rather than a containment, which is the only form that goes
21
+ * red when this function is short-circuited to `return []` — every list
22
+ * contains the empty one, so a containment assertion certifies a decider that
23
+ * has stopped deciding.
24
+ *
25
+ * ## The second form, and what it is for
26
+ *
27
+ * `spec-work` requires *Criteria this serves*. A consumer agent reporting a
28
+ * problem upstream, and ordinary housekeeping, cannot know a criterion id —
29
+ * so until `everyday-work` existed there was no correct way to file anything
30
+ * that was not spec work, and the measured consequence was agents reaching
31
+ * for the `external-audit` label, which the same decision had ruled out.
32
+ *
33
+ * The two forms differ in exactly one field and `test/issue-shape.test.ts`
34
+ * asserts that by name. A second difference arriving later is a decision, not
35
+ * a tidy-up.
36
+ */
37
+
38
+ /** The forms. The set is closed; adding one is an edit here and a file on disk. */
39
+ export const ISSUE_FORMS = ["spec-work", "everyday-work"] as const;
40
+
41
+ export type IssueForm = (typeof ISSUE_FORMS)[number];
42
+
43
+ export interface IssueSection {
44
+ /** The `id:` of the field in the issue form, and the key everything joins on. */
45
+ readonly id: string;
46
+ /**
47
+ * The field's `label:` in the form AND its heading in a rendered body.
48
+ *
49
+ * ONE string for both deliberately. Two would let the form ask for
50
+ * *Criteria this serves* while the parser looked for *Criteria*, which is
51
+ * the same class of defect this file exists to remove, one layer down.
52
+ */
53
+ readonly label: string;
54
+ /** The forms that SHOW this field. */
55
+ readonly forms: readonly IssueForm[];
56
+ /** The forms that REQUIRE it. Always a subset of `forms`. */
57
+ readonly required: readonly IssueForm[];
58
+ }
59
+
60
+ const BOTH = ISSUE_FORMS;
61
+
62
+ /**
63
+ * Every section, in the order a form shows them.
64
+ *
65
+ * The order is load-bearing for `formTemplatePath`'s files and for
66
+ * `decomposedBody`: a reader scanning a body top to bottom meets them in this
67
+ * order, and a generator that emits them in another makes two issues that say
68
+ * the same thing look different.
69
+ */
70
+ export const ISSUE_SECTIONS: readonly IssueSection[] = [
71
+ {
72
+ id: "outcome",
73
+ label: "What must become true",
74
+ forms: BOTH,
75
+ required: BOTH,
76
+ },
77
+ {
78
+ id: "criteria",
79
+ label: "Criteria this serves",
80
+ forms: ["spec-work"],
81
+ required: ["spec-work"],
82
+ },
83
+ {
84
+ id: "files",
85
+ label: "Files this will change",
86
+ forms: BOTH,
87
+ required: BOTH,
88
+ },
89
+ {
90
+ id: "blocked-by",
91
+ label: "Blocked by",
92
+ forms: BOTH,
93
+ // Required by neither, and that is the design: empty is what puts an
94
+ // issue in the pickable set, so demanding the field would make every
95
+ // filer invent an ordering and the board would then lie about it.
96
+ required: [],
97
+ },
98
+ {
99
+ id: "proof",
100
+ label: "How we will know",
101
+ forms: BOTH,
102
+ required: BOTH,
103
+ },
104
+ ];
105
+
106
+ /**
107
+ * **THE DECIDER.** What a body must carry to be a valid issue of this form.
108
+ *
109
+ * Short-circuit this to `return []` and all four consumers go red. If one
110
+ * stays green it is a second decider and the work is not done —
111
+ * `test/issue-shape.test.ts`'s header carries the battery's terms.
112
+ */
113
+ export function requiredSections(form: IssueForm): readonly IssueSection[] {
114
+ return ISSUE_SECTIONS.filter(s => s.required.includes(form));
115
+ }
116
+
117
+ /** Every section a form shows, required or not. */
118
+ export function sectionsOf(form: IssueForm): readonly IssueSection[] {
119
+ return ISSUE_SECTIONS.filter(s => s.forms.includes(form));
120
+ }
121
+
122
+ /** The markdown heading that opens a section in a body. */
123
+ export function headingFor(section: IssueSection): string {
124
+ return `## ${section.label}`;
125
+ }
126
+
127
+ /** Where the form lives, relative to the repository root. */
128
+ export function formTemplatePath(form: IssueForm): string {
129
+ return `.github/ISSUE_TEMPLATE/${form}.yml`;
130
+ }
131
+
132
+ /**
133
+ * Every offset at which `heading` OPENS A LINE, outside any fenced block.
134
+ *
135
+ * Generalised out of `lib/issue-repair.ts`, which held the only correct
136
+ * version and held it for one hard-coded string. Its docblock records why the
137
+ * obvious `body.indexOf` is wrong, and the answer is worth keeping in one
138
+ * place: these bodies quote markdown and shell constantly, so an unanchored
139
+ * match reads *"add a `## Criteria this serves` section"* in prose, and a
140
+ * fence-blind one reads a template pasted into a code block. That was caught
141
+ * by a security review rather than by a test, and the repair it would have
142
+ * made was to REPLACE everything from the quotation to the next heading —
143
+ * which in those bodies is the measurements the repair exists to preserve.
144
+ *
145
+ * Any heading level opens a section. A body that writes `### Files this will
146
+ * change` has named the section; refusing it would be a decider narrower than
147
+ * what it detects, with nothing gained.
148
+ */
149
+ export function headingOccurrencesOf(body: string, heading: string): number[] {
150
+ const text = heading.replace(/^#+\s*/, "");
151
+ const opens = new RegExp(`^#{1,6}\\s+${escapeRegExp(text)}\\s*$`);
152
+ const out: number[] = [];
153
+ let fenced = false;
154
+ let at = 0;
155
+ for (const line of body.split("\n")) {
156
+ if (/^\s*```/.test(line)) fenced = !fenced;
157
+ else if (!fenced && opens.test(line.trimEnd())) out.push(at);
158
+ at += line.length + 1;
159
+ }
160
+ return out;
161
+ }
162
+
163
+ function escapeRegExp(s: string): string {
164
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
165
+ }
166
+
167
+ /**
168
+ * The headings a body is short, for `form`. Empty means well-formed.
169
+ *
170
+ * **A heading over nothing does not count.** A body somebody pasted the
171
+ * template into and did not fill in carries every heading and answers no
172
+ * question, and to a check that only looks for the string it is
173
+ * indistinguishable from a complete one — *assertions that hold vacuously*,
174
+ * in `.claude/rules/checks-must-be-able-to-fail.md`. So a section is present
175
+ * when there is non-blank text between its heading and the next one.
176
+ *
177
+ * Returns headings rather than ids, because the only reader that matters is
178
+ * an agent reading a refusal, and the heading is what they have to type.
179
+ */
180
+ export function missingSections(body: string, form: IssueForm): string[] {
181
+ return requiredSections(form)
182
+ .filter(s => !hasContent(body, headingFor(s)))
183
+ .map(headingFor);
184
+ }
185
+
186
+ /** True when `heading` opens a section with non-blank text under it. */
187
+ function hasContent(body: string, heading: string): boolean {
188
+ for (const at of headingOccurrencesOf(body, heading)) {
189
+ const rest = body.slice(at).split("\n").slice(1);
190
+ for (const line of rest) {
191
+ if (/^#{1,6}\s+\S/.test(line)) break; // the next section, with nothing between
192
+ if (line.trim() !== "") return true;
193
+ }
194
+ }
195
+ return false;
196
+ }
@@ -726,7 +726,15 @@ export function scopeNotSupplied(): AiReviewScopeReading {
726
726
  detail:
727
727
  `no changed-file list was given (second positional argument), so whether ` +
728
728
  `a blocking finding names a file this pull request touches was not checked. ` +
729
- `This is a reading, not a pass: the generated job does not supply the list yet`,
729
+ // #1567. This said "the generated job does not supply the list yet",
730
+ // which stopped being true when #1356 wired the writer: the step passes
731
+ // the list as a second positional today. An operator reading the old
732
+ // sentence would conclude the harness cannot do this, when the true
733
+ // state is that THIS invocation arrived without one — a different
734
+ // problem with a different fix.
735
+ `This is a reading, not a pass. The generated job passes the list as a second ` +
736
+ `positional, so an empty one here means either the step that writes it did not ` +
737
+ `run, or the adjudicator was invoked by hand`,
730
738
  };
731
739
  }
732
740
 
@@ -5803,6 +5803,22 @@ working tree disagrees with the diff about one of them. Reading one of these
5803
5803
  files to judge a change to it tells you about the base, not about this pull
5804
5804
  request.
5805
5805
 
5806
+ THE SCRATCH DIRECTORY ${AI_REVIEW_ACTION_SCRATCH} IS NOT THE EXCEPTION TO
5807
+ THAT, AND IT LOOKS LIKE ONE. The review action copies what it calls "the
5808
+ pull request's sensitive paths" there and logs that it preserved them. It
5809
+ runs AFTER the restore step above, so for every path listed here what it
5810
+ copied was already the base's copy. That directory therefore holds BASE
5811
+ content under a name that says otherwise, and it is the most convincing
5812
+ wrong answer available to you: it looks like a pre-restore snapshot and it
5813
+ is a post-restore one. A finding of the form "the author claims they changed
5814
+ this and the preserved copy shows they did not" is this trap, and it was
5815
+ filed as a blocking finding twice against a pull request whose commit did
5816
+ carry the change.
5817
+
5818
+ So THE DIFF REMAINS AUTHORITATIVE even against that directory. If you want to
5819
+ know what one of these paths contains on this pull request, the diff is the
5820
+ only reading in this checkout that can tell you.
5821
+
5806
5822
  Everywhere else in the checkout, the working tree IS this pull request and a
5807
5823
  disagreement with the diff is worth reporting.
5808
5824
 
@@ -11716,6 +11732,25 @@ export function buildReviewRunStep(
11716
11732
  indented(carry, indent) +
11717
11733
  indented(baseline, indent) +
11718
11734
  indented(review, indent) +
11735
+ // #1395. BEFORE the ledger, and that is the whole of this ordering. The
11736
+ // ledger quotes a line out of a reviewer-cited file, and #1383 made that
11737
+ // read come from the INDEX rather than the working tree — correct, and a
11738
+ // workaround: it routes AROUND a modified checkout instead of preventing
11739
+ // one, so every later reader of this tree has to remember to ask the
11740
+ // index too. Refusing here makes a modified checkout unquotable by
11741
+ // construction and leaves the index read as defence in depth.
11742
+ //
11743
+ // What it costs, deliberately: a refusal ends the job, and this job
11744
+ // forbids `if:`, so the ledger, the threads, the execution-file staging
11745
+ // and the report do not run on a drift failure. `buildDriftScript` says
11746
+ // why that is the right loss — a review that edited the code it was
11747
+ // reviewing "is not an absent review; it is a review nobody should
11748
+ // read" — and a finding set the carry-forward walker would re-inject
11749
+ // into later rounds is exactly what a tainted round must not leave
11750
+ // behind. The refusal is not silent: its annotation names the paths that
11751
+ // moved, so the diagnosis is in the annotation rather than in the
11752
+ // execution file this order skips.
11753
+ indented(drift, indent) +
11719
11754
  indented(persist, indent) +
11720
11755
  // #1612. After the ledger and before the report, for the reason
11721
11756
  // `AI_REVIEW_THREADS_STEP_ID` gives: the payload exists, the adjudicator
@@ -11727,7 +11762,6 @@ export function buildReviewRunStep(
11727
11762
  indented(stageExecution, indent) +
11728
11763
  indented(executionArtifact, indent) +
11729
11764
  indented(report, indent) +
11730
- indented(drift, indent) +
11731
11765
  indented(disarm, indent)
11732
11766
  );
11733
11767
  }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * One way to list the source files a census claims to police.
3
+ *
4
+ * Covers SC-2732, SC-2733 (specs/BOARD-FLOW-SPEC.md).
5
+ *
6
+ * ## Why this is a module and not a `readdirSync`
7
+ *
8
+ * Several census tests spelled the same line:
9
+ *
10
+ * ```ts
11
+ * for (const f of readdirSync(join(ROOT, dir))) if (f.endsWith(".ts")) …
12
+ * ```
13
+ *
14
+ * `readdirSync` does not recurse, and a directory entry fails
15
+ * `endsWith(".ts")`, so every file under `lib/generators/`, `lib/scaffold/`
16
+ * and `lib/validators/` was dropped **without a word**. Eighteen files sat
17
+ * outside populations that reported themselves clean.
18
+ *
19
+ * That is the failure mode in `.claude/rules/checks-must-be-able-to-fail.md`
20
+ * where the instrument is narrower than the thing it detects — and worse
21
+ * here than usual, because these particular censuses exist to assert a
22
+ * property over N sites rather than repair them one at a time. A census
23
+ * with a hole in its population is the defect it was written to prevent,
24
+ * wearing the shape of the prevention.
25
+ *
26
+ * Measured 2026-11-06, before the fix: of fourteen test files calling
27
+ * `readdirSync`, seven already recursed, two scanned directories other than
28
+ * these, and five scanned `lib/` or `scripts/` flat.
29
+ * `test/selection-path-safety.test.ts` is the honest one of the five — its
30
+ * case is named "no file **directly under** scripts/", so it declares the
31
+ * narrow scope rather than claiming the whole tree.
32
+ *
33
+ * ## It returns paths, not names
34
+ *
35
+ * A census that joined a bare filename onto its directory could not express
36
+ * `generators/types.ts`, so the return value is repo-relative and the
37
+ * caller never rebuilds a path. The one exception a caller still needs —
38
+ * "only the top level" — is a parameter rather than a second function,
39
+ * because two listers is how the first hole appeared.
40
+ */
41
+
42
+ import { readdirSync } from "fs";
43
+ import { join } from "path";
44
+
45
+ /**
46
+ * The only read error `sourceFiles` absorbs. One exported site, so a
47
+ * mutation can widen it and a case can observe that it did.
48
+ */
49
+ export const ABSENT_DIRECTORY = "ENOENT";
50
+
51
+ export interface SourceCensusOptions {
52
+ /** File extension to keep, with the dot. */
53
+ readonly ext?: string;
54
+ /**
55
+ * Stop at the top level.
56
+ *
57
+ * **For a census that SAYS it is top-level only**, like
58
+ * `test/selection-path-safety.test.ts`, whose case is named for it. Not a
59
+ * convenience: passing this to avoid dealing with a subdirectory
60
+ * reintroduces the hole, and the case name is the only thing that makes
61
+ * it honest.
62
+ */
63
+ readonly topLevelOnly?: boolean;
64
+ }
65
+
66
+ /**
67
+ * Every source file under `dirs`, repo-relative, sorted.
68
+ *
69
+ * A directory that does not **exist** is skipped rather than thrown on: a
70
+ * census naming a directory the tree has not got should fail on its own
71
+ * empty population, with its own message, not on an `ENOENT` from here.
72
+ *
73
+ * **Every other read error is rethrown**, and the narrowness is the whole
74
+ * point. A bare `catch { return; }` here is the fail-open shape in
75
+ * `.claude/rules/checks-must-be-able-to-fail.md` — an `EACCES`, an `EMFILE`
76
+ * part-way through a large walk, or a `dirs` entry that is a file rather
77
+ * than a directory would shrink the population with no signal, and a short
78
+ * population is indistinguishable from a clean one to every caller. Worse
79
+ * now than before the fix: this is the single binding all of them read, so
80
+ * one absorbed error goes quiet across every census at once.
81
+ */
82
+ export function sourceFiles(
83
+ root: string,
84
+ dirs: readonly string[],
85
+ options: SourceCensusOptions = {},
86
+ ): string[] {
87
+ const ext = options.ext ?? ".ts";
88
+ const out: string[] = [];
89
+ const walk = (rel: string): void => {
90
+ let entries;
91
+ try {
92
+ entries = readdirSync(join(root, rel), { withFileTypes: true });
93
+ } catch (e) {
94
+ if ((e as NodeJS.ErrnoException).code !== ABSENT_DIRECTORY) throw e;
95
+ return;
96
+ }
97
+ for (const e of entries) {
98
+ const path = `${rel}/${e.name}`;
99
+ if (e.isDirectory()) {
100
+ if (!options.topLevelOnly) walk(path);
101
+ continue;
102
+ }
103
+ if (e.name.endsWith(ext)) out.push(path);
104
+ }
105
+ };
106
+ for (const dir of dirs) walk(dir);
107
+ return out.sort();
108
+ }
package/lib/spec-deps.ts CHANGED
@@ -20,9 +20,9 @@
20
20
  *
21
21
  * ## The phase sequence is the phases that EXIST, never N-1 arithmetic
22
22
  *
23
- * {@link dependencyPlan} sorts the phases that actually carry issues and
24
- * chains adjacent members of that list. A spec whose placement table skips a
25
- * number — Phase 0, 1, 3 with nothing in 2 — would otherwise leave Phase 3
23
+ * {@link dependencyPlan} sorts the phases that actually carry issues and hands
24
+ * that list to {@link chainAdjacentPhases}. A spec whose placement table skips
25
+ * a number — Phase 0, 1, 3 with nothing in 2 — would otherwise leave Phase 3
26
26
  * blocked by a phase that does not exist, which reads as *unblocked* and puts
27
27
  * the last phase in the Ready lane beside the first.
28
28
  *
@@ -164,6 +164,36 @@ export function degenerateReasons(r: {
164
164
  return out;
165
165
  }
166
166
 
167
+ /**
168
+ * The cross product of each phase with the one immediately before it in the
169
+ * list it is handed — the whole of the ordering rule, in one symbol.
170
+ *
171
+ * `phases` must be the phases that EXIST, ascending. This function does no
172
+ * arithmetic on the numbers: it pairs index `k` with index `k - 1`, so a
173
+ * placement table that skips Phase 2 chains 1 → 3 rather than leaving Phase 3
174
+ * blocked by a phase carrying nothing. Passing an unsorted list, or one
175
+ * containing a phase with no issues, is what a caller must not do.
176
+ *
177
+ * It lives here rather than inline in {@link dependencyPlan} because SC-2606
178
+ * is the criterion that this rule is *named*: a reader looking for where
179
+ * adjacency is decided has one symbol to open, and a mutation of it moves
180
+ * every edge the plan reports.
181
+ */
182
+ export function chainAdjacentPhases(
183
+ phases: readonly number[],
184
+ byPhase: ReadonlyMap<number, readonly DepIssue[]>,
185
+ ): DepEdge[] {
186
+ const edges: DepEdge[] = [];
187
+ for (let k = 1; k < phases.length; k++) {
188
+ for (const blocked of byPhase.get(phases[k]) ?? []) {
189
+ for (const blocker of byPhase.get(phases[k - 1]) ?? []) {
190
+ edges.push({ blocked: blocked.number, blocker: blocker.number });
191
+ }
192
+ }
193
+ }
194
+ return edges;
195
+ }
196
+
167
197
  /**
168
198
  * What the repository's `blocked by` edges should be, given the phases its
169
199
  * issues sit in.
@@ -202,14 +232,7 @@ export function dependencyPlan(
202
232
 
203
233
  // Adjacent members of the phases that EXIST. See the header: `p - 1` would
204
234
  // leave a phase after a gap blocked by nothing and reading as startable.
205
- const derived: DepEdge[] = [];
206
- for (let k = 1; k < phases.length; k++) {
207
- for (const blocked of byPhase.get(phases[k])!) {
208
- for (const blocker of byPhase.get(phases[k - 1])!) {
209
- derived.push({ blocked: blocked.number, blocker: blocker.number });
210
- }
211
- }
212
- }
235
+ const derived = chainAdjacentPhases(phases, byPhase);
213
236
 
214
237
  const key = (e: DepEdge): string => `${e.blocked}<-${e.blocker}`;
215
238
  const derivedKeys = new Set(derived.map(key));
@@ -203,6 +203,114 @@ export function placementReading(content: string): PlacementReading {
203
203
  };
204
204
  }
205
205
 
206
+ /** What one spec's planning state is, across the whole tree — SC-2611. */
207
+ export type PlacementState = "PLANNED" | "UNPLANNED" | "NO_CRITERIA" | "UNREADABLE";
208
+
209
+ export interface SpecPlacement {
210
+ /** Repo-relative, as the sweep spells it. */
211
+ path: string;
212
+ state: PlacementState;
213
+ /** Why it is not PLANNED. Empty exactly when it is. */
214
+ reasons: string[];
215
+ /** How many criteria the spec states, and how many the table places. */
216
+ criteria: number;
217
+ placed: number;
218
+ }
219
+
220
+ export interface PlacementCoverage {
221
+ /** UNMEASURED FAILS. An empty list from a sweep that failed is not a clean one. */
222
+ reading: "MEASURED" | "UNMEASURED";
223
+ unmeasuredReasons: string[];
224
+ /** Every spec the sweep located, in its order. */
225
+ specs: SpecPlacement[];
226
+ /** The paths in each state, so a caller reports names rather than a count. */
227
+ planned: string[];
228
+ unplanned: string[];
229
+ noCriteria: string[];
230
+ }
231
+
232
+ /** THE one way out of {@link placementCoverage} without a reading. */
233
+ function unmeasuredCoverage(reasons: string[]): PlacementCoverage {
234
+ return { reading: "UNMEASURED", unmeasuredReasons: reasons, specs: [], planned: [], unplanned: [], noCriteria: [] };
235
+ }
236
+
237
+ /**
238
+ * Every spec in the tree, and whether its criteria are placed — SC-2611.
239
+ *
240
+ * **The gap this closes.** {@link placementReading} answers the question for
241
+ * ONE spec, and both of its callers are given a spec on the command line. So
242
+ * a spec with no `### Phase placement` table contributed nothing to any
243
+ * repository-wide view: it had no phases, so it raised no milestone, so it
244
+ * appeared in no lane. 1 of 26 specs had a table on 2026-10-29 and the other
245
+ * 25 were indistinguishable from specs with no work left — which is the
246
+ * flattering reading of the two, and the wrong one.
247
+ *
248
+ * **`NO_CRITERIA` is separate from `UNPLANNED` deliberately.** A spec that
249
+ * states nothing to place genuinely has no work in it; a spec that states
250
+ * twelve criteria and places none has twelve. Folding them together
251
+ * reproduces the defect one level up — the count would be honest and the
252
+ * reader still could not act on it.
253
+ *
254
+ * **One unreadable spec makes the whole reading UNMEASURED**, not a shorter
255
+ * list: a shorter list is exactly what a tree with fewer specs produces. The
256
+ * spec is still carried in `specs` as `UNREADABLE` so the reason names it.
257
+ *
258
+ * The enumeration is `listSpecs`, not a second directory walk. `specs/` is
259
+ * already swept in one place, and a second walk is a second decider for
260
+ * "which files are specs" that no behavioural test of either could separate
261
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
262
+ */
263
+ export function placementCoverage(
264
+ root: string,
265
+ listSpecs: (root: string) => { reading: "MEASURED" | "UNMEASURED"; unmeasuredReasons: string[]; paths: string[] },
266
+ readSpec: (root: string, path: string) => string,
267
+ ): PlacementCoverage {
268
+ const sweep = listSpecs(root);
269
+ if (sweep.reading === "UNMEASURED") {
270
+ return unmeasuredCoverage([
271
+ `the specs/ sweep could not be taken, so nothing below is a reading of this tree: ` +
272
+ sweep.unmeasuredReasons.join("; "),
273
+ ]);
274
+ }
275
+
276
+ const specs: SpecPlacement[] = [];
277
+ const reasons: string[] = [];
278
+ for (const path of sweep.paths) {
279
+ let content: string;
280
+ try {
281
+ content = readSpec(root, path);
282
+ } catch (e) {
283
+ specs.push({ path, state: "UNREADABLE", reasons: [(e as Error).message], criteria: 0, placed: 0 });
284
+ reasons.push(`could not read ${path}: ${(e as Error).message}`);
285
+ continue;
286
+ }
287
+ const r = placementReading(content);
288
+ const placed = r.criteria.length - r.unplaced.length;
289
+ const state: PlacementState =
290
+ r.criteria.length === 0 ? "NO_CRITERIA" : r.reading === "MEASURED" ? "PLANNED" : "UNPLANNED";
291
+ specs.push({
292
+ path,
293
+ state,
294
+ reasons: state === "PLANNED" ? [] : r.unmeasuredReasons,
295
+ criteria: r.criteria.length,
296
+ placed,
297
+ });
298
+ }
299
+
300
+ if (reasons.length > 0) {
301
+ // Carry the per-spec rows: the refusal has to be able to NAME the file.
302
+ return { ...unmeasuredCoverage(reasons), specs };
303
+ }
304
+ return {
305
+ reading: "MEASURED",
306
+ unmeasuredReasons: [],
307
+ specs,
308
+ planned: specs.filter(s => s.state === "PLANNED").map(s => s.path),
309
+ unplanned: specs.filter(s => s.state === "UNPLANNED").map(s => s.path),
310
+ noCriteria: specs.filter(s => s.state === "NO_CRITERIA").map(s => s.path),
311
+ };
312
+ }
313
+
206
314
  /** One criterion, and what the board says about it — item **B2**. */
207
315
  export interface CriterionCoverage {
208
316
  id: string;
@@ -344,12 +344,37 @@ export function claimedImprovements(
344
344
  return out;
345
345
  }
346
346
 
347
- /** Improvements a retro declares outstanding — reported, never hidden. */
348
- export function openImprovements(stages: readonly Stage[]): { stage: string; what: string }[] {
347
+ /**
348
+ * Improvements a retro declares outstanding — reported, never hidden.
349
+ *
350
+ * **The WHOLE improvement, not a two-field summary** (#1745). It used to
351
+ * return `{stage, what}`, and the only caller printed it to a `console.log`
352
+ * nobody reads — so three improvements that nothing could measure were
353
+ * invisible to the document every session is told to read first, while
354
+ * `test/stage-ladder.test.ts` scored stage ITEMS and reported the ladder
355
+ * healthy. That is the fail-open SUCCESS.md claim 4 names: *could not
356
+ * measure* reading as *nothing wrong*.
357
+ *
358
+ * `mechanism` and `issue` ride along because a reader needs both: the first
359
+ * says whether anybody has decided HOW, the second whether it is on the
360
+ * tracker at all. One function answers *what is outstanding* — a renderer
361
+ * that re-filtered `status === "open"` itself would be a second decider over
362
+ * one input, and a mutation of either would leave the other holding the case
363
+ * up.
364
+ */
365
+ export function openImprovements(stages: readonly Stage[]): ({ stage: string } & Improvement)[] {
349
366
  return stages.flatMap(s =>
350
367
  (s.retro?.improvements ?? [])
351
368
  .filter(im => im.status === "open")
352
- .map(im => ({ stage: s.id, what: im.what })),
369
+ // `stage` LAST. Spelled `{ stage: s.id, ...im }` for one commit, which
370
+ // lets an improvement carrying its own `stage` key overwrite the one
371
+ // computed from the stage it is actually in — and the key
372
+ // `OPEN_WITHOUT_ISSUE` matches on in `test/stage-ladder.test.ts` is
373
+ // `${stage}: ${what}`, so data in `project-state.json` could forge a
374
+ // ratchet key and tick a line reserved for a different improvement.
375
+ // Found by the security review of #1812. The computed field is the
376
+ // identity here, so it goes last and the data cannot reach it.
377
+ .map(im => ({ ...im, stage: s.id })),
353
378
  );
354
379
  }
355
380