rungate 0.8.13 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -0,0 +1,1211 @@
1
+ /**
2
+ * What Ready holds, in one place — read by the writer AND by the health
3
+ * reading, so the two cannot disagree.
4
+ *
5
+ * Covers SC-2710, SC-2711, SC-2712, SC-2715, SC-2716, SC-2719 (specs/BOARD-FLOW-SPEC.md).
6
+ *
7
+ * ## Why this file exists at all
8
+ *
9
+ * On 2026-11-05 two files held two different definitions of Ready and
10
+ * neither knew about the other. `isReady` in `lib/board-mirror.ts` required
11
+ * the frontier phase; `target()` in `lib/board-lane-health.ts` compared the
12
+ * lane against every unblocked, unclaimed issue in the repository. Measured
13
+ * over all 35 pickable issues that day, at most **3** could ever satisfy the
14
+ * writer, and the lane held 5 — so the report said `SHORT by 30` and would
15
+ * have said so forever. **The instrument blamed the board.**
16
+ *
17
+ * That is the fourth shape in `.claude/rules/checks-must-be-able-to-fail.md`
18
+ * inverted: not two deciders that agree, but two that disagree, with no
19
+ * single site a mutation could move. Hence one module, two callers, and
20
+ * `test/board-ready-rule.test.ts` asserting that a mutation here reddens
21
+ * both.
22
+ *
23
+ * ## The rule, decided by Jason on 2026-11-05
24
+ *
25
+ * | | Eligibility | Ordering | Size |
26
+ * |---|---|---|---|
27
+ * | before | unblocked + unclaimed + **current phase** | — | unbounded |
28
+ * | now | unblocked + unclaimed | by phase, then issue number | **capped** |
29
+ *
30
+ * Phase moves out of eligibility and into ordering. It was doing crowd
31
+ * control inside an eligibility test, which is why `lib/board-mirror.ts`
32
+ * recorded that removing it made 36 of 46 open issues Ready — "the backlog
33
+ * with a different name". **The cap is the answer to that, not a filter.**
34
+ * Ready is Anderson's replenishment commitment point, and Yeret's line is
35
+ * the one that matters: the number is not the policy, the policy is what
36
+ * happens once it is reached.
37
+ *
38
+ * **This file is the SIZE and the ORDER. Eligibility is still elsewhere** —
39
+ * `isReady` in `lib/board-mirror.ts`, which carried the phase gate until
40
+ * 2026-11-05. The bound landed first deliberately: dropping the gate while nothing
41
+ * caps the lane is the 36-of-46 reading again, so the bound has to exist
42
+ * before the gate can go.
43
+ */
44
+
45
+ import { NAMES_NONE, NEEDS_CRITERION_LABEL, openFrontier, phaseOf } from "./board-mirror";
46
+ import { inMilestoneFamily } from "./live-issues";
47
+
48
+ /**
49
+ * How much work was delivered, over how long.
50
+ *
51
+ * `days` is the observation window, not a count of working days — a window
52
+ * that excluded weekends would make the rate higher than the queue actually
53
+ * drains, and the cap would stop binding exactly when the swarm is quiet.
54
+ */
55
+ export interface Throughput {
56
+ /** Issues closed as delivered inside the window. */
57
+ readonly delivered: number;
58
+ /** The length of the window in days. Must be positive. */
59
+ readonly days: number;
60
+ }
61
+
62
+ /**
63
+ * How long a puller may wait for Ready to be replenished, in days.
64
+ *
65
+ * Half a day. Replenishment here is event-driven rather than a meeting, so
66
+ * the tolerance is not a cadence — it is how much of a stall we accept if
67
+ * every event mechanism is wedged at once. Little's Law turns it into a
68
+ * depth: at the 2026-11-05 reading of 237 issues over 14 days ≈ 17/day, half
69
+ * a day of cover is 8.
70
+ */
71
+ export const READY_TOLERANCE_DAYS = 0.5;
72
+
73
+ /**
74
+ * The queue depth, derived from live throughput.
75
+ *
76
+ * **A literal would go stale in both directions** — too shallow the moment a
77
+ * swarm runs, too deep the moment one stops — and a depth nobody can
78
+ * re-derive is a number nobody will ever change. So it is computed every
79
+ * time from what the repository actually delivered.
80
+ *
81
+ * `null` for a window that cannot produce a rate. A zero-length window is
82
+ * not a throughput of zero; those are opposite facts wearing the same digit,
83
+ * and the caller must be able to tell a quiet fortnight from a failed read
84
+ * (`.claude/rules/config-access.md`, *Silent Default Substitution*).
85
+ *
86
+ * The floor of 1 is not a fudge: a repository that genuinely delivered
87
+ * nothing still has to let the first item through, or Ready can never start.
88
+ */
89
+ export function readyCap(t: Throughput): number | null {
90
+ if (!Number.isFinite(t.delivered) || !Number.isFinite(t.days)) return null;
91
+ if (t.days <= 0) return null;
92
+ if (t.delivered < 0) return null;
93
+ return Math.max(1, Math.floor((t.delivered / t.days) * READY_TOLERANCE_DAYS));
94
+ }
95
+
96
+ /**
97
+ * What Ready SHOULD hold: the cap, or the eligible count when there is less
98
+ * work than cap.
99
+ *
100
+ * This is the denominator `lib/board-lane-health.ts` judges the lane
101
+ * against, and it is the same number the writer fills to — which is the
102
+ * point. `null` propagates: an unreadable cap makes the lane unjudged, never
103
+ * healthy.
104
+ */
105
+ export function readyTarget(eligible: number, cap: number | null): number | null {
106
+ if (cap === null) return null;
107
+ return Math.min(eligible, cap);
108
+ }
109
+
110
+ /**
111
+ * Everything ordering reads. `milestone` is the milestone TITLE, or `null`.
112
+ *
113
+ * **The title and not a phase number** (#1943). A number has already thrown
114
+ * away the family, and the family is half the order: this repository runs two
115
+ * milestone families at once — `Pipeline Phase N`, the engine, and
116
+ * `Convergence Phase N`, the payload the engine ships — and comparing their
117
+ * numbers as one sequence puts the payload ahead of the engine whenever its
118
+ * number is lower. Observed 2026-11-09 in `work-status`: `#1764 Convergence
119
+ * Phase 3` ranked above `#1717 Pipeline Phase 6`, which inverts what
120
+ * `specs/SPEC-TO-BOARD-PIPELINE-SPEC.md` states and what SC-2625 makes the
121
+ * engine's own acceptance test.
122
+ *
123
+ * Carrying both the title and a pre-read number would be two views of one
124
+ * fact, and a caller could hand over a pair that disagree. The title is the
125
+ * one a caller already has; `phaseOf` is still the single thing that reads a
126
+ * number out of it, imported rather than re-spelled.
127
+ *
128
+ * `labels` is **required, with no default** (#1853). An optional field here
129
+ * would let a caller omit it and receive UNPLACED, which is a reading rather
130
+ * than an absence — the same defect `laneHealthLines` records about its own
131
+ * `offBoard` parameter, where a default invented a value the caller already
132
+ * had. Both callers now have to say what they read.
133
+ */
134
+ export interface Rankable {
135
+ readonly milestone: string | null;
136
+ readonly number: number;
137
+ readonly labels: readonly string[];
138
+ }
139
+
140
+ /**
141
+ * Which milestone family an issue's phase belongs to — 0 for the engine, 1
142
+ * for everything else.
143
+ *
144
+ * `enginePrefix` is `board.milestonePrefix` from the project's own config —
145
+ * `"Pipeline"` here — and it is **passed in, never read in this module**.
146
+ * `lib/live-issues.ts` already records what happens when two places compile
147
+ * their own `^<prefix> Phase (\d+)` : two deciders, and no behavioural case
148
+ * can tell them apart.
149
+ *
150
+ * **Membership is `inMilestoneFamily`, delegated rather than re-decided.**
151
+ * Round 2 of this PR's review: the first version matched with a bare
152
+ * `milestone.startsWith(enginePrefix)`, which ranks any family whose NAME
153
+ * merely begins with the engine's as the engine — `EngineX Phase 2` under
154
+ * prefix `Engine`, and `Engine Phase 0` under a truncated `Eng`. That is the
155
+ * same pair `lib/live-issues.ts` records as round 2 of #1703, *"the
156
+ * cross-spec contamination the prefix exists to prevent, arriving through
157
+ * the fix for it"* — and this file's docblock cited that one while the code
158
+ * under it reintroduced the bug. Writing a boundary check here instead of
159
+ * calling the existing one would be a THIRD decider of the same question,
160
+ * which is what that file's whole docblock is about.
161
+ *
162
+ * **A `null` prefix ranks every family 0, and that is a reading rather than a
163
+ * default.** A tree that declares no engine milestone family has ONE family,
164
+ * so there is nothing to rank and the order falls back to phase alone —
165
+ * exactly what every consumer did before #1943. It is not
166
+ * `.claude/rules/config-access.md`'s Silent Default Substitution, which is
167
+ * about inventing a value: nothing is invented here, and `placementOf`'s
168
+ * `why` says which of the two readings it took so the distinction reaches
169
+ * the report.
170
+ */
171
+ export function familyRank(milestone: string | null, enginePrefix: string | null): number {
172
+ if (enginePrefix === null) return 0;
173
+ return inMilestoneFamily(milestone, enginePrefix) ? 0 : 1;
174
+ }
175
+
176
+ /**
177
+ * **No label ranks an issue — SC-2741, ADR-013 row 8 (Jason, 2026-11-11).**
178
+ *
179
+ * `LABEL_RANK` lived here from #1853: a closed map from four labels to a
180
+ * rank, used to order the 74% of candidates no milestone placed. It made
181
+ * the label a second plan beside the milestone, and on 2026-11-11 it was
182
+ * placing 50 of 59 candidates. It is deleted. Label-only work reaches Ready
183
+ * only through the expedite label below, and otherwise waits until somebody
184
+ * gives it a milestone — which is a decision a person makes on the tracker.
185
+ */
186
+
187
+ /**
188
+ * The label that makes one issue go next — Jason's call, 2026-11-09 (#1962).
189
+ *
190
+ * **Not a flag.** A flag is exercised once at promotion time and leaves
191
+ * nothing behind, so nobody can later ask why a card jumped the queue. A
192
+ * label is data on the card, visible in the issue's own timeline, and
193
+ * AGENTS.md rule 4 says ordering is data.
194
+ *
195
+ * **It is its own tier, above PHASE, and that is the design** — the whole
196
+ * point is to reach the top of the queue past work that outranks it, and it
197
+ * is the one way label-only work enters Ready at all (SC-2741).
198
+ *
199
+ * **Its NAME is config, never a constant here** (SC-2735). It was
200
+ * the constant `WORK_NEXT_LABEL`, which made this library the owner of
201
+ * every consumer's vocabulary for the one label that reorders Ready. It is
202
+ * `board.expediteLabel` now, read by `readExpediteLabel` in
203
+ * `lib/config-readers.ts` and passed in by each caller — the same single
204
+ * binding `board.queueLabel` already has — and a tree that configures none
205
+ * gets `UNCONFIGURED`, which promotes nothing.
206
+ */
207
+
208
+ /** Which source placed an issue — or that nothing did. */
209
+ export type PlacementTier = "NEXT" | "PHASE" | "UNPLACED";
210
+
211
+ /** What the expedite label did, and why — `UNCONFIGURED` when the tree names none. */
212
+ export type WorkNextStatus = "NONE" | "HONOURED" | "OVER_BOUND" | "UNMEASURED" | "UNCONFIGURED" | "REFUSED";
213
+
214
+ /**
215
+ * The carriers of the expedite label that also carry `needs-criterion` —
216
+ * #2063, SC-2762. They are refused, by name: the one lever that skips the
217
+ * ordinary order is not spent on an issue that has not said which criterion
218
+ * it serves. The label is `criterion-label.yml`'s, from `criterionAnswer`,
219
+ * so this reads the board's one answer to that question rather than asking it
220
+ * again.
221
+ */
222
+ export function needsCriterionRefusal(
223
+ population: readonly Rankable[],
224
+ carrying: readonly number[],
225
+ ): number[] {
226
+ return carrying.filter(n => population.find(i => i.number === n)?.labels.includes(NEEDS_CRITERION_LABEL));
227
+ }
228
+
229
+ /**
230
+ * How many open issues carry `needs-criterion`, and the oldest of them —
231
+ * SC-2762, the line `scripts/work-status.ts` prints. An issue in this set is
232
+ * work nobody can trace to a criterion, so its count is shown, never left as
233
+ * a number somebody has to go and look up.
234
+ */
235
+ export function needsCriterionLine(
236
+ open: readonly {
237
+ readonly number: number;
238
+ readonly labels: readonly string[];
239
+ /** `null` when the creation date could not be read — never `""`, which sorts as the oldest. */
240
+ readonly createdAt: string | null;
241
+ }[],
242
+ ): string {
243
+ const carrying = open.filter(i => i.labels.includes(NEEDS_CRITERION_LABEL));
244
+ if (carrying.length === 0) return ` No open issue carries ${NEEDS_CRITERION_LABEL}.`;
245
+ const undated = carrying.filter(i => i.createdAt === null).map(i => `#${i.number}`);
246
+ if (undated.length > 0) {
247
+ return (
248
+ ` ${carrying.length} open issue(s) carry ${NEEDS_CRITERION_LABEL}; the oldest is UNMEASURED, ` +
249
+ `because ${undated.join(", ")} came back with no creation date.`
250
+ );
251
+ }
252
+ const dated = carrying as readonly { number: number; createdAt: string }[];
253
+ const oldest = [...dated].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.number - b.number)[0]!;
254
+ return (
255
+ ` ${carrying.length} open issue(s) carry ${NEEDS_CRITERION_LABEL}, oldest #${oldest.number} ` +
256
+ `(${oldest.createdAt.slice(0, 10)}). None of them can be expedited until it names a criterion.`
257
+ );
258
+ }
259
+
260
+ /**
261
+ * Whether a caller can see every candidate it is ordering, or only some.
262
+ *
263
+ * `COMPLETE` means *every candidate this surface orders*, not *every issue
264
+ * in the repository* — the report's pickable list, the board's own items,
265
+ * the top-up's open set. Each is the whole of what its own lane draws from,
266
+ * and each is a denominator somebody chose.
267
+ *
268
+ * `SLICE` is a run that was handed a subset of its own population, and it
269
+ * promotes nothing. `scripts/board-ready.ts --closed-issue N` is the
270
+ * instance: its candidates are the direct dependents of one closed issue,
271
+ * and a ratio taken over them answers about a set nobody picked.
272
+ *
273
+ * **The caller declares it, and a test asserts which one each caller
274
+ * passes** — see `test/board-ready-rule.test.ts`. A declaration is only as
275
+ * honest as the caller, so it is checked in the one place that can see all
276
+ * of them at once rather than trusted per site.
277
+ */
278
+ export type PopulationScope = "COMPLETE" | "SLICE";
279
+
280
+ export interface WorkNextReading {
281
+ readonly status: WorkNextStatus;
282
+ /**
283
+ * Every issue carrying the label, ascending. Populated in the four states
284
+ * that have a label to look for; empty under `UNCONFIGURED`, which has none.
285
+ */
286
+ readonly carrying: readonly number[];
287
+ /** Whose promotion is actually applied. EMPTY unless `HONOURED`. */
288
+ readonly honoured: ReadonlySet<number>;
289
+ /** Ready's depth, the bound. `null` when it could not be read. */
290
+ readonly cap: number | null;
291
+ readonly why: string;
292
+ }
293
+
294
+ /**
295
+ * The six facts the work-next outcome is decided from — #2125.
296
+ *
297
+ * The outcome used to be chosen by the ORDER of an if-chain, and each review
298
+ * round of PR #2123 found one more combination the order got wrong. These
299
+ * are the inputs that order was secretly enumerating, named, so
300
+ * `test/board-ready-rule.test.ts` can walk every combination of them.
301
+ */
302
+ export const WORK_NEXT_FACTS = ["carries", "slice", "depthUnread", "universal", "allRefused", "overDepth"] as const;
303
+
304
+ export type WorkNextFacts = { readonly [K in (typeof WORK_NEXT_FACTS)[number]]: boolean };
305
+
306
+ export type WorkNextOutcome =
307
+ | "NONE"
308
+ | "UNMEASURED_SLICE"
309
+ | "UNMEASURED_DEPTH"
310
+ | "OVER_BOUND_UNIVERSAL"
311
+ | "REFUSED"
312
+ | "OVER_BOUND_DEPTH"
313
+ | "HONOURED";
314
+
315
+ export interface WorkNextRow {
316
+ /** The facts this row requires. A fact it does not name is one it does not depend on. */
317
+ readonly when: Partial<WorkNextFacts>;
318
+ readonly outcome: WorkNextOutcome;
319
+ }
320
+
321
+ /**
322
+ * Every outcome, with its conditions said out loud rather than implied by
323
+ * position. Each row names the facts every earlier row tested, negated, so
324
+ * the rows are disjoint by construction and the coverage test proves it.
325
+ */
326
+ export const WORK_NEXT_ROWS: readonly WorkNextRow[] = [
327
+ // Nobody asked, so there is nothing to measure (round 3 of #1971's review).
328
+ // A bound answers "are there too many"; with none the question is unasked,
329
+ // and every caller's `status !== "NONE"` gate is written against this row.
330
+ { when: { carries: false }, outcome: "NONE" },
331
+ // A slice cannot bound anything (round 2 of #1971's review): both tests the
332
+ // bound applies are ratios against a population nobody chose. Before the
333
+ // depth, so two UNMEASURED causes never hide each other.
334
+ { when: { carries: true, slice: true }, outcome: "UNMEASURED_SLICE" },
335
+ // An unread depth is not zero and not infinity (Silent Default Substitution).
336
+ { when: { carries: true, slice: false, depthUnread: true }, outcome: "UNMEASURED_DEPTH" },
337
+ // If every candidate carries the label, it ranks nothing — keyed on EVERY
338
+ // carrier, refused or not, because refusing one does not make the label
339
+ // discriminate (review of #2123). Before REFUSED: with the label universal,
340
+ // naming a criterion cannot lift anything, so the refusal must not promise
341
+ // it would (round 3 of #2123).
342
+ { when: { carries: true, slice: false, depthUnread: false, universal: true }, outcome: "OVER_BOUND_UNIVERSAL" },
343
+ // Every carrier is refused for needs-criterion (#2063, SC-2762).
344
+ {
345
+ when: { carries: true, slice: false, depthUnread: false, universal: false, allRefused: true },
346
+ outcome: "REFUSED",
347
+ },
348
+ // More eligible carriers than Ready is deep: nothing is promoted, never "the
349
+ // first cap of them", which would be a promotion nobody chose.
350
+ {
351
+ when: { carries: true, slice: false, depthUnread: false, universal: false, allRefused: false, overDepth: true },
352
+ outcome: "OVER_BOUND_DEPTH",
353
+ },
354
+ {
355
+ when: { carries: true, slice: false, depthUnread: false, universal: false, allRefused: false, overDepth: false },
356
+ outcome: "HONOURED",
357
+ },
358
+ ];
359
+
360
+ /** The rows whose conditions `facts` meets. Exactly one, for every combination. */
361
+ export function workNextRows(facts: WorkNextFacts): WorkNextRow[] {
362
+ return WORK_NEXT_ROWS.filter(row =>
363
+ (Object.keys(row.when) as (keyof WorkNextFacts)[]).every(k => row.when[k] === facts[k]),
364
+ );
365
+ }
366
+
367
+ /**
368
+ * Whether the `work-this-next` label is honoured, and over how many issues.
369
+ *
370
+ * ## The bound is the whole of the design
371
+ *
372
+ * If every issue carries the label, the label ranks nothing. So the count
373
+ * carrying it is bounded by **Ready's own depth** — `readyCap`, derived from
374
+ * live throughput — rather than by a number somebody typed. A lever with no
375
+ * bound is a lever that has stopped being one, and a typed bound goes stale
376
+ * in both directions the way `READY_TOLERANCE_DAYS` already records.
377
+ *
378
+ * ## It fails toward NOT promoting
379
+ *
380
+ * Over the bound, **nothing is promoted and the issues are named**. Not "the
381
+ * first `cap` of them" — a silent truncation is a promotion nobody chose, and
382
+ * picking which `cap` to honour is exactly the hand-placement this board
383
+ * exists to replace. A card that did not jump the queue costs a cycle; a
384
+ * silent override nobody can audit costs the property the board is for.
385
+ *
386
+ * An unreadable cap is `UNMEASURED` and promotes nothing either, for the same
387
+ * reason — `.claude/rules/config-access.md`, Silent Default Substitution. A
388
+ * depth that could not be read is not a depth of zero and not a depth of
389
+ * infinity, and only one of the three is honest.
390
+ */
391
+ export function workNextReading(
392
+ population: readonly Rankable[],
393
+ cap: number | null,
394
+ scope: PopulationScope,
395
+ /**
396
+ * `board.expediteLabel`, from `readExpediteLabel` — REQUIRED, with no
397
+ * default, for the reason `placementOf`'s promoted set is: a caller that
398
+ * could omit it would receive a name it never read (SC-2735).
399
+ */
400
+ label: string | null,
401
+ ): WorkNextReading {
402
+ // **No configured label, no promotion — and it says so** (SC-2735). Not
403
+ // `NONE`: that word means *nobody asked*, and here nobody COULD ask,
404
+ // because the tree never named the label. Every caller prints any status
405
+ // but `NONE`, so a project that has not configured one is told once per
406
+ // run what to set rather than being handed a built-in name.
407
+ if (label === null) {
408
+ return {
409
+ status: "UNCONFIGURED",
410
+ carrying: [],
411
+ honoured: new Set(),
412
+ cap,
413
+ why:
414
+ "UNCONFIGURED — no expedite label is set (board.expediteLabel in the rungate " +
415
+ "config), so nothing can be promoted to the top of Ready",
416
+ };
417
+ }
418
+ const carrying = population
419
+ .filter(i => i.labels.includes(label))
420
+ .map(i => i.number)
421
+ .sort((a, b) => a - b);
422
+ const named = carrying.map(n => `#${n}`).join(", ");
423
+ // #2063, SC-2762: a carrier that also carries needs-criterion is refused by
424
+ // name, and holds no place in the bound.
425
+ const refused = needsCriterionRefusal(population, carrying);
426
+ const asking = carrying.filter(n => !refused.includes(n));
427
+ const refusedNames = refused.map(n => `#${n}`).join(", ");
428
+ const refusedNote =
429
+ refused.length === 0
430
+ ? ""
431
+ : ` Refused: ${refusedNames}, which carr${refused.length === 1 ? "ies" : "y"} ${NEEDS_CRITERION_LABEL}.`;
432
+ const askingNames = asking.map(n => `#${n}`).join(", ");
433
+ const facts: WorkNextFacts = {
434
+ carries: carrying.length > 0,
435
+ slice: scope === "SLICE",
436
+ depthUnread: cap === null,
437
+ universal: carrying.length > 0 && carrying.length >= population.length,
438
+ allRefused: asking.length === 0,
439
+ overDepth: cap !== null && asking.length > cap,
440
+ };
441
+ const rows = workNextRows(facts);
442
+ const base = { carrying, honoured: new Set<number>(), cap };
443
+ // Fails toward NOT promoting. The coverage test makes this unreachable; if a
444
+ // row were ever lost, an undecided combination promotes nothing and says so.
445
+ if (rows.length !== 1) {
446
+ return {
447
+ ...base,
448
+ status: "UNMEASURED",
449
+ why:
450
+ `UNMEASURED — the work-next table matched ${rows.length} rows for ${JSON.stringify(facts)}, ` +
451
+ `so NOTHING was promoted${named ? `, including ${named}` : ""}`,
452
+ };
453
+ }
454
+ switch (rows[0]!.outcome) {
455
+ case "NONE":
456
+ return { ...base, status: "NONE", why: `no issue carries "${label}", so the ordinary order stands` };
457
+ case "UNMEASURED_SLICE":
458
+ return {
459
+ ...base,
460
+ status: "UNMEASURED",
461
+ why:
462
+ `UNMEASURED — this run sees only a slice of the candidates, so the bound on ` +
463
+ `"${label}" has no denominator and NOTHING was promoted, ` +
464
+ `including ${named}`,
465
+ };
466
+ case "UNMEASURED_DEPTH":
467
+ return {
468
+ ...base,
469
+ status: "UNMEASURED",
470
+ why:
471
+ `UNMEASURED — Ready's depth could not be read, so the bound on "${label}" ` +
472
+ `is unknown and NOTHING was promoted, including ${named}`,
473
+ };
474
+ case "OVER_BOUND_UNIVERSAL":
475
+ return {
476
+ ...base,
477
+ status: "OVER_BOUND",
478
+ why:
479
+ `REFUSED — all ${population.length} candidate(s) carry "${label}", so it ` +
480
+ `ranks nothing among them whatever Ready's depth of ${cap} allows. NONE was ` +
481
+ `promoted: ${named}.${refusedNote}`,
482
+ };
483
+ case "REFUSED":
484
+ return {
485
+ ...base,
486
+ status: "REFUSED",
487
+ why:
488
+ `REFUSED — ${refusedNames} carr${refused.length === 1 ? "ies" : "y"} "${label}" and also ` +
489
+ `${NEEDS_CRITERION_LABEL}, so NOTHING was promoted: an issue that names no criterion is ` +
490
+ `never expedited. Name the criterion it serves, or "${NAMES_NONE}", and the label lifts.`,
491
+ };
492
+ case "OVER_BOUND_DEPTH":
493
+ return {
494
+ ...base,
495
+ status: "OVER_BOUND",
496
+ why:
497
+ `REFUSED — ${asking.length} issues carry "${label}" and Ready's depth is ` +
498
+ `${cap}, so the label ranks nothing. NONE of them was promoted: ${askingNames}. ` +
499
+ `Remove the label from ${asking.length - cap!} of them.${refusedNote}`,
500
+ };
501
+ case "HONOURED":
502
+ return {
503
+ ...base,
504
+ status: "HONOURED",
505
+ honoured: new Set(asking),
506
+ why:
507
+ `${asking.length} of a bound of ${cap} carry "${label}" and go first: ${askingNames}.${refusedNote}`,
508
+ };
509
+ }
510
+ }
511
+
512
+ /** Nothing is promoted. The reading a caller that has not taken one must pass. */
513
+ export const NO_WORK_NEXT: ReadonlySet<number> = new Set<number>();
514
+
515
+ export interface Placement {
516
+ readonly tier: PlacementTier;
517
+ /**
518
+ * Which milestone family placed it — `familyRank`, so 0 is the engine
519
+ * (#1943). Compared BEFORE the tier, because a phase number is only
520
+ * meaningful inside its own family.
521
+ *
522
+ * Always 0 outside the PHASE tier: an absence belongs to no milestone
523
+ * family, and giving it one would be an ordering nothing declared.
524
+ */
525
+ readonly family: number;
526
+ /** Rank inside the tier. `POSITIVE_INFINITY` for UNPLACED. */
527
+ readonly rank: number;
528
+ readonly why: string;
529
+ }
530
+
531
+ /**
532
+ * NEXT before PHASE before UNPLACED.
533
+ *
534
+ * `work-this-next` beats the milestone, because an honoured promotion is a person saying *this one, now*
535
+ * about a bounded, auditable number of cards (#1962). Everything below it is
536
+ * unchanged, so an empty promotion set leaves the order exactly as #1853 and
537
+ * #1943 left it.
538
+ */
539
+ const TIER_ORDER: Readonly<Record<PlacementTier, number>> = {
540
+ NEXT: 0,
541
+ PHASE: 1,
542
+ UNPLACED: 2,
543
+ };
544
+
545
+ /**
546
+ * Where an issue sits in the plan — milestone, else nowhere.
547
+ *
548
+ * ## The label tier is gone (SC-2741)
549
+ *
550
+ * #1853 added a second source: of 38 candidates on 2026-11-06, 28 carried no
551
+ * milestone and the lane was ordered by age, so a closed label rank placed
552
+ * them. ADR-013 row 8 replaced that with a focus: Ready draws from the active
553
+ * milestone only (`activeMilestone`), so ranking milestone-less work is a
554
+ * question Ready no longer asks. Such work is UNPLACED, and the report names
555
+ * it so somebody can give it a milestone.
556
+ *
557
+ * ## The promoted set is REQUIRED, with no default (#1962)
558
+ *
559
+ * The same reason `labels` is, one field up: an optional parameter lets a
560
+ * caller omit it and receive an answer it never asked for. Here the honest
561
+ * empty value is `NO_WORK_NEXT`, which promotes nothing — so a caller that
562
+ * has not taken the reading has to say so in its own source, where a census
563
+ * test can see it, rather than inheriting the safe answer by accident.
564
+ */
565
+ export function placementOf(
566
+ r: Rankable,
567
+ enginePrefix: string | null,
568
+ honoured: ReadonlySet<number>,
569
+ ): Placement {
570
+ const phase = phaseOf(r.milestone);
571
+ if (honoured.has(r.number)) {
572
+ // **The promotion reports where the card WOULD have sat**, so the lever
573
+ // is auditable from the report alone: "work-this-next promotes it above
574
+ // every tier — the Engine family places it in phase 6" says both that it
575
+ // jumped and what it jumped. A sentence naming only the label would make
576
+ // the promotion unreviewable after the fact, which is the property that
577
+ // ruled out a flag in the first place.
578
+ //
579
+ // Family and rank are 0 for every promoted card, so promoted cards order
580
+ // among themselves by issue number — the oldest ask goes first. Carrying
581
+ // the underlying family and rank up would compare a phase number against
582
+ // a label rank inside one tier, which is two scales in one expression.
583
+ const base = unpromotedPlacement(r, enginePrefix, phase);
584
+ return {
585
+ tier: "NEXT",
586
+ family: 0,
587
+ rank: 0,
588
+ why: `the expedite label promotes it above every tier — ${base.why}`,
589
+ };
590
+ }
591
+ return unpromotedPlacement(r, enginePrefix, phase);
592
+ }
593
+
594
+ /** Where a card sits with no promotion applied. `placementOf`'s other half. */
595
+ function unpromotedPlacement(
596
+ r: Rankable,
597
+ enginePrefix: string | null,
598
+ phase: number | null,
599
+ ): Placement {
600
+ if (phase !== null) {
601
+ const family = familyRank(r.milestone, enginePrefix);
602
+ return {
603
+ tier: "PHASE",
604
+ family,
605
+ rank: phase,
606
+ // The family is in the sentence because it is in the order. #1943 was
607
+ // found by reading `work-status` output that said *"milestone places
608
+ // it in phase 3"* above one that said *"phase 6"* — both true, and
609
+ // between them they hid the fact that the two numbers were counted in
610
+ // different sequences.
611
+ why:
612
+ enginePrefix === null
613
+ ? `milestone places it in phase ${phase} (no engine family is configured, ` +
614
+ "so phase alone orders this)"
615
+ : family === 0
616
+ ? `the ${enginePrefix} family places it in phase ${phase}`
617
+ : `phase ${phase}, but NOT in the ${enginePrefix} family — the engine ships first, ` +
618
+ "so every engine phase outranks this",
619
+ };
620
+ }
621
+ return {
622
+ tier: "UNPLACED",
623
+ family: 0,
624
+ rank: Number.POSITIVE_INFINITY,
625
+ why:
626
+ r.labels.length === 0
627
+ ? "no milestone and no label at all — nothing in the repository says where this belongs"
628
+ : `no milestone, and a label (${r.labels.join(", ")}) places nothing — ` +
629
+ "label-only work enters Ready only through the expedite label (SC-2741)",
630
+ };
631
+ }
632
+
633
+ /**
634
+ * ORDERING: which eligible issue should be pulled first.
635
+ *
636
+ * Tier first (expedite, then phase, then unplaced), rank inside the tier, then
637
+ * issue number. **Age still breaks ties and no longer decides the tier** —
638
+ * before #1853 it decided the tier for 28 of 38 candidates, because every
639
+ * one of them ranked `POSITIVE_INFINITY` and the tiebreak was the whole
640
+ * ordering.
641
+ *
642
+ * Phase ascending, because the phase placement table is the project's own
643
+ * declared order and is data rather than a judgement made here. **A
644
+ * phase-less issue sorts last, not never** — that is the whole difference
645
+ * between ordering and the eligibility gate it replaces, and on 2026-11-05
646
+ * it was the difference between 3 candidates and 35. Issue number ascending
647
+ * is age: the oldest work in a tier goes first, so nothing is starved by a
648
+ * steady arrival of newer items.
649
+ *
650
+ * Two UNPLACED items compare `Infinity !== Infinity`, which is false, so the
651
+ * rank test falls through to the number rather than producing `NaN`.
652
+ */
653
+ export function readyOrderFor(
654
+ enginePrefix: string | null,
655
+ honoured: ReadonlySet<number>,
656
+ ): (a: Rankable, b: Rankable) => number {
657
+ return (a, b) => {
658
+ const pa = placementOf(a, enginePrefix, honoured);
659
+ const pb = placementOf(b, enginePrefix, honoured);
660
+ // Tier first: an honoured expedite card, then the declared plan.
661
+ if (TIER_ORDER[pa.tier] !== TIER_ORDER[pb.tier]) {
662
+ return TIER_ORDER[pa.tier] - TIER_ORDER[pb.tier];
663
+ }
664
+ // **Then family, INSIDE the tier, and before rank** (#1943). A phase
665
+ // number is only meaningful inside its own family, so comparing
666
+ // `Convergence Phase 3` against `Pipeline Phase 6` on the number alone
667
+ // puts the payload ahead of the engine that ships it.
668
+ //
669
+ // **Above the tier was the first spelling and it was wrong.** `family`
670
+ // is 0 outside the PHASE tier, so hoisting it made every milestone-less
671
+ // issue honorary engine — a category beating a declared plan.
672
+ if (pa.family !== pb.family) return pa.family - pb.family;
673
+ if (pa.rank !== pb.rank) return pa.rank - pb.rank;
674
+ return a.number - b.number;
675
+ };
676
+ }
677
+
678
+ /** How many candidates each source placed. The report's one reading. */
679
+ export interface PlacementCensus {
680
+ /** Promoted by `work-this-next` and honoured (#1962). */
681
+ readonly next: number;
682
+ readonly phase: number;
683
+ readonly unplaced: number;
684
+ }
685
+
686
+ /**
687
+ * The census the report prints.
688
+ *
689
+ * It lives here rather than inline in `scripts/work-status.ts` so that a
690
+ * mutation of the placement rule moves the writer's ordering AND the
691
+ * reader's count — which is the property `lib/board-lane-health.ts`'s own
692
+ * header says was missing the last two times this area went wrong.
693
+ *
694
+ * **UNPLACED is counted, not folded into "no milestone".** An issue nothing
695
+ * can rank currently reads identically to one ranked last, and that is the
696
+ * distinction every row in the lane-health report exists to keep.
697
+ */
698
+ export function placementCensus(
699
+ items: readonly Rankable[],
700
+ enginePrefix: string | null,
701
+ honoured: ReadonlySet<number>,
702
+ ): PlacementCensus {
703
+ let next = 0;
704
+ let phase = 0;
705
+ let unplaced = 0;
706
+ for (const i of items) {
707
+ const t = placementOf(i, enginePrefix, honoured).tier;
708
+ if (t === "NEXT") next++;
709
+ else if (t === "PHASE") phase++;
710
+ else unplaced++;
711
+ }
712
+ return { next, phase, unplaced };
713
+ }
714
+
715
+ /**
716
+ * The one focus Ready refills from — SC-2741, ADR-013 row 8.
717
+ *
718
+ * `title` is the milestone, or `null` when no open issue sits in any phase
719
+ * milestone at all — and then Ready stays empty, because nothing pickable is
720
+ * an answer, not a reason to reach for something else.
721
+ */
722
+ export interface ActiveMilestone {
723
+ readonly title: string | null;
724
+ readonly why: string;
725
+ }
726
+
727
+ /**
728
+ * **The lowest engine phase with an open issue, else the payload's.**
729
+ *
730
+ * Kanban pull, Jason's call of 2026-11-11: one active focus. The frontier is
731
+ * `openFrontier` in `lib/board-mirror.ts` — the reading `plan-deps` already
732
+ * prints as "Frontier: Phase 6" — reused rather than re-decided, because a
733
+ * second minimum over the same phases is a second decider.
734
+ *
735
+ * - `open` is EVERY open issue the caller can see, claimed and blocked ones
736
+ * included. A phase whose work is all in progress is still the focus;
737
+ * reading only the pickable ones would move the focus past work that is
738
+ * not finished.
739
+ * - Milestone open/closed state is not read. Phases 0-5 here are open
740
+ * milestones holding no open issue, and they are finished.
741
+ * - **Payload waits for the car** (ADR-013 decision 9): a milestone outside
742
+ * the engine family becomes the focus only when no engine phase has an
743
+ * open issue. A `null` prefix is one family — `familyRank`'s reading — so
744
+ * the lowest phase overall leads.
745
+ * - Two titles at one phase in one family resolve by title, so the answer
746
+ * does not depend on the order GitHub returned issues in.
747
+ */
748
+ export function activeMilestone(
749
+ open: readonly { readonly milestone: string | null }[],
750
+ enginePrefix: string | null,
751
+ ): ActiveMilestone {
752
+ const phased = open.filter(i => phaseOf(i.milestone) !== null);
753
+ const engine = phased.filter(i => familyRank(i.milestone, enginePrefix) === 0);
754
+ const payload = phased.filter(i => familyRank(i.milestone, enginePrefix) !== 0);
755
+ const focusIn = (pool: typeof phased): string | null => {
756
+ const frontier = openFrontier(pool.map(i => ({ state: "OPEN", phase: phaseOf(i.milestone) })));
757
+ if (frontier === null) return null;
758
+ const titles = pool
759
+ .filter(i => phaseOf(i.milestone) === frontier)
760
+ .map(i => i.milestone as string)
761
+ .sort();
762
+ return titles[0] ?? null;
763
+ };
764
+ const car = focusIn(engine);
765
+ if (car !== null) {
766
+ return {
767
+ title: car,
768
+ why:
769
+ enginePrefix === null
770
+ ? `${car} is the lowest phase with an open issue (no engine family is configured)`
771
+ : `${car} is the lowest ${enginePrefix} phase with an open issue`,
772
+ };
773
+ }
774
+ const load = focusIn(payload);
775
+ if (load !== null) {
776
+ return {
777
+ title: load,
778
+ why: `no ${enginePrefix} phase has an open issue, so the payload's lowest phase, ${load}, is next`,
779
+ };
780
+ }
781
+ return {
782
+ title: null,
783
+ why: "no open issue sits in any phase milestone, so nothing is pickable and Ready stays empty",
784
+ };
785
+ }
786
+
787
+ /**
788
+ * Is this card inside the focus? The ONE predicate, for entry and for stay.
789
+ *
790
+ * `expedited` is the caller's reading of the expedite lane: an honoured
791
+ * promotion on the way in, carrying the configured label for a card already
792
+ * in Ready. Everything else must sit in the active milestone exactly.
793
+ */
794
+ export function inReadyScope(
795
+ r: { readonly milestone: string | null },
796
+ active: ActiveMilestone,
797
+ expedited: boolean,
798
+ ): boolean {
799
+ if (expedited) return true;
800
+ return active.title !== null && r.milestone === active.title;
801
+ }
802
+
803
+ /**
804
+ * Split candidates into the ones Ready may draw from and the ones it may not.
805
+ *
806
+ * Every Ready writer and the report call this between the eligibility
807
+ * decision and `selectReady`, so the scope is decided once (SC-2741). Order
808
+ * is preserved; ordering is still `readyOrderFor`'s.
809
+ */
810
+ export function scopedCandidates<T extends Rankable>(
811
+ eligible: readonly T[],
812
+ active: ActiveMilestone,
813
+ honoured: ReadonlySet<number>,
814
+ ): { inScope: T[]; outOfScope: T[] } {
815
+ const inScope: T[] = [];
816
+ const outOfScope: T[] = [];
817
+ for (const c of eligible) {
818
+ (inReadyScope(c, active, honoured.has(c.number)) ? inScope : outOfScope).push(c);
819
+ }
820
+ return { inScope, outOfScope };
821
+ }
822
+
823
+ /**
824
+ * How full Ready is — the ONE answer, read by the writer and by the report.
825
+ *
826
+ * ## Why this exists (#1852)
827
+ *
828
+ * Two files answered "how full is Ready" and answered differently.
829
+ * `scripts/board-ready.ts` counted **every card**, arguing correctly that a
830
+ * pull request parked in the lane occupies a slot a puller can see.
831
+ * `scripts/work-status.ts` counted **open issues only**, arguing equally
832
+ * correctly that a lane of closed cards has nothing to start. Neither was
833
+ * wrong about the question it asked; they were asking different questions
834
+ * and the plan treated the answers as one number.
835
+ *
836
+ * Measured on main 2026-11-07, with a draft card and issue #1650 in the
837
+ * lane at a cap of 2: the writer reported `2 of 2, so it is full and nothing
838
+ * was promoted` and refused 37 eligible issues, while the report reported
839
+ * `1 of 2 SHORT` and exited non-zero. **The lane was physically full and
840
+ * functionally empty, and no single integer could say so.**
841
+ *
842
+ * That is `.claude/rules/checks-must-be-able-to-fail.md`'s fourth shape
843
+ * inverted — not two deciders that agree, but two that disagree with no
844
+ * single site a mutation could move — and this module's own header records
845
+ * it happening here before, on 2026-11-05, between `isReady` and `target()`.
846
+ *
847
+ * ## Both numbers, because the state needs both
848
+ *
849
+ * `cards` bounds promotion: a slot held by anything is not free, so the
850
+ * writer cannot exceed the depth by however many non-issues the lane holds.
851
+ * `dispatchable` is what a session can actually start. `WEDGED` is the state
852
+ * that needed naming: full by cards, empty by work, and reachable by one
853
+ * undispatchable card at a cap of 2.
854
+ */
855
+ export type OccupancyVerdict = "ROOM" | "FULL" | "WEDGED" | "UNMEASURED";
856
+
857
+ /**
858
+ * One card in the Ready lane, as much of it as the occupancy decision needs.
859
+ *
860
+ * Deliberately not the GraphQL node. The caller reads the board; this module
861
+ * decides. A test that had to build a `ProjectV2Item` to ask a yes/no question
862
+ * would be testing the query.
863
+ */
864
+ export interface ReadyCard {
865
+ /** `content.__typename` — `"Issue"`, `"PullRequest"`, or absent for a draft. */
866
+ readonly typename?: string;
867
+ /** `content.state` — `"OPEN"` or `"CLOSED"` for an issue. */
868
+ readonly state?: string;
869
+ /**
870
+ * `content.number`. Absent when the query did not select it, which holds
871
+ * the slot — see {@link holdsReadySlot}.
872
+ */
873
+ readonly number?: number;
874
+ }
875
+
876
+ /**
877
+ * Does this card hold a Ready slot? — #1905.
878
+ *
879
+ * ## The race
880
+ *
881
+ * `board-ready.yml` and `board-flow.yml` both fire on `issues: assigned`.
882
+ * `board-ready` counted the just-assigned card as occupying Ready, concluded
883
+ * the lane was full, and promoted nothing; `board-flow` moved that same card
884
+ * to *In progress* one second later. Measured 2026-11-08: `board-ready` at
885
+ * 13:06:55Z read *"Ready holds 1 of its depth of 1"*, `board-flow` moved
886
+ * #1668 out at 13:06:56Z, and the lane was then empty with nothing queued.
887
+ *
888
+ * ## `movingIssue` is ONE issue number, and that bound is the whole design
889
+ *
890
+ * The caller passes the number of the issue **this event is about** — the
891
+ * card `board-flow` is moving out of Ready in the run racing this one. That
892
+ * single card does not hold its slot. Nothing else is excluded.
893
+ *
894
+ * **The first version of this excluded every assigned open issue**, on the
895
+ * argument that `laneFor` maps `issue_assigned` to `In progress`
896
+ * unconditionally, so such a card is always leaving. Review found the hole
897
+ * and it is a real one: `laneFor` is a pure decision function, not a
898
+ * guarantee the write it feeds ever lands. `scripts/board-flow.ts` gates the
899
+ * write behind `actorMayWrite`, which refuses GitHub's **Triage** role —
900
+ * sufficient to assign an issue, absent from `WRITING_PERMISSIONS` — and the
901
+ * write also fails on an expired token or a GraphQL error, both recorded
902
+ * happening here. A card whose move failed is OPEN, assigned, and still in
903
+ * Ready **forever**; the old predicate excluded it on every later run, so
904
+ * the writer promoted on top of it with nothing bounding the pile. That is
905
+ * the over-the-cap outcome this file says must never happen, and it also
906
+ * re-opened #1852's split: `lib/board-lane-health.ts` kept counting that
907
+ * card, so the writer and the health report disagreed permanently.
908
+ *
909
+ * Keying on the event's own issue number bounds all of it:
910
+ *
911
+ * - **At most one card** is ever excluded, in the one run that races.
912
+ * - **It is self-correcting.** A later run is about a different issue, so a
913
+ * card whose move failed is counted normally again and the lane reads
914
+ * over-depth, which `board-lane-health` reports.
915
+ * - **No permanent disagreement.** The health report takes its own reading
916
+ * with no event, so it excludes nothing; the difference exists only
917
+ * during the racing run.
918
+ *
919
+ * **The residual, stated rather than hidden:** if `board-flow`'s write
920
+ * fails, the lane ends that run one card over its depth. At the instant
921
+ * this predicate is asked, a successful move and a failed one are
922
+ * indistinguishable — the card is in Ready either way — so one is the floor,
923
+ * not a choice. Bounded and visible beats dry and silent.
924
+ *
925
+ * ## Why not the three options #1905 listed
926
+ *
927
+ * - **Chain `board-ready` on `board-flow`'s completion.** It drops
928
+ * triggers. `board-ready` fires on five issue events and `board-flow` on
929
+ * three; a `workflow_run` chain loses `unassigned` and `opened`, both
930
+ * `--top-up` sources, and its payload carries neither the originating
931
+ * issue nor the action, so the mode could not be resolved.
932
+ * - **Fold the top-up into `board-flow`.** Works, and couples the move to
933
+ * the refill for a defect one predicate wide.
934
+ * - **Re-read before concluding FULL.** #1905 rejected it and was right:
935
+ * it narrows the window instead of closing it.
936
+ *
937
+ * ## The direction this is allowed to be wrong in
938
+ *
939
+ * Toward **holding** the slot, so every uncertain reading holds:
940
+ *
941
+ * - `movingIssue` **absent** excludes nothing. A caller that does not know
942
+ * which card is moving must not thereby empty the lane.
943
+ * - A card whose **`number`** the query did not select holds it. Absent is
944
+ * UNMEASURED, never "matches".
945
+ * - A **non-issue** holds it. A pull request parked in Ready takes a slot
946
+ * exactly as an issue does, and `board-flow` moves no PR on an issue
947
+ * assignment.
948
+ * - A **closed** issue holds it, because nothing here is a tidier.
949
+ */
950
+ export function holdsReadySlot(card: ReadyCard, movingIssue?: number): boolean {
951
+ if (card.typename !== "Issue") return true;
952
+ if (card.state !== "OPEN") return true;
953
+ // **ONE guard for both absences, and the mutation battery is why.** They
954
+ // were two lines — `movingIssue === undefined` and `card.number ===
955
+ // undefined` — and mutating EITHER turned zero cases red, because each
956
+ // was held up by the other through the `!==` below. Two guards answering
957
+ // one question are behaviourally one guard, and no behavioural test can
958
+ // tell them apart.
959
+ //
960
+ // They are not redundant, which is the trap: `undefined !== undefined` is
961
+ // FALSE, so with both removed a card whose number was never selected, in
962
+ // a run that named no mover, frees its slot — and that is every card on
963
+ // the board. One site, and a case that is red when it goes.
964
+ if (movingIssue === undefined || card.number === undefined) return true;
965
+ return card.number !== movingIssue;
966
+ }
967
+
968
+ export interface ReadyOccupancy {
969
+ /** Every card in the lane — an issue, a pull request, a draft. */
970
+ readonly cards: number;
971
+ /** Cards a session can start: open issues. Never above `cards`. */
972
+ readonly dispatchable: number;
973
+ /** `cards - dispatchable`. Named, because it is the thing to clear. */
974
+ readonly undispatchable: number;
975
+ readonly cap: number | null;
976
+ /** Slots a promoter may fill. Always 0 when the cap is unreadable. */
977
+ readonly free: number;
978
+ readonly verdict: OccupancyVerdict;
979
+ readonly why: string;
980
+ }
981
+
982
+ /**
983
+ * The one reading. `dispatchable` above `cards` is a caller bug, not a lane
984
+ * state — it means the two were counted over different populations, which is
985
+ * the defect this function exists to end — so it is refused rather than
986
+ * clamped. A clamp would make the wrong call site look right.
987
+ */
988
+ export function readyOccupancy(
989
+ cards: number,
990
+ dispatchable: number,
991
+ /**
992
+ * How deep the lane is allowed to be. The WRITER passes `readyCap`; the
993
+ * REPORT passes `readyTarget`, which is the smaller of the cap and the
994
+ * eligible count. Both are "the depth", and the sentences below say depth
995
+ * for that reason — calling a target a cap in the report's own output is
996
+ * the drift this module exists to stop.
997
+ */
998
+ cap: number | null,
999
+ ): ReadyOccupancy {
1000
+ if (!Number.isInteger(cards) || !Number.isInteger(dispatchable) || cards < 0 || dispatchable < 0) {
1001
+ throw new Error(
1002
+ `readyOccupancy: cards and dispatchable must be non-negative integers, got ` +
1003
+ `${cards} and ${dispatchable}. A count that could not be taken is not a count of zero.`,
1004
+ );
1005
+ }
1006
+ if (dispatchable > cards) {
1007
+ throw new Error(
1008
+ `readyOccupancy: dispatchable (${dispatchable}) exceeds cards (${cards}), so the two were ` +
1009
+ "counted over different populations — which is exactly the defect #1852 closed. " +
1010
+ "Both must be read from one pass over one lane.",
1011
+ );
1012
+ }
1013
+ const undispatchable = cards - dispatchable;
1014
+ if (cap === null) {
1015
+ return {
1016
+ cards,
1017
+ dispatchable,
1018
+ undispatchable,
1019
+ cap: null,
1020
+ free: 0,
1021
+ verdict: "UNMEASURED",
1022
+ why:
1023
+ "UNMEASURED — throughput could not be read, so Ready's depth is unknown and nothing was promoted",
1024
+ };
1025
+ }
1026
+ const free = Math.max(0, cap - cards);
1027
+ if (free > 0) {
1028
+ return {
1029
+ cards,
1030
+ dispatchable,
1031
+ undispatchable,
1032
+ cap,
1033
+ free,
1034
+ verdict: "ROOM",
1035
+ why: `Ready holds ${cards} of its depth of ${cap}, so ${free} slot(s) are free`,
1036
+ };
1037
+ }
1038
+ // Full by cards. WEDGED is the half that had no name: the lane is at its
1039
+ // depth and nothing in it can be started, so the writer will not refill it
1040
+ // and the reader will keep refusing. It unsticks only by hand.
1041
+ if (dispatchable === 0) {
1042
+ return {
1043
+ cards,
1044
+ dispatchable,
1045
+ undispatchable,
1046
+ cap,
1047
+ free: 0,
1048
+ verdict: "WEDGED",
1049
+ why:
1050
+ `Ready holds ${cards} of its depth of ${cap} and NONE of them can be started — ` +
1051
+ `${undispatchable} card(s) in the lane ${undispatchable === 1 ? "is" : "are"} not an open ` +
1052
+ "issue. Nothing can dispatch a draft or a pull request, and nothing ages one out, so this " +
1053
+ "lane is full and empty at the same time and no event will refill it. Clear the lane.",
1054
+ };
1055
+ }
1056
+ return {
1057
+ cards,
1058
+ dispatchable,
1059
+ undispatchable,
1060
+ cap,
1061
+ free: 0,
1062
+ verdict: "FULL",
1063
+ why:
1064
+ `Ready holds ${cards} of its depth of ${cap}, so it is full and nothing was promoted` +
1065
+ (undispatchable > 0
1066
+ ? ` — and ${undispatchable} of them cannot be started, so only ${dispatchable} is real work`
1067
+ : ""),
1068
+ };
1069
+ }
1070
+
1071
+ /**
1072
+ * SELECTION: which eligible issues to promote right now.
1073
+ *
1074
+ * It takes a `ReadyOccupancy` rather than a cap and a count, so the free-slot
1075
+ * arithmetic exists exactly once (#1852). It used to compute
1076
+ * `max(0, cap - occupied)` itself, which made it the second site that decided
1077
+ * how full the lane was.
1078
+ *
1079
+ * This is the replenishment half of the commitment point, and it is what
1080
+ * makes the cap something other than a ceiling nobody reaches: a pull frees a
1081
+ * slot and the next event refills it.
1082
+ *
1083
+ * **An unreadable cap promotes nothing, and says so.** The tempting
1084
+ * fallback — promote everything eligible and let a human trim it — is the
1085
+ * exact failure the cap exists to prevent, performed automatically.
1086
+ */
1087
+ export function selectReady<T extends Rankable>(
1088
+ eligible: readonly T[],
1089
+ occ: ReadyOccupancy,
1090
+ enginePrefix: string | null,
1091
+ honoured: ReadonlySet<number>,
1092
+ ): { readonly promote: readonly T[]; readonly why: string } {
1093
+ if (occ.free === 0) {
1094
+ // One branch for every reason there is no room — UNMEASURED, FULL and
1095
+ // WEDGED each carry their own sentence on the reading itself, so this
1096
+ // does not restate them and cannot disagree with them.
1097
+ return { promote: [], why: occ.why };
1098
+ }
1099
+ // A copy, not a sort in place: the caller's array is its own decision
1100
+ // record and reordering it changes what its log prints.
1101
+ const promote = [...eligible].sort(readyOrderFor(enginePrefix, honoured)).slice(0, occ.free);
1102
+ return {
1103
+ promote,
1104
+ why:
1105
+ `${occ.why}; ${eligible.length} eligible, promoting ${promote.length} ` +
1106
+ (enginePrefix === null
1107
+ ? "in phase then age order"
1108
+ : `in ${enginePrefix}-first, then phase, then age order`),
1109
+ };
1110
+ }
1111
+
1112
+ /**
1113
+ * Why an eligible issue did not move.
1114
+ *
1115
+ * **Two causes, two sentences.** The writer printed "Ready is at its
1116
+ * depth" for every eligible issue it held back, including when the depth
1117
+ * was never read — so a run that measured nothing told the reader the lane
1118
+ * was full, one line below its own UNMEASURED warning. ai-review found it
1119
+ * on #1793 and it is the same defect in miniature as the lane health row
1120
+ * that blamed the board: a reading that names the wrong cause sends the
1121
+ * next person to the wrong place.
1122
+ *
1123
+ * It lives here rather than inline in the script so a case can hold it.
1124
+ *
1125
+ * **Three causes now, not two** (#1852). "Ready is at its depth" is true of a
1126
+ * WEDGED lane and sends the reader to the depth — which is not the thing to
1127
+ * change. A lane held at its cap by cards nobody can start needs clearing,
1128
+ * and the held issues are the evidence that something wants the slot.
1129
+ */
1130
+ export function heldReason(occ: ReadyOccupancy): string {
1131
+ switch (occ.verdict) {
1132
+ case "UNMEASURED":
1133
+ return "Ready's depth could not be measured, so nothing was promoted";
1134
+ case "WEDGED":
1135
+ return (
1136
+ `Ready is at its depth of ${occ.cap} and WEDGED — every card in it is undispatchable, ` +
1137
+ "so clearing the lane is the fix, not lowering the depth"
1138
+ );
1139
+ case "FULL":
1140
+ case "ROOM":
1141
+ return "Ready is at its depth";
1142
+ default: {
1143
+ const unhandled: never = occ.verdict;
1144
+ throw new Error(
1145
+ `heldReason: unclassified occupancy verdict ${JSON.stringify(unhandled)}. ` +
1146
+ "Every verdict must name its own cause — defaulting a new one to 'at its depth' is " +
1147
+ "how WEDGED read as a lane that only needed a bigger cap.",
1148
+ );
1149
+ }
1150
+ }
1151
+ }
1152
+
1153
+ /**
1154
+ * What to do about cards in Ready nobody can start — the REPORT's question.
1155
+ *
1156
+ * ## Not the same question as `heldReason`, which is why it is not the same
1157
+ * sentence
1158
+ *
1159
+ * ai-review round 1 of #1857. `heldReason` answers *why did this eligible
1160
+ * issue not move*, and both callers ask it while iterating items they held
1161
+ * back. In a `ROOM` reading those items are held because promoting into the
1162
+ * free slots reaches the depth, so "Ready is at its depth" is true of them.
1163
+ *
1164
+ * `scripts/work-status.ts` promotes nothing. It is describing a lane, and it
1165
+ * says this whenever the lane holds a card that is not an open issue —
1166
+ * including when the lane is SHORT. Routing that through `heldReason` printed
1167
+ * "Ready is at its depth" over a lane holding 2 of a depth of 5. That is
1168
+ * false, and it is the wrong instruction besides: a short lane is fixed by
1169
+ * promoting, not by clearing.
1170
+ *
1171
+ * ## Two renderings, one decider
1172
+ *
1173
+ * Both switch on a verdict neither computes. `readyOccupancy` remains the only
1174
+ * thing that decides how full Ready is, so a mutation of the reading moves
1175
+ * both sentences together and neither can drift from the other's arithmetic —
1176
+ * which is the property #1852 bought and the thing a second *decider* would
1177
+ * have given back.
1178
+ */
1179
+ export function undispatchableRemedy(occ: ReadyOccupancy): string {
1180
+ switch (occ.verdict) {
1181
+ case "UNMEASURED":
1182
+ return (
1183
+ "Ready's depth could not be read, so whether those card(s) are costing a slot " +
1184
+ "is unknown too"
1185
+ );
1186
+ case "WEDGED":
1187
+ return (
1188
+ `Ready is at its depth of ${occ.cap} and WEDGED — NOTHING in the lane can be started, ` +
1189
+ "so clearing the lane is the fix. Promotion cannot help: there is no slot to promote into"
1190
+ );
1191
+ case "FULL":
1192
+ return (
1193
+ `Ready is at its depth of ${occ.cap}, so each of them holds a slot a startable issue ` +
1194
+ "could be in — clear them and the next promotion fills the lane"
1195
+ );
1196
+ case "ROOM":
1197
+ return (
1198
+ `Ready is NOT full — it holds ${occ.cards} of its depth of ${occ.cap}, so ${occ.free} ` +
1199
+ "slot(s) are free and PROMOTING is what fixes this lane. Clearing the undispatchable " +
1200
+ "card(s) is worth doing and is not what is holding it short"
1201
+ );
1202
+ default: {
1203
+ const unhandled: never = occ.verdict;
1204
+ throw new Error(
1205
+ `undispatchableRemedy: unclassified occupancy verdict ${JSON.stringify(unhandled)}. ` +
1206
+ "Every verdict must name its own remedy — defaulting a new one to 'clear the lane' " +
1207
+ "sends a SHORT lane's reader to the one fix that cannot work.",
1208
+ );
1209
+ }
1210
+ }
1211
+ }