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,545 @@
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
+ /**
46
+ * How much work was delivered, over how long.
47
+ *
48
+ * `days` is the observation window, not a count of working days — a window
49
+ * that excluded weekends would make the rate higher than the queue actually
50
+ * drains, and the cap would stop binding exactly when the swarm is quiet.
51
+ */
52
+ export interface Throughput {
53
+ /** Issues closed as delivered inside the window. */
54
+ readonly delivered: number;
55
+ /** The length of the window in days. Must be positive. */
56
+ readonly days: number;
57
+ }
58
+
59
+ /**
60
+ * How long a puller may wait for Ready to be replenished, in days.
61
+ *
62
+ * Half a day. Replenishment here is event-driven rather than a meeting, so
63
+ * the tolerance is not a cadence — it is how much of a stall we accept if
64
+ * every event mechanism is wedged at once. Little's Law turns it into a
65
+ * depth: at the 2026-11-05 reading of 237 issues over 14 days ≈ 17/day, half
66
+ * a day of cover is 8.
67
+ */
68
+ export const READY_TOLERANCE_DAYS = 0.5;
69
+
70
+ /**
71
+ * The queue depth, derived from live throughput.
72
+ *
73
+ * **A literal would go stale in both directions** — too shallow the moment a
74
+ * swarm runs, too deep the moment one stops — and a depth nobody can
75
+ * re-derive is a number nobody will ever change. So it is computed every
76
+ * time from what the repository actually delivered.
77
+ *
78
+ * `null` for a window that cannot produce a rate. A zero-length window is
79
+ * not a throughput of zero; those are opposite facts wearing the same digit,
80
+ * and the caller must be able to tell a quiet fortnight from a failed read
81
+ * (`.claude/rules/config-access.md`, *Silent Default Substitution*).
82
+ *
83
+ * The floor of 1 is not a fudge: a repository that genuinely delivered
84
+ * nothing still has to let the first item through, or Ready can never start.
85
+ */
86
+ export function readyCap(t: Throughput): number | null {
87
+ if (!Number.isFinite(t.delivered) || !Number.isFinite(t.days)) return null;
88
+ if (t.days <= 0) return null;
89
+ if (t.delivered < 0) return null;
90
+ return Math.max(1, Math.floor((t.delivered / t.days) * READY_TOLERANCE_DAYS));
91
+ }
92
+
93
+ /**
94
+ * What Ready SHOULD hold: the cap, or the eligible count when there is less
95
+ * work than cap.
96
+ *
97
+ * This is the denominator `lib/board-lane-health.ts` judges the lane
98
+ * against, and it is the same number the writer fills to — which is the
99
+ * point. `null` propagates: an unreadable cap makes the lane unjudged, never
100
+ * healthy.
101
+ */
102
+ export function readyTarget(eligible: number, cap: number | null): number | null {
103
+ if (cap === null) return null;
104
+ return Math.min(eligible, cap);
105
+ }
106
+
107
+ /**
108
+ * Everything ordering reads. Phase `null` means "no phase milestone".
109
+ *
110
+ * `labels` is **required, with no default** (#1853). An optional field here
111
+ * would let a caller omit it and receive UNPLACED, which is a reading rather
112
+ * than an absence — the same defect `laneHealthLines` records about its own
113
+ * `offBoard` parameter, where a default invented a value the caller already
114
+ * had. Both callers now have to say what they read.
115
+ */
116
+ export interface Rankable {
117
+ readonly phase: number | null;
118
+ readonly number: number;
119
+ readonly labels: readonly string[];
120
+ }
121
+
122
+ /**
123
+ * The order labels rank in when no milestone places an issue — Jason's call,
124
+ * 2026-11-06. **This is the only place it is spelled.**
125
+ *
126
+ * `engine` leads because it is the work that reduces the backlog itself:
127
+ * AGENTS.md rule 7 watches issues opened against issues closed, and above 1
128
+ * the backlog diverges however fast the work goes, so engine work compounds
129
+ * and a follow-up does not.
130
+ *
131
+ * **A label outside this map does not place an issue.** The set is closed
132
+ * deliberately: ranking an unknown label by guessing is the silent default
133
+ * `.claude/rules/config-access.md` names, and `arbiter-override` is the live
134
+ * instance — one eligible issue carries it and nothing else, and the honest
135
+ * answer is UNPLACED rather than a tier somebody invented for it.
136
+ */
137
+ export const LABEL_RANK: ReadonlyMap<string, number> = new Map([
138
+ ["engine", 0],
139
+ ["spec:convergence", 1],
140
+ ["follow-up", 2],
141
+ ["external-audit", 3],
142
+ ]);
143
+
144
+ /** Which source placed an issue — or that nothing did. */
145
+ export type PlacementTier = "PHASE" | "LABEL" | "UNPLACED";
146
+
147
+ export interface Placement {
148
+ readonly tier: PlacementTier;
149
+ /** Rank inside the tier. `POSITIVE_INFINITY` for UNPLACED. */
150
+ readonly rank: number;
151
+ readonly why: string;
152
+ }
153
+
154
+ /** PHASE before LABEL before UNPLACED. A milestone always beats a label. */
155
+ const TIER_ORDER: Readonly<Record<PlacementTier, number>> = { PHASE: 0, LABEL: 1, UNPLACED: 2 };
156
+
157
+ /**
158
+ * Where an issue sits in the plan — milestone, else label, else nowhere.
159
+ *
160
+ * ## Why a second source exists at all (#1853)
161
+ *
162
+ * Phase comes from `phaseOf`, which reads a number out of a MILESTONE TITLE
163
+ * and nothing else. Measured 2026-11-06: of 38 unblocked, unclaimed issues,
164
+ * **10** carried a milestone and **28** did not, so 74% of what Ready draws
165
+ * from sorted as `POSITIVE_INFINITY` and fell through to the tiebreak. The
166
+ * tiebreak is issue number. **The lane was ordered by age.**
167
+ *
168
+ * The obvious repair is to backfill `### Phase placement` tables so
169
+ * `plan-spec` derives a milestone for everything. It cannot reach this
170
+ * backlog: only **16 of 80** open issues name an `SC-` id at all. The other
171
+ * 64 are review follow-ups, audit findings and engine work that never passed
172
+ * through a spec, and no table placed on any spec can rank them.
173
+ *
174
+ * So the label is the fallback, and it is the signal this repository already
175
+ * produces for work with no spec. A milestone still wins, because the
176
+ * milestone is the declared plan and the label is a category.
177
+ *
178
+ * **An issue with several ranked labels takes the best of them.** A
179
+ * follow-up that is also engine work is engine work; taking the worst would
180
+ * let adding a label demote an issue, which makes the rank punish labelling.
181
+ */
182
+ export function placementOf(r: Rankable): Placement {
183
+ if (r.phase !== null) {
184
+ return { tier: "PHASE", rank: r.phase, why: `milestone places it in phase ${r.phase}` };
185
+ }
186
+ let best: { label: string; rank: number } | null = null;
187
+ for (const label of r.labels) {
188
+ const rank = LABEL_RANK.get(label);
189
+ if (rank === undefined) continue;
190
+ if (best === null || rank < best.rank) best = { label, rank };
191
+ }
192
+ if (best !== null) {
193
+ return {
194
+ tier: "LABEL",
195
+ rank: best.rank,
196
+ why: `no milestone, and "${best.label}" ranks ${best.rank} of ${LABEL_RANK.size}`,
197
+ };
198
+ }
199
+ return {
200
+ tier: "UNPLACED",
201
+ rank: Number.POSITIVE_INFINITY,
202
+ why:
203
+ r.labels.length === 0
204
+ ? "no milestone and no label at all — nothing in the repository says where this belongs"
205
+ : `no milestone, and none of its labels (${r.labels.join(", ")}) is ranked — ` +
206
+ "add one to LABEL_RANK deliberately, or give it a milestone",
207
+ };
208
+ }
209
+
210
+ /**
211
+ * ORDERING: which eligible issue should be pulled first.
212
+ *
213
+ * Tier first (phase, then label, then unplaced), rank inside the tier, then
214
+ * issue number. **Age still breaks ties and no longer decides the tier** —
215
+ * before #1853 it decided the tier for 28 of 38 candidates, because every
216
+ * one of them ranked `POSITIVE_INFINITY` and the tiebreak was the whole
217
+ * ordering.
218
+ *
219
+ * Phase ascending, because the phase placement table is the project's own
220
+ * declared order and is data rather than a judgement made here. **A
221
+ * phase-less issue sorts last, not never** — that is the whole difference
222
+ * between ordering and the eligibility gate it replaces, and on 2026-11-05
223
+ * it was the difference between 3 candidates and 35. Issue number ascending
224
+ * is age: the oldest work in a tier goes first, so nothing is starved by a
225
+ * steady arrival of newer items.
226
+ *
227
+ * Two UNPLACED items compare `Infinity !== Infinity`, which is false, so the
228
+ * rank test falls through to the number rather than producing `NaN`.
229
+ */
230
+ export function readyOrder(a: Rankable, b: Rankable): number {
231
+ const pa = placementOf(a);
232
+ const pb = placementOf(b);
233
+ if (TIER_ORDER[pa.tier] !== TIER_ORDER[pb.tier]) {
234
+ return TIER_ORDER[pa.tier] - TIER_ORDER[pb.tier];
235
+ }
236
+ if (pa.rank !== pb.rank) return pa.rank - pb.rank;
237
+ return a.number - b.number;
238
+ }
239
+
240
+ /** How many candidates each source placed. The report's one reading. */
241
+ export interface PlacementCensus {
242
+ readonly phase: number;
243
+ readonly label: number;
244
+ readonly unplaced: number;
245
+ }
246
+
247
+ /**
248
+ * The census the report prints.
249
+ *
250
+ * It lives here rather than inline in `scripts/work-status.ts` so that a
251
+ * mutation of the placement rule moves the writer's ordering AND the
252
+ * reader's count — which is the property `lib/board-lane-health.ts`'s own
253
+ * header says was missing the last two times this area went wrong.
254
+ *
255
+ * **UNPLACED is counted, not folded into "no milestone".** An issue nothing
256
+ * can rank currently reads identically to one ranked last, and that is the
257
+ * distinction every row in the lane-health report exists to keep.
258
+ */
259
+ export function placementCensus(items: readonly Rankable[]): PlacementCensus {
260
+ let phase = 0;
261
+ let label = 0;
262
+ let unplaced = 0;
263
+ for (const i of items) {
264
+ const t = placementOf(i).tier;
265
+ if (t === "PHASE") phase++;
266
+ else if (t === "LABEL") label++;
267
+ else unplaced++;
268
+ }
269
+ return { phase, label, unplaced };
270
+ }
271
+
272
+ /**
273
+ * How full Ready is — the ONE answer, read by the writer and by the report.
274
+ *
275
+ * ## Why this exists (#1852)
276
+ *
277
+ * Two files answered "how full is Ready" and answered differently.
278
+ * `scripts/board-ready.ts` counted **every card**, arguing correctly that a
279
+ * pull request parked in the lane occupies a slot a puller can see.
280
+ * `scripts/work-status.ts` counted **open issues only**, arguing equally
281
+ * correctly that a lane of closed cards has nothing to start. Neither was
282
+ * wrong about the question it asked; they were asking different questions
283
+ * and the plan treated the answers as one number.
284
+ *
285
+ * Measured on main 2026-11-07, with a draft card and issue #1650 in the
286
+ * lane at a cap of 2: the writer reported `2 of 2, so it is full and nothing
287
+ * was promoted` and refused 37 eligible issues, while the report reported
288
+ * `1 of 2 SHORT` and exited non-zero. **The lane was physically full and
289
+ * functionally empty, and no single integer could say so.**
290
+ *
291
+ * That is `.claude/rules/checks-must-be-able-to-fail.md`'s fourth shape
292
+ * inverted — not two deciders that agree, but two that disagree with no
293
+ * single site a mutation could move — and this module's own header records
294
+ * it happening here before, on 2026-11-05, between `isReady` and `target()`.
295
+ *
296
+ * ## Both numbers, because the state needs both
297
+ *
298
+ * `cards` bounds promotion: a slot held by anything is not free, so the
299
+ * writer cannot exceed the depth by however many non-issues the lane holds.
300
+ * `dispatchable` is what a session can actually start. `WEDGED` is the state
301
+ * that needed naming: full by cards, empty by work, and reachable by one
302
+ * undispatchable card at a cap of 2.
303
+ */
304
+ export type OccupancyVerdict = "ROOM" | "FULL" | "WEDGED" | "UNMEASURED";
305
+
306
+ export interface ReadyOccupancy {
307
+ /** Every card in the lane — an issue, a pull request, a draft. */
308
+ readonly cards: number;
309
+ /** Cards a session can start: open issues. Never above `cards`. */
310
+ readonly dispatchable: number;
311
+ /** `cards - dispatchable`. Named, because it is the thing to clear. */
312
+ readonly undispatchable: number;
313
+ readonly cap: number | null;
314
+ /** Slots a promoter may fill. Always 0 when the cap is unreadable. */
315
+ readonly free: number;
316
+ readonly verdict: OccupancyVerdict;
317
+ readonly why: string;
318
+ }
319
+
320
+ /**
321
+ * The one reading. `dispatchable` above `cards` is a caller bug, not a lane
322
+ * state — it means the two were counted over different populations, which is
323
+ * the defect this function exists to end — so it is refused rather than
324
+ * clamped. A clamp would make the wrong call site look right.
325
+ */
326
+ export function readyOccupancy(
327
+ cards: number,
328
+ dispatchable: number,
329
+ /**
330
+ * How deep the lane is allowed to be. The WRITER passes `readyCap`; the
331
+ * REPORT passes `readyTarget`, which is the smaller of the cap and the
332
+ * eligible count. Both are "the depth", and the sentences below say depth
333
+ * for that reason — calling a target a cap in the report's own output is
334
+ * the drift this module exists to stop.
335
+ */
336
+ cap: number | null,
337
+ ): ReadyOccupancy {
338
+ if (!Number.isInteger(cards) || !Number.isInteger(dispatchable) || cards < 0 || dispatchable < 0) {
339
+ throw new Error(
340
+ `readyOccupancy: cards and dispatchable must be non-negative integers, got ` +
341
+ `${cards} and ${dispatchable}. A count that could not be taken is not a count of zero.`,
342
+ );
343
+ }
344
+ if (dispatchable > cards) {
345
+ throw new Error(
346
+ `readyOccupancy: dispatchable (${dispatchable}) exceeds cards (${cards}), so the two were ` +
347
+ "counted over different populations — which is exactly the defect #1852 closed. " +
348
+ "Both must be read from one pass over one lane.",
349
+ );
350
+ }
351
+ const undispatchable = cards - dispatchable;
352
+ if (cap === null) {
353
+ return {
354
+ cards,
355
+ dispatchable,
356
+ undispatchable,
357
+ cap: null,
358
+ free: 0,
359
+ verdict: "UNMEASURED",
360
+ why:
361
+ "UNMEASURED — throughput could not be read, so Ready's depth is unknown and nothing was promoted",
362
+ };
363
+ }
364
+ const free = Math.max(0, cap - cards);
365
+ if (free > 0) {
366
+ return {
367
+ cards,
368
+ dispatchable,
369
+ undispatchable,
370
+ cap,
371
+ free,
372
+ verdict: "ROOM",
373
+ why: `Ready holds ${cards} of its depth of ${cap}, so ${free} slot(s) are free`,
374
+ };
375
+ }
376
+ // Full by cards. WEDGED is the half that had no name: the lane is at its
377
+ // depth and nothing in it can be started, so the writer will not refill it
378
+ // and the reader will keep refusing. It unsticks only by hand.
379
+ if (dispatchable === 0) {
380
+ return {
381
+ cards,
382
+ dispatchable,
383
+ undispatchable,
384
+ cap,
385
+ free: 0,
386
+ verdict: "WEDGED",
387
+ why:
388
+ `Ready holds ${cards} of its depth of ${cap} and NONE of them can be started — ` +
389
+ `${undispatchable} card(s) in the lane ${undispatchable === 1 ? "is" : "are"} not an open ` +
390
+ "issue. Nothing can dispatch a draft or a pull request, and nothing ages one out, so this " +
391
+ "lane is full and empty at the same time and no event will refill it. Clear the lane.",
392
+ };
393
+ }
394
+ return {
395
+ cards,
396
+ dispatchable,
397
+ undispatchable,
398
+ cap,
399
+ free: 0,
400
+ verdict: "FULL",
401
+ why:
402
+ `Ready holds ${cards} of its depth of ${cap}, so it is full and nothing was promoted` +
403
+ (undispatchable > 0
404
+ ? ` — and ${undispatchable} of them cannot be started, so only ${dispatchable} is real work`
405
+ : ""),
406
+ };
407
+ }
408
+
409
+ /**
410
+ * SELECTION: which eligible issues to promote right now.
411
+ *
412
+ * It takes a `ReadyOccupancy` rather than a cap and a count, so the free-slot
413
+ * arithmetic exists exactly once (#1852). It used to compute
414
+ * `max(0, cap - occupied)` itself, which made it the second site that decided
415
+ * how full the lane was.
416
+ *
417
+ * This is the replenishment half of the commitment point, and it is what
418
+ * makes the cap something other than a ceiling nobody reaches: a pull frees a
419
+ * slot and the next event refills it.
420
+ *
421
+ * **An unreadable cap promotes nothing, and says so.** The tempting
422
+ * fallback — promote everything eligible and let a human trim it — is the
423
+ * exact failure the cap exists to prevent, performed automatically.
424
+ */
425
+ export function selectReady<T extends Rankable>(
426
+ eligible: readonly T[],
427
+ occ: ReadyOccupancy,
428
+ ): { readonly promote: readonly T[]; readonly why: string } {
429
+ if (occ.free === 0) {
430
+ // One branch for every reason there is no room — UNMEASURED, FULL and
431
+ // WEDGED each carry their own sentence on the reading itself, so this
432
+ // does not restate them and cannot disagree with them.
433
+ return { promote: [], why: occ.why };
434
+ }
435
+ // A copy, not a sort in place: the caller's array is its own decision
436
+ // record and reordering it changes what its log prints.
437
+ const promote = [...eligible].sort(readyOrder).slice(0, occ.free);
438
+ return {
439
+ promote,
440
+ why:
441
+ `${occ.why}; ${eligible.length} eligible, promoting ${promote.length} ` +
442
+ "in phase then age order",
443
+ };
444
+ }
445
+
446
+ /**
447
+ * Why an eligible issue did not move.
448
+ *
449
+ * **Two causes, two sentences.** The writer printed "Ready is at its
450
+ * depth" for every eligible issue it held back, including when the depth
451
+ * was never read — so a run that measured nothing told the reader the lane
452
+ * was full, one line below its own UNMEASURED warning. ai-review found it
453
+ * on #1793 and it is the same defect in miniature as the lane health row
454
+ * that blamed the board: a reading that names the wrong cause sends the
455
+ * next person to the wrong place.
456
+ *
457
+ * It lives here rather than inline in the script so a case can hold it.
458
+ *
459
+ * **Three causes now, not two** (#1852). "Ready is at its depth" is true of a
460
+ * WEDGED lane and sends the reader to the depth — which is not the thing to
461
+ * change. A lane held at its cap by cards nobody can start needs clearing,
462
+ * and the held issues are the evidence that something wants the slot.
463
+ */
464
+ export function heldReason(occ: ReadyOccupancy): string {
465
+ switch (occ.verdict) {
466
+ case "UNMEASURED":
467
+ return "Ready's depth could not be measured, so nothing was promoted";
468
+ case "WEDGED":
469
+ return (
470
+ `Ready is at its depth of ${occ.cap} and WEDGED — every card in it is undispatchable, ` +
471
+ "so clearing the lane is the fix, not lowering the depth"
472
+ );
473
+ case "FULL":
474
+ case "ROOM":
475
+ return "Ready is at its depth";
476
+ default: {
477
+ const unhandled: never = occ.verdict;
478
+ throw new Error(
479
+ `heldReason: unclassified occupancy verdict ${JSON.stringify(unhandled)}. ` +
480
+ "Every verdict must name its own cause — defaulting a new one to 'at its depth' is " +
481
+ "how WEDGED read as a lane that only needed a bigger cap.",
482
+ );
483
+ }
484
+ }
485
+ }
486
+
487
+ /**
488
+ * What to do about cards in Ready nobody can start — the REPORT's question.
489
+ *
490
+ * ## Not the same question as `heldReason`, which is why it is not the same
491
+ * sentence
492
+ *
493
+ * ai-review round 1 of #1857. `heldReason` answers *why did this eligible
494
+ * issue not move*, and both callers ask it while iterating items they held
495
+ * back. In a `ROOM` reading those items are held because promoting into the
496
+ * free slots reaches the depth, so "Ready is at its depth" is true of them.
497
+ *
498
+ * `scripts/work-status.ts` promotes nothing. It is describing a lane, and it
499
+ * says this whenever the lane holds a card that is not an open issue —
500
+ * including when the lane is SHORT. Routing that through `heldReason` printed
501
+ * "Ready is at its depth" over a lane holding 2 of a depth of 5. That is
502
+ * false, and it is the wrong instruction besides: a short lane is fixed by
503
+ * promoting, not by clearing.
504
+ *
505
+ * ## Two renderings, one decider
506
+ *
507
+ * Both switch on a verdict neither computes. `readyOccupancy` remains the only
508
+ * thing that decides how full Ready is, so a mutation of the reading moves
509
+ * both sentences together and neither can drift from the other's arithmetic —
510
+ * which is the property #1852 bought and the thing a second *decider* would
511
+ * have given back.
512
+ */
513
+ export function undispatchableRemedy(occ: ReadyOccupancy): string {
514
+ switch (occ.verdict) {
515
+ case "UNMEASURED":
516
+ return (
517
+ "Ready's depth could not be read, so whether those card(s) are costing a slot " +
518
+ "is unknown too"
519
+ );
520
+ case "WEDGED":
521
+ return (
522
+ `Ready is at its depth of ${occ.cap} and WEDGED — NOTHING in the lane can be started, ` +
523
+ "so clearing the lane is the fix. Promotion cannot help: there is no slot to promote into"
524
+ );
525
+ case "FULL":
526
+ return (
527
+ `Ready is at its depth of ${occ.cap}, so each of them holds a slot a startable issue ` +
528
+ "could be in — clear them and the next promotion fills the lane"
529
+ );
530
+ case "ROOM":
531
+ return (
532
+ `Ready is NOT full — it holds ${occ.cards} of its depth of ${occ.cap}, so ${occ.free} ` +
533
+ "slot(s) are free and PROMOTING is what fixes this lane. Clearing the undispatchable " +
534
+ "card(s) is worth doing and is not what is holding it short"
535
+ );
536
+ default: {
537
+ const unhandled: never = occ.verdict;
538
+ throw new Error(
539
+ `undispatchableRemedy: unclassified occupancy verdict ${JSON.stringify(unhandled)}. ` +
540
+ "Every verdict must name its own remedy — defaulting a new one to 'clear the lane' " +
541
+ "sends a SHORT lane's reader to the one fix that cannot work.",
542
+ );
543
+ }
544
+ }
545
+ }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * How much this repository actually delivered, and over how long.
3
+ *
4
+ * Covers SC-2713, SC-2714, SC-2717, SC-2718 (specs/BOARD-FLOW-SPEC.md).
5
+ *
6
+ * Ready's depth is derived from this (`lib/board-ready-rule.ts`), so the
7
+ * window and what counts as delivery are decisions, not details — and they
8
+ * live in one place because three callers need the same answer. Two callers
9
+ * reading two windows would reproduce the defect the ready rule was written
10
+ * to remove: a writer and a reading disagreeing about the same lane with no
11
+ * single site a mutation could move.
12
+ *
13
+ * **No token, no network of its own.** The caller injects `gql`, which is
14
+ * what makes this testable without a credential — and a credential is the
15
+ * thing that turns a measurement into a thing nobody re-runs.
16
+ */
17
+
18
+ import type { Throughput } from "./board-ready-rule";
19
+ import { nextCursor } from "./graphql-cursor";
20
+
21
+ /**
22
+ * The window throughput is measured over.
23
+ *
24
+ * Two weeks: long enough that one quiet day does not halve Ready's depth,
25
+ * short enough that a swarm starting is visible inside a day or two.
26
+ *
27
+ * **It is the live decision, and the readings say why.** Measured
28
+ * 2026-11-05 on this repository: 9 delivered in 7 days, 132 in 14, 646 in
29
+ * 30 — a factor of ten between the shortest and longest window, because 30
30
+ * days contains a swarm and the last 7 do not. The resulting depths are 1,
31
+ * 4 and 10. Anyone changing this number is changing Ready's size, and that
32
+ * is the honest place for the argument to happen.
33
+ *
34
+ * Raw days rather than working days, deliberately: a window that skipped
35
+ * weekends would raise the rate above the speed the queue actually drains.
36
+ */
37
+ export const THROUGHPUT_DAYS = 14;
38
+
39
+ /** What `measureThroughput` needs from a GraphQL client. */
40
+ export type GqlFn = (query: string, variables: Record<string, unknown>) => Promise<any>;
41
+
42
+ export const CLOSED_ISSUES_QUERY = `query($o:String!,$n:String!,$c:String){repository(owner:$o,name:$n){
43
+ issues(states:CLOSED,first:100,after:$c){pageInfo{hasNextPage endCursor} nodes{stateReason closedAt}}}}`;
44
+
45
+ /**
46
+ * Everything one pass over the closed issues can answer.
47
+ *
48
+ * **Two readings, one pass, because they fail together.** They were two
49
+ * passes for one round — a cost ai-review flagged on #1793, and it was
50
+ * right: the code this replaced had deliberately combined them and the
51
+ * refactor undid that to get a single definition of "delivered". Both
52
+ * properties are available at once, so there was never a trade to make.
53
+ *
54
+ * Returning them in one object also makes the shared failure honest: a
55
+ * pass that died gives no throughput AND no cancellation count, and two
56
+ * separate `null`s invite a caller to believe one of them.
57
+ */
58
+ export interface ClosedIssueReadings {
59
+ /** Issues delivered inside the window, and the window. */
60
+ readonly throughput: Throughput;
61
+ /**
62
+ * Issues closed as `NOT_PLANNED` or `DUPLICATE`, over all time.
63
+ *
64
+ * Both reasons, because `specs/BOARD-FLOW-SPEC.md` defines Cancelled's
65
+ * entry as both and `lib/work-status.ts` maps both to ABANDONED. All
66
+ * time, not the window: it is the Cancelled lane's denominator, not a
67
+ * rate.
68
+ */
69
+ readonly cancelled: number;
70
+ }
71
+
72
+ /**
73
+ * One pass over every closed issue: delivery inside the window, and
74
+ * cancellations over all time.
75
+ *
76
+ * `null` when the pass could not complete. **Not zero** — a failed read and
77
+ * a quiet fortnight are opposite facts wearing the same digit, and
78
+ * collapsing them produces a Ready depth of 1 out of a measurement that
79
+ * never happened (`.claude/rules/config-access.md`).
80
+ *
81
+ * **Delivered, not merely closed.** A cancellation leaves the system
82
+ * without adding capacity, so counting it would deepen the queue exactly
83
+ * when the repository is abandoning work. On 2026-11-05 that was 4 of 136
84
+ * closures over the window — small, and in the wrong direction.
85
+ *
86
+ * This pages every closed issue rather than running one search, for the
87
+ * reason recorded in `scripts/work-status.ts` beside the cancelled count:
88
+ * **a search qualifier the index does not understand returns the same zero
89
+ * as a true zero**, measured with a control (`reason:bogusvalue` → 0).
90
+ */
91
+ export async function measureClosedIssues(
92
+ gql: GqlFn,
93
+ owner: string,
94
+ name: string,
95
+ now: number = Date.now(),
96
+ days: number = THROUGHPUT_DAYS,
97
+ ): Promise<ClosedIssueReadings | null> {
98
+ const since = now - days * 86_400_000;
99
+ let delivered = 0;
100
+ let cancelled = 0;
101
+ let c: string | null = null;
102
+ try {
103
+ do {
104
+ const d = await gql(CLOSED_ISSUES_QUERY, { o: owner, n: name, c });
105
+ // **No `if (!page?.nodes) return null` guard, and the mutation
106
+ // battery is why.** It was here, reading well and covered by a case,
107
+ // and removing it changed nothing: every shape it caught — a null
108
+ // repository, an absent node list — throws one line later and the
109
+ // `catch` below converts it to the same `null`. Two deciders, one
110
+ // answer, and no behavioural test can tell which is live
111
+ // (`.claude/rules/checks-must-be-able-to-fail.md`). The case that
112
+ // "covered" it was green on the catch.
113
+ const page = d?.repository?.issues;
114
+ for (const i of page.nodes) {
115
+ if (i?.stateReason === "NOT_PLANNED" || i?.stateReason === "DUPLICATE") cancelled++;
116
+ if (i?.stateReason !== "COMPLETED") continue;
117
+ const at = Date.parse(i.closedAt ?? "");
118
+ if (Number.isFinite(at) && at >= since) delivered++;
119
+ }
120
+ // **One decider for every pager** — `lib/graphql-cursor.ts`. This
121
+ // site held three variants of the same silent truncation, found one
122
+ // at a time across two pull requests, while four sibling loops held
123
+ // all three. Repairing them site by site is what kept producing
124
+ // them (`.claude/rules/checks-must-be-able-to-fail.md`).
125
+ const step = nextCursor(page.pageInfo);
126
+ if (step.kind === "unreadable") return null;
127
+ c = step.kind === "more" ? step.cursor : null;
128
+ } while (c);
129
+ } catch {
130
+ // Deliberately swallowed and converted to the UNMEASURED value, which
131
+ // every caller already refuses on. Letting it throw would take down a
132
+ // board write for a count that only sizes a queue.
133
+ return null;
134
+ }
135
+ return { throughput: { delivered, days }, cancelled };
136
+ }