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
@@ -33,6 +33,7 @@
33
33
  */
34
34
  import { readdirSync, readFileSync } from "fs";
35
35
  import { join, relative, sep } from "path";
36
+ import { readMilestoneTitle } from "./milestone-title";
36
37
  import { idBoundedPattern, oneScMentionPattern } from "./sc-ids";
37
38
  import { parseCriteria } from "./spec-evidence";
38
39
 
@@ -41,6 +42,12 @@ export interface SpecCriteria {
41
42
  /** Repo-relative, with `/` separators, so a reading is comparable across machines. */
42
43
  readonly path: string;
43
44
  readonly ids: readonly string[];
45
+ /**
46
+ * The ids whose box is NOT ticked in this spec, from the same read as
47
+ * `ids` (#2005). A pull request closing an issue that names one of these
48
+ * leaves the criterion with one fewer open issue and no tick.
49
+ */
50
+ readonly unticked: readonly string[];
44
51
  }
45
52
 
46
53
  /** What `specCriteriaIn` found, including what it could not resolve. */
@@ -205,6 +212,7 @@ export function specCriteriaIn(root: string, readDir: SpecDirReader = readSpecDi
205
212
  const seen = new Map<string, string[]>();
206
213
  for (const path of files) {
207
214
  let ids: string[];
215
+ let unticked: string[];
208
216
  try {
209
217
  // De-duplicated WITHIN the spec. `parseCriteria` matches every
210
218
  // `- [ ] ID:` line independently and does not dedupe, so one spec
@@ -215,7 +223,9 @@ export function specCriteriaIn(root: string, readDir: SpecDirReader = readSpecDi
215
223
  // misreported as ambiguous, with a nonsensical reason. Found by the
216
224
  // AI review of #1679; zero specs state a duplicate today, so nothing
217
225
  // observable changes and the guard is for the case that arrives.
218
- ids = criterionIdsIn(readFileSync(join(root, path), "utf-8"));
226
+ const text = readFileSync(join(root, path), "utf-8");
227
+ ids = criterionIdsIn(text);
228
+ unticked = [...new Set(parseCriteria(text).filter(c => !c.ticked).map(c => c.id))];
219
229
  } catch (e) {
220
230
  // One unreadable spec does not make a SHORTER id list — it makes the
221
231
  // whole sweep unmeasured, because a shorter list is exactly what a
@@ -223,7 +233,7 @@ export function specCriteriaIn(root: string, readDir: SpecDirReader = readSpecDi
223
233
  reasons.push(`could not read ${path}: ${(e as Error).message}`);
224
234
  continue;
225
235
  }
226
- specs.push({ path, ids });
236
+ specs.push({ path, ids, unticked });
227
237
  for (const id of ids) seen.set(id, [...(seen.get(id) ?? []), path]);
228
238
  }
229
239
 
@@ -273,8 +283,27 @@ export interface MirrorRow {
273
283
  readonly text: string;
274
284
  }
275
285
 
276
- /** The text used when an issue names no criterion at all. */
277
- export const NAMES_NONE = "";
286
+ /**
287
+ * The text used when an issue names no criterion at all — SC-2609.
288
+ *
289
+ * **This was `""` until #1716, and the reason it changed is worth keeping.**
290
+ * The original case read *"A cell reading 'none' sorts and filters as a
291
+ * value. Empty is absence."* Both halves are true and the conclusion is
292
+ * backwards: sorting and filtering as a value is the point, and *absence* is
293
+ * precisely the state a reader cannot act on. A blank cell says **not yet
294
+ * filled in**, **the tool could not tell** and **deliberately none** with the
295
+ * same zero bytes, so the one reading that means the board is in good order
296
+ * is indistinguishable from the two that mean it is not. 28 cells on the live
297
+ * board were blank on 2026-10-29 and nothing could say which kind they were.
298
+ *
299
+ * So the value is spelled, and a cell this module has never written stays
300
+ * `""`. That difference is the whole of SC-2609: `NAMES_NONE !== ""` is what
301
+ * lets a reader tell a judgement from a gap.
302
+ *
303
+ * It must not be mistakable for a criterion id — no `SC-`, no `CRC-`, nothing
304
+ * a reader scanning the column would try to look up.
305
+ */
306
+ export const NAMES_NONE = "serves no criterion";
278
307
 
279
308
  /**
280
309
  * Every id, never a summary.
@@ -294,6 +323,33 @@ export const NAMES_NONE = "";
294
323
  * the JSON carries it. So there is no cap, and the bound that was never
295
324
  * measured is gone rather than raised.
296
325
  */
326
+ /**
327
+ * The spec paths, in the shape `placementCoverage` takes its enumerator in.
328
+ *
329
+ * Lives here because {@link specCriteriaIn} does: *which files are specs* is
330
+ * one question with one answer, and a caller writing its own ten-line adapter
331
+ * is a second site that a mutation of the first would leave standing
332
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape). It was a
333
+ * private function in `scripts/plan-spec.ts` until `scripts/board-snapshot.ts`
334
+ * needed the same sweep for SC-2615; both call this now rather than two
335
+ * copies agreeing.
336
+ *
337
+ * An UNMEASURED sweep propagates — an empty path list from a sweep that
338
+ * failed is indistinguishable from a tree with no specs, and only one of
339
+ * those is a reading.
340
+ */
341
+ export function specPathSweep(
342
+ root: string,
343
+ readDir: SpecDirReader = readSpecDir,
344
+ ): { reading: "MEASURED" | "UNMEASURED"; unmeasuredReasons: string[]; paths: string[] } {
345
+ const sweep = specCriteriaIn(root, readDir);
346
+ return {
347
+ reading: sweep.reading,
348
+ unmeasuredReasons: [...sweep.unmeasuredReasons],
349
+ paths: sweep.specs.map(s => s.path),
350
+ };
351
+ }
352
+
297
353
  export function mirrorText(criteria: readonly string[]): string {
298
354
  if (criteria.length === 0) return NAMES_NONE;
299
355
  return criteria.join(" ");
@@ -339,6 +395,49 @@ export function criteriaNamedBy(
339
395
  );
340
396
  }
341
397
 
398
+ /**
399
+ * The label an open issue carries while it has not answered the criterion
400
+ * question (#2020). Applied and removed by `scripts/criterion-label.ts`,
401
+ * by {@link criterionAnswer} and nothing else.
402
+ */
403
+ export const NEEDS_CRITERION_LABEL = "needs-criterion";
404
+
405
+ /**
406
+ * What an issue says it serves: the criteria it names, whether it declares
407
+ * it serves none, and whether either is true — #2020.
408
+ *
409
+ * **The one decider for "has this issue answered the criterion question".**
410
+ * `criteria-named` (E2, `scripts/board-snapshot.ts`) counts it and the
411
+ * `needs-criterion` label is applied and removed by it, so the label and the
412
+ * reading cannot disagree. Two copies would be two deciders, and a mutation
413
+ * of either would leave the other holding the case up.
414
+ *
415
+ * The declaration is the literal {@link NAMES_NONE}, case and all — the one
416
+ * way this repository spells it (SC-2609). Matching anything looser would
417
+ * let an issue opt out by accident, and *has not said* versus *says none*
418
+ * is the whole of SC-2616.
419
+ */
420
+ /**
421
+ * Every id an issue can answer the criterion question with: the sweep's
422
+ * union PLUS the ids two specs both state (#2020, review round 1). A
423
+ * collision is reported, never merged, for the column — but an issue naming
424
+ * one still serves a criterion, which is why `finding-promotion` already read
425
+ * it this way. One function, so the label, `criteria-named` and the decline
426
+ * refusal all read the same population.
427
+ */
428
+ export function answerableIds(sweep: SpecSweep): string[] {
429
+ return [...sweep.ids, ...sweep.collisions.map(c => c.id)];
430
+ }
431
+
432
+ export function criterionAnswer(
433
+ issue: { readonly title: string; readonly body?: string | null },
434
+ criterionIds: readonly string[],
435
+ ): { names: string[]; servesNone: boolean; answered: boolean } {
436
+ const names = criteriaNamedBy(issue, criterionIds);
437
+ const servesNone = `${issue.title}\n${issue.body ?? ""}`.includes(NAMES_NONE);
438
+ return { names, servesNone, answered: names.length > 0 || servesNone };
439
+ }
440
+
342
441
  export function mirrorRows(
343
442
  issues: readonly { readonly number: number; readonly title: string; readonly body?: string | null }[],
344
443
  criterionIds: readonly string[],
@@ -376,8 +475,7 @@ export function isUnblocked(summary: { readonly blockedBy: number }, assignees:
376
475
 
377
476
  /** The phase number in a milestone title, or null for a milestone that is not a phase. */
378
477
  export function phaseOf(milestoneTitle: string | null | undefined): number | null {
379
- const m = /\bPhase (\d+)\b/.exec(milestoneTitle ?? "");
380
- return m ? Number(m[1]) : null;
478
+ return readMilestoneTitle(milestoneTitle)?.phase ?? null;
381
479
  }
382
480
 
383
481
  /**
@@ -397,42 +495,41 @@ export function openFrontier(
397
495
  }
398
496
 
399
497
  /**
400
- * READY means *pick this up next*, which is narrower than *nothing is
401
- * blocking it*.
498
+ * READY means *pick this up next*: open, nothing blocking it, nobody on it.
499
+ *
500
+ * ## The phase gate used to be here, and the cap replaced it
402
501
  *
403
502
  * The first run of this made 36 of 46 open issues Ready, because the
404
- * repository has almost no dependency edges and an issue with no blockers is
405
- * trivially unblocked. A lane holding 36 items is the backlog with a
406
- * different name, and it answers the question Jason actually asked — *what
407
- * can I pick up* — with "anything", which is the same as not answering.
408
- *
409
- * So readiness carries the phase order too: an issue is Ready when it is
410
- * unblocked, unassigned, AND sits in the earliest phase that still has open
411
- * work. Later phases are not ready because the spec says they come later,
412
- * and that ordering is data — the placement table — not a judgement made
413
- * here.
414
- *
415
- * An issue with no phase milestone is never Ready. That is not a
416
- * demotion: 19 of the 46 open issues are reviewer findings that serve no
417
- * criterion and belong to no phase (ADR-003), and putting them in the lane
418
- * that means "this is the next convergence work" would make the lane lie.
503
+ * repository has almost no dependency edges and an issue with no blockers
504
+ * is trivially unblocked. A lane holding 36 items is the backlog with a
505
+ * different name, and it answers *what can I pick up* with "anything",
506
+ * which is the same as not answering.
507
+ *
508
+ * The fix at the time was to require the earliest phase with open work.
509
+ * That made the lane small by making it **narrow**, and the two are not
510
+ * the same thing: an unblocked, unclaimed issue in a later phase could not
511
+ * enter Ready even when the lane sat under its depth and the earlier phase
512
+ * had nothing available. The lane refused to answer the question it exists
513
+ * for, and called that an ordering.
514
+ *
515
+ * Size is now `readyCap` in `lib/board-ready-rule.ts`, derived from
516
+ * measured throughput, and phase is `readyOrder` in the same file. The
517
+ * lane is small because it is capped and phase-ordered — so the gate was
518
+ * doing a job two other mechanisms already do, and taking it off is
519
+ * Jason's call of 2026-11-05 on #1758.
520
+ *
521
+ * **An issue with no phase milestone is now eligible.** This docblock used
522
+ * to say "never Ready", on the grounds that a reviewer finding serving no
523
+ * criterion would make the lane lie. It sorts last instead — `readyOrder`
524
+ * ranks a null phase behind every numbered one — which keeps the ordering
525
+ * claim true without refusing work that is genuinely pickable.
419
526
  */
420
- export function isReady(
421
- item: {
422
- readonly state: string;
423
- readonly phase: number | null;
424
- readonly blockedByOpen: number;
425
- readonly assignees: number;
426
- },
427
- frontier: number | null,
428
- ): boolean {
527
+ export function isReady(item: {
528
+ readonly state: string;
529
+ readonly blockedByOpen: number;
530
+ readonly assignees: number;
531
+ }): boolean {
429
532
  if (item.state !== "OPEN") return false;
430
- // No separate `item.phase === null` guard. It was here, and the mutation
431
- // battery removed it with every case still green: `null !== frontier` is
432
- // already false for any non-null frontier, so the two lines were one
433
- // decider spelled twice, and no behavioural test could ever tell which of
434
- // them was live (`.claude/rules/checks-must-be-able-to-fail.md`).
435
- if (frontier === null) return false;
436
- if (item.phase !== frontier) return false;
437
533
  return isUnblocked({ blockedBy: item.blockedByOpen }, item.assignees);
438
534
  }
535
+
@@ -29,7 +29,7 @@
29
29
  * ## What this file deliberately does NOT do
30
30
  *
31
31
  * **It does not decide readiness.** `isReady` does, and it carries the
32
- * phase-frontier rule that stopped the Ready lane holding 36 of 46 open
32
+ * cap and ordering that stop the Ready lane holding 36 of 46 open
33
33
  * issues. A second decider here would agree with it on every input anybody
34
34
  * thought to test, so no behavioural case could tell which was live and a
35
35
  * mutation of either would leave the other holding the case up. `BR-7`
@@ -40,13 +40,31 @@
40
40
  * issues happened to close.
41
41
  */
42
42
  import { isReady } from "./board-mirror";
43
+ import { laneFor } from "./board-flow";
44
+ import { workVerdict } from "./board-lane-health";
45
+ import { inReadyScope, type ActiveMilestone } from "./board-ready-rule";
43
46
 
44
47
  /** One issue that the closed blocker was blocking. */
45
48
  export interface Dependent {
46
49
  readonly number: number;
47
50
  /** `OPEN` or `CLOSED`, as GraphQL spells it. */
48
51
  readonly state: string;
49
- readonly phase: number | null;
52
+ /**
53
+ * The milestone TITLE, or `null` — never a pre-read phase number (#1943).
54
+ * The family is half the order and a number has already discarded it; see
55
+ * `Rankable` in `lib/board-ready-rule.ts`.
56
+ */
57
+ readonly milestone: string | null;
58
+ /**
59
+ * Every label on the issue, verbatim — the ordering's SECOND source
60
+ * (#1853). An empty array means the issue carries none; this script never
61
+ * reads a page that can truncate labels, so there is no third state.
62
+ *
63
+ * It is not filtered to the ranked set here. `placementOf` owns which
64
+ * labels rank, and filtering on the way in would put a second opinion
65
+ * about that in this file.
66
+ */
67
+ readonly labels: readonly string[];
50
68
  /**
51
69
  * OPEN blockers only — the lifetime count never goes back down.
52
70
  *
@@ -92,19 +110,206 @@ export type FanoutDecision =
92
110
  * after `isReady` has already returned false, so a wrong or incomplete reason
93
111
  * costs a confusing log line and cannot move an issue. Keeping that ordering
94
112
  * is what stops it becoming the second decider described above.
113
+ *
114
+ * ## There is no "did not anticipate it" fallback, and that is deliberate
115
+ *
116
+ * One stood here until the phase gate was removed. With the two phase
117
+ * branches gone the remaining tests enumerate every input `isReady` reads,
118
+ * so the fallback became a line that could not run — the shape
119
+ * `.claude/rules/checks-must-be-able-to-fail.md` names, reading as a live
120
+ * safety net while catching nothing. ai-review round 1 of #1796.
121
+ *
122
+ * **Removing it required fixing a real gap first.** `isUnblocked` refuses
123
+ * anything that is not exactly `0`, and these guards asked `> 0`, so a
124
+ * negative count — which no GraphQL response produces, but nothing here
125
+ * rejected either — made `isReady` false and reached the fallback. The
126
+ * guards now match the contract they explain, which is what makes the
127
+ * enumeration genuinely exhaustive rather than nearly so.
128
+ *
129
+ * Exhaustiveness is asserted over the whole input grid in
130
+ * `test/board-ready-fanout.test.ts`, not claimed here: a condition added to
131
+ * `isReady` and not to this list makes a row return the wrong reason, and
132
+ * that row goes red.
95
133
  */
96
- function whyNotReady(d: Dependent, frontier: number | null): string {
134
+ export function whyNotReady(d: Dependent): string {
97
135
  if (d.state !== "OPEN") return `the issue is ${d.state}`;
98
136
  if (d.blockedByOpen === null) return "UNMEASURED — the dependency summary could not be read";
99
- if (d.blockedByOpen > 0) {
137
+ if (d.blockedByOpen !== 0) {
100
138
  return `${d.blockedByOpen} open blocker${d.blockedByOpen === 1 ? "" : "s"} remain`;
101
139
  }
102
140
  if (d.assignees === null) return "UNMEASURED — the assignee count could not be read";
103
- if (d.assignees > 0) return "somebody has claimed it";
104
- if (frontier === null) return "no phase has open work, so nothing is next";
105
- if (d.phase === null) return "no phase milestone — it serves no criterion (ADR-003)";
106
- if (d.phase !== frontier) return `phase ${d.phase} is behind the frontier at phase ${frontier}`;
107
- return "isReady said no and this reason list did not anticipate it";
141
+ /**
142
+ * #1941: "somebody has claimed it" stood here, and a claim is not work.
143
+ * The question is decided in one place — `workVerdict` in
144
+ * `lib/board-lane-health.ts` — and this is its second caller.
145
+ *
146
+ * **A `Dependent` carries none of the three evidence fields**, so every
147
+ * one is NOT READ and this call can only ever return UNMEASURED. That is
148
+ * not a wasted call and it is not a placeholder: the honest reason this
149
+ * issue is not going to Ready is that somebody has claimed it and nobody
150
+ * asked whether they are working on it. The sentence now says both, and
151
+ * it says it in the decider's words rather than this file's.
152
+ *
153
+ * Giving the fanout real evidence means adding a pull-request reading to
154
+ * `Dependent`, which is built in `scripts/board-ready.ts` — a file
155
+ * outside this issue and currently under review on #1971. Deliberately
156
+ * not done here.
157
+ */
158
+ const work = workVerdict({ openPullRequest: null, pushedBranch: null, localCommits: null });
159
+ return `somebody has claimed it, and ${work.why}`;
160
+ }
161
+
162
+ /**
163
+ * A card already sitting in the Ready column, as the occupancy walk sees it.
164
+ *
165
+ * Deliberately not a `Dependent`. A `Dependent` is an APPLICANT — it carries
166
+ * `phase`, `labels`, `assignees` and `onBoard`, all of which exist to decide
167
+ * whether something may ENTER the lane. An incumbent is already in, already
168
+ * on the board by construction, and the only question asked of it is the one
169
+ * that can become false after promotion.
170
+ */
171
+ export interface Incumbent {
172
+ readonly number: number;
173
+ /** `Issue`, `PullRequest`, or whatever else GitHub puts on a board. */
174
+ readonly typename: string;
175
+ readonly state: string | null;
176
+ /** The board column this card is in, or `null` when it has no Status value. */
177
+ readonly boardStatus: string | null;
178
+ /**
179
+ * OPEN blockers, or `null` for UNMEASURED — same contract as
180
+ * `Dependent.blockedByOpen`, and the same reason: a token that cannot read
181
+ * `issueDependenciesSummary` must not read as "nothing is blocking it".
182
+ */
183
+ readonly blockedByOpen: number | null;
184
+ /** The card's milestone title, or `null` — what the focus is judged on (SC-2741). */
185
+ readonly milestone: string | null;
186
+ /** Its labels, so a card carrying the expedite label keeps its slot. */
187
+ readonly labels: readonly string[];
188
+ }
189
+
190
+ /**
191
+ * The focus Ready's incumbents are held to (SC-2741). `expediteLabel` is
192
+ * `board.expediteLabel`, passed in — `lib/config-readers.ts` holds the one
193
+ * binding — and `null` exempts nobody.
194
+ */
195
+ export interface ReadyScope {
196
+ readonly active: ActiveMilestone;
197
+ readonly expediteLabel: string | null;
198
+ }
199
+
200
+ export type IncumbentDecision =
201
+ | { readonly number: number; readonly demote: true; readonly to: string; readonly why: string }
202
+ | { readonly number: number; readonly demote: false; readonly why: string };
203
+
204
+ /**
205
+ * Ready's entry condition, applied to the lane's current occupants (#1929).
206
+ *
207
+ * **Promotion is one-way with respect to blockers and this is the half that
208
+ * closes it.** A card is promoted when `isReady` says yes; nothing re-asks
209
+ * afterwards, because the event that would prompt it — `blocked_by_added` —
210
+ * exists on the REST timeline and emits no webhook. Measured on #1495:
211
+ * promoted 00:41:41Z, blocked 02:01:08Z, zero workflow runs started at the
212
+ * second timestamp against four unfiltered `issues` subscribers.
213
+ *
214
+ * Three things it deliberately does not do:
215
+ *
216
+ * - **It does not decide readiness.** The reason text is `whyNotReady`'s
217
+ * and the destination lane is `laneFor`'s. Two deciders for either
218
+ * question would agree on every input anybody tests and a mutation of
219
+ * one would leave the other holding the case up.
220
+ * - **It touches only the Ready column.** An issue in In progress is
221
+ * allowed an open blocker — somebody has claimed it, and yanking their
222
+ * card back would be this rule acting outside the condition it enforces.
223
+ * - **UNMEASURED never moves**, and a non-issue never moves, because a
224
+ * pull request parked in Ready holds a slot and has no dependency
225
+ * reading at all.
226
+ *
227
+ * The honest limit, stated rather than discovered: this corrects on the next
228
+ * qualifying event, not at the moment of blocking. Between the edge being
229
+ * added and the next close/assign/unassign/open/reopen anywhere on the
230
+ * repository, the lane is still wrong. That window is unavoidable while
231
+ * GitHub emits no event for a dependency change.
232
+ */
233
+ export function incumbentDecisions(
234
+ incumbents: readonly Incumbent[],
235
+ readyColumn: string,
236
+ /**
237
+ * REQUIRED, with no default: a caller that could omit it would keep every
238
+ * card outside the focus, which is the defect SC-2741 closes.
239
+ */
240
+ scope: ReadyScope,
241
+ ): IncumbentDecision[] {
242
+ const backwards = laneFor({ kind: "issue_blocked_in_ready" });
243
+ return incumbents.map((c): IncumbentDecision => {
244
+ if (c.boardStatus !== readyColumn) {
245
+ return { number: c.number, demote: false, why: `not in ${readyColumn}` };
246
+ }
247
+ if (c.typename !== "Issue") {
248
+ return { number: c.number, demote: false, why: `a ${c.typename} has no blocker graph` };
249
+ }
250
+ if (c.state !== "OPEN") {
251
+ return { number: c.number, demote: false, why: `the issue is ${c.state}` };
252
+ }
253
+ if (c.blockedByOpen === null) {
254
+ return {
255
+ number: c.number,
256
+ demote: false,
257
+ why: "UNMEASURED — the dependency summary could not be read",
258
+ };
259
+ }
260
+ if (c.blockedByOpen === 0) {
261
+ // **Unblocked, so the focus decides** (SC-2741). A blocked card is
262
+ // demoted for its blocker below, once, with that reason; this branch is
263
+ // for the card that meets every entry condition except being in the
264
+ // active milestone — a card dragged in by hand, or one promoted under
265
+ // the label-and-phase ordering this replaced. Without it, it holds its
266
+ // slot forever, because no other rule ever re-asks.
267
+ const expedited = scope.expediteLabel !== null && c.labels.includes(scope.expediteLabel);
268
+ if (inReadyScope(c, scope.active, expedited)) {
269
+ return { number: c.number, demote: false, why: "still unblocked and inside the active milestone" };
270
+ }
271
+ if (backwards.lane === null) {
272
+ return {
273
+ number: c.number,
274
+ demote: false,
275
+ why: `UNMEASURED — laneFor gave no destination: ${backwards.why}`,
276
+ };
277
+ }
278
+ return {
279
+ number: c.number,
280
+ demote: true,
281
+ to: backwards.lane,
282
+ why:
283
+ `${c.milestone === null ? "it has no milestone" : `it sits in ${c.milestone}`}, outside the ` +
284
+ `active milestone — ${scope.active.why}`,
285
+ };
286
+ }
287
+ // The lane itself is UNMEASURED if the one rule for moving backwards has
288
+ // no answer. Writing a literal here would be the second decider.
289
+ if (backwards.lane === null) {
290
+ return {
291
+ number: c.number,
292
+ demote: false,
293
+ why: `UNMEASURED — laneFor gave no destination: ${backwards.why}`,
294
+ };
295
+ }
296
+ return {
297
+ number: c.number,
298
+ demote: true,
299
+ to: backwards.lane,
300
+ why:
301
+ `${whyNotReady({
302
+ number: c.number,
303
+ state: c.state,
304
+ milestone: null,
305
+ labels: [],
306
+ blockedByOpen: c.blockedByOpen,
307
+ assignees: 0,
308
+ onBoard: true,
309
+ boardStatus: c.boardStatus,
310
+ })}, so it no longer meets ${readyColumn}'s entry condition`,
311
+ };
312
+ });
108
313
  }
109
314
 
110
315
  /**
@@ -112,7 +317,6 @@ function whyNotReady(d: Dependent, frontier: number | null): string {
112
317
  */
113
318
  export function fanoutDecisions(
114
319
  dependents: readonly Dependent[],
115
- frontier: number | null,
116
320
  readyColumn: string,
117
321
  ): FanoutDecision[] {
118
322
  return dependents.map((d): FanoutDecision => {
@@ -142,16 +346,77 @@ export function fanoutDecisions(
142
346
  // answered false. Refusing before the decider is what keeps `isReady` the
143
347
  // only thing that says yes.
144
348
  if (d.blockedByOpen === null || d.assignees === null) {
145
- return { number: d.number, move: false, why: whyNotReady(d, frontier) };
349
+ return { number: d.number, move: false, why: whyNotReady(d) };
146
350
  }
147
351
  const measured = { ...d, blockedByOpen: d.blockedByOpen, assignees: d.assignees };
148
- if (!isReady(measured, frontier)) {
149
- return { number: d.number, move: false, why: whyNotReady(d, frontier) };
352
+ if (!isReady(measured)) {
353
+ return { number: d.number, move: false, why: whyNotReady(d) };
150
354
  }
151
355
  return { number: d.number, move: true };
152
356
  });
153
357
  }
154
358
 
359
+ /** What the two candidate walks produced, as one set the decider reads once. */
360
+ export interface MergedCandidates<T> {
361
+ /** Every candidate, deduplicated by number, close-freed ones first. */
362
+ readonly candidates: readonly T[];
363
+ /** The numbers THIS close freed — the set the log names in full. */
364
+ readonly freed: ReadonlySet<number>;
365
+ }
366
+
367
+ /**
368
+ * The two candidate sources, merged into the one array the decider reads.
369
+ *
370
+ * ## Why both may run at once (#1917)
371
+ *
372
+ * A close is the one event that reliably FREES a slot in Ready, and it used to
373
+ * be the one event that could not refill the lane from the general pool:
374
+ * `.github/workflows/board-ready.yml` ran `--closed-issue` on `closed` and
375
+ * `--top-up` on everything else, so a close that unblocked nothing left the
376
+ * lane one short until a person ran a command by hand. Measured 2026-11-08 —
377
+ * #1889 closed, run `42528160275` reported "was blocking nothing", 33
378
+ * candidates were eligible against a depth of 2 with one slot free, and a
379
+ * hand-run top-up moved #1157 within seconds.
380
+ *
381
+ * ## The two sets are not disjoint, and the fan-out adds no candidate
382
+ *
383
+ * The top-up query asks for `states:[OPEN]` over the whole repository, so it
384
+ * already contains every OPEN issue a `blocking` list can produce. What the
385
+ * fan-out contributes is `freed`: the issues THIS close unblocked, which the
386
+ * caller names in full — movers and non-movers alike — where a top-up names
387
+ * only the movers. Concatenating instead of merging would hand the decider the
388
+ * same issue twice and let one close count against the cap twice.
389
+ *
390
+ * **It lives here rather than inline in the script so a case can hold it.** A
391
+ * `main()` that needs a live GraphQL endpoint cannot be asked this question.
392
+ *
393
+ * A node with no numeric `number` is carried through unchanged rather than
394
+ * dropped: it is unreadable rather than duplicate, and `truncatedReadings` and
395
+ * the caller's mapping are where that is judged.
396
+ */
397
+ export function mergeCandidateSources<T extends { readonly number?: unknown }>(
398
+ fromClose: readonly T[],
399
+ fromTopUp: readonly T[],
400
+ ): MergedCandidates<T> {
401
+ const freed = new Set<number>();
402
+ for (const n of fromClose) {
403
+ if (typeof n?.number === "number") freed.add(n.number);
404
+ }
405
+ const candidates: T[] = [];
406
+ const seen = new Set<number>();
407
+ // Close-freed first, so the log names what this event freed before the pool
408
+ // it was topped up from. Ordering does not decide promotion — `selectReady`
409
+ // sorts by `readyOrder` — so this is a reading order, not a priority.
410
+ for (const n of [...fromClose, ...fromTopUp]) {
411
+ if (typeof n?.number === "number") {
412
+ if (seen.has(n.number)) continue;
413
+ seen.add(n.number);
414
+ }
415
+ candidates.push(n);
416
+ }
417
+ return { candidates, freed };
418
+ }
419
+
155
420
  /** A GraphQL connection, as far as truncation is concerned. */
156
421
  interface MaybeTruncated {
157
422
  readonly pageInfo?: { readonly hasNextPage?: boolean } | null;
@@ -201,10 +466,28 @@ export function truncatedReadings(
201
466
  * Its `permission` field is one of `admin`, `write`, `read`, `none`, and an
202
467
  * unreadable response is `null` — which is UNMEASURED and refuses, because
203
468
  * a permission we could not read is not a permission we were granted.
469
+ *
470
+ * ## And the endpoint cannot answer about the owner
471
+ *
472
+ * `GITHUB_TOKEN` cannot read `collaborators/{actor}/permission` — it needs
473
+ * admin access — so on a run triggered by the repository owner the read comes
474
+ * back unreadable and `null` refuses the person who owns the board. Run
475
+ * `42080290624` is the record: the first execution of this lane that got as
476
+ * far as the decider, refusing `hornjason` on `hornjason/rungate`.
477
+ *
478
+ * The owner is trusted by identity rather than by a permission read, because
479
+ * the identity is a fact the run already holds and the permission is one it
480
+ * cannot obtain. An EMPTY actor never satisfies it: absent-and-absent are the
481
+ * same empty string, and `"" === ""` would hand a write to a run that
482
+ * identified nobody (BR-45).
204
483
  */
205
484
  export const WRITING_PERMISSIONS: readonly string[] = ["admin", "write", "maintain"];
206
485
 
207
- export function actorMayWrite(permission: string | null): boolean {
486
+ export function actorMayWrite(
487
+ permission: string | null,
488
+ identity: { readonly actor: string; readonly owner: string },
489
+ ): boolean {
490
+ if (identity.actor !== "" && identity.actor === identity.owner) return true;
208
491
  if (permission === null) return false;
209
492
  return WRITING_PERMISSIONS.includes(permission);
210
493
  }