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
@@ -38,12 +38,33 @@ import { existsSync, readFileSync } from "fs";
38
38
  import { isAbsolute, join } from "path";
39
39
  import { parseArgs } from "util";
40
40
  import { createGitHubClient } from "../lib/github";
41
+ import { enginePrefixReading, readExpediteLabel, readQueueLabel } from "../lib/config-readers";
42
+ import {
43
+ ghWithoutGhToken,
44
+ inMilestoneFamily,
45
+ readLiveIssues,
46
+ type GraphQlExec,
47
+ type LiveIssue,
48
+ } from "../lib/live-issues";
49
+ import {
50
+ activeMilestone,
51
+ heldReason,
52
+ readyCap,
53
+ readyOccupancy,
54
+ scopedCandidates,
55
+ selectReady,
56
+ type ActiveMilestone,
57
+ workNextReading,
58
+ type WorkNextReading,
59
+ type ReadyOccupancy,
60
+ } from "../lib/board-ready-rule";
61
+ import { measureClosedIssues } from "../lib/board-throughput";
62
+ import { readOpenIssueMilestones } from "../lib/active-milestone";
63
+ import { incumbentDecisions } from "../lib/board-ready-fanout";
41
64
  import {
42
65
  criterionIdsIn,
43
66
  isReady,
44
67
  mirrorRows,
45
- openFrontier,
46
- phaseOf,
47
68
  specCriteriaIn,
48
69
  } from "../lib/board-mirror";
49
70
 
@@ -54,7 +75,351 @@ import {
54
75
  */
55
76
  export const REFUSAL_EXIT = 1;
56
77
 
78
+ /**
79
+ * Which open issues in the engine's milestone family lack the queue label —
80
+ * #2062, SC-2609.
81
+ *
82
+ * `plan-issues --decompose` labels what it creates, and nothing labelled an
83
+ * issue somebody milestoned by hand: on 2026-11-12 six such issues took the
84
+ * `queue-label` reading (B6) from 12 of 12 to 6 of 12 (#2020). That reading
85
+ * counts open issues whose milestone is in the engine family, so this picks
86
+ * its population with the same {@link inMilestoneFamily} rather than a test
87
+ * of its own — two deciders of "engine issue" would disagree on some title,
88
+ * and the repair would leave the reading short while reporting nothing to do.
89
+ *
90
+ * A cut label list is `unreadable`, not missing: the label may be on the page
91
+ * that was not read. An issue whose label WAS read is fine either way.
92
+ */
93
+ export function queueLabelRepairs(
94
+ issues: readonly Pick<LiveIssue, "number" | "state" | "milestone" | "labels" | "labelsTruncated">[],
95
+ prefix: string,
96
+ queueLabel: string,
97
+ ): { add: number[]; unreadable: number[] } {
98
+ const add: number[] = [];
99
+ const unreadable: number[] = [];
100
+ for (const i of issues) {
101
+ if (i.state !== "OPEN" || !inMilestoneFamily(i.milestone, prefix)) continue;
102
+ if (i.labels.includes(queueLabel)) continue;
103
+ if (i.labelsTruncated === true) unreadable.push(i.number);
104
+ else add.push(i.number);
105
+ }
106
+ return { add, unreadable };
107
+ }
108
+
109
+ /**
110
+ * `board-mirror --queue-label --repo owner/name [--write]` — #2062, SC-2609.
111
+ *
112
+ * Reads the repository's open issues through the one reader the board
113
+ * readings use (`readLiveIssues`), and adds `board.queueLabel` to each that
114
+ * {@link queueLabelRepairs} names. It never touches the project board, so it
115
+ * runs on the job's own `GITHUB_TOKEN`: ADR-013 puts issue writes there and
116
+ * keeps `RUNGATE_PROJECT_TOKEN` to the board-mirror step that writes the
117
+ * Criteria column. `.github/workflows/phase-order.yml` runs both, as separate
118
+ * steps, when an issue's milestone changes.
119
+ *
120
+ * Idempotent like `plan-deps`: every run reads the whole tracker and adds only
121
+ * what is missing, so it does not matter which issue fired it, and an issue
122
+ * milestoned by a tool (whose `GITHUB_TOKEN` write fires no event) is repaired
123
+ * by the next run.
124
+ *
125
+ * Refuses, writing nothing, when the engine family or the queue label is not
126
+ * configured — a tree that never named a queue has no queue, not an empty one
127
+ * — or when any candidate's label list was cut.
128
+ */
129
+ export async function queueLabelRun(opts: {
130
+ repo: string;
131
+ prefix: string | null;
132
+ prefixUnmeasured: string | null;
133
+ queueLabel: string | null;
134
+ write: boolean;
135
+ exec?: GraphQlExec;
136
+ log?: (line: string) => void;
137
+ }): Promise<number> {
138
+ const log = opts.log ?? ((line: string) => console.log(line));
139
+ const exec = opts.exec ?? ghWithoutGhToken;
140
+ if (opts.prefix === null) {
141
+ log(
142
+ opts.prefixUnmeasured ??
143
+ "board-mirror: UNMEASURED — board.milestonePrefix is not set, so there is no engine family to label. Nothing written.",
144
+ );
145
+ return REFUSAL_EXIT;
146
+ }
147
+ if (opts.queueLabel === null) {
148
+ log("board-mirror: UNMEASURED — board.queueLabel is not set, so there is no queue to label into. Nothing written.");
149
+ return REFUSAL_EXIT;
150
+ }
151
+ const issues = await readLiveIssues(opts.repo, false, exec);
152
+ const { add, unreadable } = queueLabelRepairs(issues, opts.prefix, opts.queueLabel);
153
+ if (unreadable.length > 0) {
154
+ log(
155
+ `board-mirror: UNMEASURED — the label list was cut for ${unreadable.map(n => `#${n}`).join(", ")}, so ` +
156
+ `"${opts.queueLabel}" may be on a page that was not read. Nothing written.`,
157
+ );
158
+ return REFUSAL_EXIT;
159
+ }
160
+ if (add.length === 0) {
161
+ log(`board-mirror: every open "${opts.prefix} Phase" issue carries "${opts.queueLabel}" — nothing to add.`);
162
+ return 0;
163
+ }
164
+ // Every repair is attempted, and the run ends red naming each that failed
165
+ // (#2099). The first failure used to throw out of the loop, so the rest of
166
+ // the batch waited for the next run with no record of which were skipped.
167
+ const failed: string[] = [];
168
+ for (const n of add) {
169
+ if (opts.write) {
170
+ try {
171
+ exec(["issue", "edit", String(n), "--repo", opts.repo, "--add-label", opts.queueLabel]);
172
+ } catch (e) {
173
+ failed.push(`#${n} (${(e as Error).message})`);
174
+ log(` FAILED #${n} + ${opts.queueLabel}: ${(e as Error).message}`);
175
+ continue;
176
+ }
177
+ }
178
+ log(` ${opts.write ? "labelled" : "would label"} #${n} + ${opts.queueLabel}`);
179
+ }
180
+ if (!opts.write) log(`\n (reporting only — pass --write to apply)`);
181
+ if (failed.length > 0) {
182
+ log(`board-mirror: ${failed.length} of ${add.length} label write(s) failed: ${failed.join(", ")}. Every other was attempted.`);
183
+ return REFUSAL_EXIT;
184
+ }
185
+ return 0;
186
+ }
187
+
188
+ /**
189
+ * `owner/name`, or `null` for anything that is not exactly that.
190
+ *
191
+ * **`split("/")[1]` is `undefined` for `--repo rungate`, and a `!` only
192
+ * silences the type checker.** That `undefined` reached
193
+ * `measureClosedIssues` and surfaced as an opaque GraphQL error far from
194
+ * the typo that caused it — ai-review on #1795.
195
+ *
196
+ * Exported because the first version of this guard was inline in
197
+ * `main()`, where no case could reach it: the mutation battery removed
198
+ * the whole condition and read ZERO. A guard no test can observe is a
199
+ * line in a file (`.claude/rules/checks-must-be-able-to-fail.md`).
200
+ */
201
+ export function parseRepo(value: string): { owner: string; name: string } | null {
202
+ const parts = value.split("/");
203
+ if (parts.length !== 2) return null;
204
+ const [owner, name] = parts;
205
+ if (!owner || !name) return null;
206
+ return { owner, name };
207
+ }
208
+
209
+ /**
210
+ * The items this command may move, and how many of them hold Ready.
211
+ *
212
+ * **One array, read twice — not two filters that happen to agree.**
213
+ * `occupied` used to be counted over EVERY board item while the
214
+ * transitions were computed over the open ones, so anything the command
215
+ * can never move counted against the cap forever and silently starved
216
+ * promotions. A closed issue whose Status was never taken off Ready is
217
+ * the case ai-review named; a DRAFT board item, which has no state at
218
+ * all, is the one that was live on the board when this was written.
219
+ *
220
+ * Returning both from one pass is the point. Re-spelling
221
+ * `state === "OPEN"` beside the count would be two deciders answering one
222
+ * question, which no behavioural test can tell apart
223
+ * (`.claude/rules/checks-must-be-able-to-fail.md`) — and that is exactly
224
+ * how the two came to disagree. ai-review round 3 of #1795.
225
+ */
226
+ export function readyPopulation<T extends { state: string; status: string }>(
227
+ items: readonly T[],
228
+ ): { writable: T[]; occupied: number } {
229
+ const writable = items.filter(i => i.state === "OPEN");
230
+ return { writable, occupied: writable.filter(i => i.status === READY).length };
231
+ }
232
+
233
+ /**
234
+ * Ready's incumbents that have fallen outside the active milestone (#2007,
235
+ * SC-2741).
236
+ *
237
+ * `isReady` answers who may ENTER Ready, so an unblocked, unclaimed card
238
+ * already there computes `to = Ready` and its change was filtered out as no
239
+ * change — a card dragged in by hand, or left behind by a frontier move, held
240
+ * its slot forever. `scripts/board-ready.ts` demoted the same card through
241
+ * `incumbentDecisions`. This asks that same decider with the same scope, so
242
+ * the two Ready writers cannot disagree about an UNCLAIMED incumbent — this
243
+ * command never overwrites a claimed card (`mayWrite`, below), and claiming a
244
+ * card moves it out of Ready anyway — and it adds no
245
+ * predicate of its own (`.claude/rules/checks-must-be-able-to-fail.md`, two
246
+ * deciders that agree).
247
+ *
248
+ * Every item here is an Issue: the board query reads `... on Issue` only.
249
+ */
250
+ export function scopeDemotions<
251
+ T extends {
252
+ number: number;
253
+ state: string;
254
+ status: string;
255
+ blockedByOpen: number;
256
+ /** `false` when the blocker count was never read: the decider gets `null`, i.e. UNMEASURED. */
257
+ blockersRead?: boolean;
258
+ milestone: string | null;
259
+ labels: readonly string[];
260
+ },
261
+ >(items: readonly T[], active: ActiveMilestone, expediteLabel: string | null): Array<{ item: T; to: string }> {
262
+ const byNumber = new Map(items.map(i => [i.number, i]));
263
+ const decisions = incumbentDecisions(
264
+ items.map(i => ({
265
+ number: i.number,
266
+ typename: "Issue",
267
+ state: i.state,
268
+ boardStatus: i.status,
269
+ blockedByOpen: i.blockersRead === false ? null : i.blockedByOpen,
270
+ milestone: i.milestone,
271
+ labels: i.labels,
272
+ })),
273
+ READY,
274
+ { active, expediteLabel },
275
+ );
276
+ const out: Array<{ item: T; to: string }> = [];
277
+ for (const d of decisions) {
278
+ if (d.demote) out.push({ item: byNumber.get(d.number)!, to: d.to });
279
+ }
280
+ return out;
281
+ }
282
+
283
+ /**
284
+ * Split what this command MAY write into what the cap lets through.
285
+ *
286
+ * **The cap applies here too, and from the same function the workflow
287
+ * uses.** This command is the hand-run second CALLER of Ready's rule —
288
+ * not a second rule, which is the distinction that matters: it and
289
+ * `board-ready.yml` both read `lib/board-ready-rule.ts`, so they cannot
290
+ * size the lane differently. Before this, the workflow filled to a
291
+ * derived depth and one hand-run of this command refilled the lane to
292
+ * whatever happened to be eligible.
293
+ *
294
+ * **A demotion to Backlog is never capped**, and that is the half a
295
+ * naive implementation gets wrong. The cap bounds what may ENTER Ready;
296
+ * applying it to departures would pin a claimed or newly-blocked card in
297
+ * the lane for as long as the lane stayed full — the cap would start
298
+ * preserving exactly the staleness it exists to prevent.
299
+ *
300
+ * Exported so a case can hold it. Inline, the only way to observe it was
301
+ * to run the command against a live board.
302
+ */
303
+ export function splitReadyChanges<
304
+ T extends {
305
+ item: { number: number; milestone: string | null; labels: readonly string[]; status: string };
306
+ to: string;
307
+ },
308
+ >(
309
+ eligible: readonly T[],
310
+ cap: number | null,
311
+ occupied: number,
312
+ /**
313
+ * `board.milestonePrefix` — the ENGINE milestone family (#1943). Passed
314
+ * in, never read here: `lib/config-readers.ts` holds the one binding, and
315
+ * a second reader is two deciders over one config key.
316
+ */
317
+ enginePrefix: string | null,
318
+ /**
319
+ * `board.expediteLabel` (SC-2735), passed in for the reason `enginePrefix`
320
+ * is: `lib/config-readers.ts` holds the one binding.
321
+ */
322
+ expediteLabel: string | null,
323
+ /**
324
+ * The focus, from `activeMilestone` (SC-2741). REQUIRED: this writer used to
325
+ * promote on its own rule — any phase, label-ranked — and ADR-013 row 8
326
+ * ends that, so it draws from the same scope `scripts/board-ready.ts` does.
327
+ */
328
+ active: ActiveMilestone,
329
+ ): {
330
+ readyWritable: T[];
331
+ heldByCap: T[];
332
+ /** Eligible promotions outside the active milestone — waiting, not held by the cap. */
333
+ outOfScope: T[];
334
+ selection: ReturnType<typeof selectReady>;
335
+ /**
336
+ * The `work-this-next` reading (#1962), RETURNED rather than printed.
337
+ * This function runs on every invocation; only the caller knows whether
338
+ * `--ready` was passed, and announcing a refused promotion during a
339
+ * Criteria sync is a claim about something the run never attempted.
340
+ */
341
+ workNext: WorkNextReading;
342
+ /** The reading the caller must restate, never re-derive (#1852). */
343
+ occ: ReadyOccupancy;
344
+ } {
345
+ const promotions = eligible.filter(c => c.to === READY);
346
+ const demotions = eligible.filter(c => c.to !== READY);
347
+ // **A demotion in THIS batch frees a slot in this batch.** `occupied`
348
+ // is the pre-write count, so handing it to `selectReady` unchanged
349
+ // under-promotes by however many cards are leaving Ready in the same
350
+ // run — a frontier move that demotes three and promotes three would
351
+ // promote none. ai-review round 2 of #1795.
352
+ //
353
+ // Only demotions FROM Ready free anything. This command may also
354
+ // overwrite a card with no Status at all, and counting those would
355
+ // over-promote past the cap — the opposite error, reached by the
356
+ // obvious fix.
357
+ const freed = demotions.filter(c => c.item.status === READY).length;
358
+ // **This command's lane view is OPEN ISSUES ONLY, by design, so its two
359
+ // occupancy counts are one number** (#1852). `readyPopulation` filters to
360
+ // `state === "OPEN"` before counting, deliberately: a closed issue left on
361
+ // Ready counted against the cap forever and starved promotions
362
+ // (ai-review round 3 of #1795), and a draft has no state at all and is
363
+ // dropped before it reaches here.
364
+ //
365
+ // So WEDGED is unreachable from this caller, and that is HONEST rather
366
+ // than convenient: a lane held full by cards this command cannot see is a
367
+ // lane it also cannot clear, and `scripts/board-ready.ts` reads the whole
368
+ // column and reports it. What this caller must not do is invent a second
369
+ // free-slot calculation, which is the defect #1852 closed.
370
+ const after = Math.max(0, occupied - freed);
371
+ const occ = readyOccupancy(after, after, cap);
372
+ const candidates = promotions.map(c => ({
373
+ number: c.item.number,
374
+ milestone: c.item.milestone,
375
+ labels: c.item.labels,
376
+ }));
377
+ // The `work-this-next` promotion (#1962), bounded by `cap` — the SAME
378
+ // depth `occ` was built from, not a second reading of it. This is the
379
+ // writer, so this is where the label stops being a report and becomes the
380
+ // order cards are actually written in.
381
+ //
382
+ // `COMPLETE`: these candidates are the board's own items, which is the
383
+ // whole of what this lane draws from, so the ratio has a denominator
384
+ // somebody chose.
385
+ //
386
+ // **It does not log.** This function is called on every run, including a
387
+ // plain `--field Criteria --write` that never passed `--ready` — round 2
388
+ // of #1971's review found it announcing a refused Ready promotion during
389
+ // a Criteria sync, which is a claim about something the run did not
390
+ // attempt. The reading is RETURNED and the caller prints it under
391
+ // `--ready`, where it is true.
392
+ const workNext = workNextReading(candidates, cap, "COMPLETE", expediteLabel);
393
+ // The one scope (SC-2741): the active milestone plus honoured expedite cards.
394
+ const scoped = scopedCandidates(candidates, active, workNext.honoured);
395
+ const waiting = new Set(scoped.outOfScope.map(c => c.number));
396
+ const selection = selectReady(scoped.inScope, occ, enginePrefix, workNext.honoured);
397
+ // **Written in the order `selectReady` chose, not in board order.**
398
+ // A `filter` over `promotions` re-derives the right MEMBERSHIP in the
399
+ // wrong SEQUENCE, so the log and the write order stop matching the
400
+ // phase-then-age ranking the lane is supposed to express — and a run
401
+ // that dies part-way through would have written an arbitrary subset
402
+ // rather than the highest-ranked one. ai-review round 2 of #1795.
403
+ const byNumber = new Map(promotions.map(c => [c.item.number, c]));
404
+ const chosen = selection.promote.map(p => byNumber.get(p.number)!).filter(Boolean);
405
+ const chosenNumbers = new Set(chosen.map(c => c.item.number));
406
+ return {
407
+ readyWritable: [...demotions, ...chosen],
408
+ heldByCap: promotions.filter(c => !chosenNumbers.has(c.item.number) && !waiting.has(c.item.number)),
409
+ outOfScope: promotions.filter(c => waiting.has(c.item.number)),
410
+ selection,
411
+ occ,
412
+ workNext,
413
+ };
414
+ }
415
+
57
416
  const USAGE = `rungate board-mirror --project <node-id> [--spec <spec.md>] [--field <name>] [--write] [--ready] [--json]
417
+ rungate board-mirror --queue-label --repo <owner/name> [--write]
418
+
419
+ --queue-label instead of the board, add board.queueLabel to every open
420
+ issue in the engine's milestone family that lacks it (#2062).
421
+ Needs --repo, and refuses --project: it is an issue write made
422
+ with the repository's own token, never the board token.
58
423
 
59
424
  --project the ProjectV2 node id, e.g. PVT_kwHO…
60
425
  --spec narrow the column to ONE spec's criteria. Omit it — which is the
@@ -65,6 +430,10 @@ const USAGE = `rungate board-mirror --project <node-id> [--spec <spec.md>] [--fi
65
430
  already exist on the project — this does not create one, because
66
431
  a typo would silently add a column nobody looks at.
67
432
  --write write the field. Without it nothing is mutated.
433
+ --repo owner/name — required with --ready, which derives Ready's depth
434
+ from how much that repository delivered. A board can span
435
+ repositories and carries no single answer, so there is no
436
+ default: without it the depth is UNMEASURED and nothing moves.
68
437
  --ready also move Status between Backlog and Ready from the OPEN
69
438
  blocked-by count. Implies nothing unless --write is given too.
70
439
  --json the whole reading.`;
@@ -84,9 +453,18 @@ interface Item {
84
453
  assignees: number;
85
454
  blockedByOpen: number;
86
455
  blockedByTotal: number;
456
+ /**
457
+ * Whether `issueDependenciesSummary` came back at all. GitHub omits it when
458
+ * the token cannot read it, and `blockedByOpen` above defaults that to 0
459
+ * for the promotion path; the incumbent decider must see UNMEASURED
460
+ * instead (review of #2027).
461
+ */
462
+ blockersRead: boolean;
87
463
  criteriaCell: string;
88
- milestone: string;
89
- phase: number | null;
464
+ /** The milestone TITLE, or `null` — the contract `Rankable` states (#1965). */
465
+ milestone: string | null;
466
+ /** Ordering's second source when no milestone places the issue (#1853). */
467
+ labels: readonly string[];
90
468
  }
91
469
 
92
470
  const ITEMS_QUERY = `query($project: ID!, $field: String!, $after: String) {
@@ -105,6 +483,7 @@ const ITEMS_QUERY = `query($project: ID!, $field: String!, $after: String) {
105
483
  ... on Issue {
106
484
  number title body state
107
485
  milestone { title }
486
+ labels(first: 20) { pageInfo { hasNextPage } nodes { name } }
108
487
  assignees { totalCount }
109
488
  issueDependenciesSummary { blockedBy totalBlockedBy }
110
489
  }
@@ -128,6 +507,8 @@ export async function main(argv: string[]): Promise<number> {
128
507
  ready: { type: "boolean", default: false },
129
508
  json: { type: "boolean", default: false },
130
509
  "project-root": { type: "string" },
510
+ repo: { type: "string" },
511
+ "queue-label": { type: "boolean", default: false },
131
512
  },
132
513
  allowPositionals: false,
133
514
  });
@@ -136,6 +517,37 @@ export async function main(argv: string[]): Promise<number> {
136
517
  return REFUSAL_EXIT;
137
518
  }
138
519
  const { values } = parsed;
520
+ // **`split("/")[1]` is `undefined` for `--repo rungate`, and the `!`
521
+ // only silences the type checker.** That `undefined` reaches
522
+ // `measureClosedIssues` and surfaces as an opaque GraphQL error far
523
+ // from the typo that caused it. Validated here, where the message can
524
+ // name the flag. ai-review on #1795.
525
+ if (values.repo !== undefined && parseRepo(values.repo) === null) {
526
+ console.error(`board-mirror: --repo must be owner/name, got "${values.repo}"\n\n${USAGE}`);
527
+ return REFUSAL_EXIT;
528
+ }
529
+ // #2062: the label mode is its own run. It holds the repository's token and
530
+ // the board mode holds the board token (ADR-013), so one invocation doing
531
+ // both would need the widened credential that decision forbids.
532
+ if (values["queue-label"]) {
533
+ if (values.project !== undefined || values.ready) {
534
+ console.error(`board-mirror: --queue-label is its own run — it refuses --project and --ready\n\n${USAGE}`);
535
+ return REFUSAL_EXIT;
536
+ }
537
+ if (values.repo === undefined) {
538
+ console.error(`board-mirror: --queue-label needs --repo owner/name\n\n${USAGE}`);
539
+ return REFUSAL_EXIT;
540
+ }
541
+ const labelRoot = values["project-root"] ?? process.cwd();
542
+ const engine = enginePrefixReading(labelRoot);
543
+ return queueLabelRun({
544
+ repo: values.repo,
545
+ prefix: engine.prefix,
546
+ prefixUnmeasured: engine.unmeasured,
547
+ queueLabel: readQueueLabel(labelRoot),
548
+ write: values.write,
549
+ });
550
+ }
139
551
  if (!values.project) {
140
552
  console.error(`board-mirror: --project is required\n\n${USAGE}`);
141
553
  return REFUSAL_EXIT;
@@ -214,6 +626,21 @@ export async function main(argv: string[]): Promise<number> {
214
626
  fieldId = node.field.id;
215
627
  for (const n of node.items.nodes) {
216
628
  if (!n.content?.number) continue; // a draft item has no issue
629
+ // **A truncated label list is UNMEASURED, not a short one** (#1853).
630
+ // Ordering reads a label when no milestone places the issue, so a
631
+ // ranked label sitting on page two makes this writer promote the
632
+ // issue as if nothing placed it — and that is indistinguishable from
633
+ // an issue nothing places. `scripts/board-ready.ts` refuses the same
634
+ // state; this file silently did not, which is the one-site-fixed
635
+ // shape ai-review round 1 of #1855 named.
636
+ if (n.content.labels?.pageInfo?.hasNextPage) {
637
+ console.error(
638
+ `board-mirror: #${n.content.number} carries more than 20 labels, so the label that ` +
639
+ `ranks it may be unread and its position in Ready would be wrong. UNMEASURED, ` +
640
+ `nothing written.`,
641
+ );
642
+ return REFUSAL_EXIT;
643
+ }
217
644
  items.push({
218
645
  itemId: n.id,
219
646
  number: n.content.number,
@@ -224,9 +651,20 @@ export async function main(argv: string[]): Promise<number> {
224
651
  assignees: n.content.assignees?.totalCount ?? 0,
225
652
  blockedByOpen: n.content.issueDependenciesSummary?.blockedBy ?? 0,
226
653
  blockedByTotal: n.content.issueDependenciesSummary?.totalBlockedBy ?? 0,
654
+ blockersRead: n.content.issueDependenciesSummary != null,
227
655
  criteriaCell: n.fieldValueByName?.text ?? "",
228
- milestone: n.content.milestone?.title ?? "",
229
- phase: phaseOf(n.content.milestone?.title),
656
+ // `null` and never `""` — ONE absent value, matching `Rankable` and
657
+ // the five other producers in the tree (#1965 round 4). `""` reads
658
+ // identically today only because `phaseOf` and `phaseInFamily`
659
+ // normalise it, so a `=== null` added to the ordering later would
660
+ // misbehave here and nowhere else.
661
+ milestone: n.content.milestone?.title ?? null,
662
+ // Ordering's second source (#1853). This writer promotes too, so a
663
+ // mirror run that ranked everything milestone-less as UNPLACED
664
+ // would order by age exactly where the fan-out no longer does.
665
+ labels: (n.content.labels?.nodes ?? [])
666
+ .map((l: any) => l?.name)
667
+ .filter((x: any) => typeof x === "string"),
230
668
  });
231
669
  }
232
670
  if (!node.items.pageInfo.hasNextPage) break;
@@ -240,11 +678,70 @@ export async function main(argv: string[]): Promise<number> {
240
678
  .filter(i => (byNumber.get(i.number)?.text ?? "") !== i.criteriaCell)
241
679
  .map(i => ({ item: i, to: byNumber.get(i.number)!.text }));
242
680
 
243
- const frontier = openFrontier(items);
244
- const readyChanges = items
245
- .filter(i => i.state === "OPEN")
246
- .map(i => ({ item: i, to: isReady(i, frontier) ? READY : BACKLOG }))
681
+ // The ENGINE milestone family, from this project's own config (#1943),
682
+ // and whether the absence of one was MEASURED — round 3 of #1965's review.
683
+ //
684
+ // This is the call site that matters most and the one I left behind when I
685
+ // fixed the other two: `board-mirror --ready --write` is the only thing
686
+ // that writes the Ready lane. A `null` prefix orders by phase alone, so a
687
+ // root with no config promotes `Convergence Phase 3` ahead of `Pipeline
688
+ // Phase 6` — the exact pre-#1943 ordering, written to the board, in
689
+ // silence. `enginePrefixReading` tells that apart from a tree that
690
+ // genuinely declares one family.
691
+ const engine = enginePrefixReading(root);
692
+ if (engine.unmeasured !== null) console.error(` ${engine.unmeasured}`);
693
+ const enginePrefix = engine.prefix;
694
+ // A board can span repositories, so there is no repository to default
695
+ // to and no honest depth without one. UNMEASURED, and nothing is
696
+ // promoted on a null cap.
697
+ // Re-parsed rather than carried, so there is one spelling of what a
698
+ // repository argument is. `main` has already refused anything this
699
+ // returns null for.
700
+ const repo = values.repo === undefined ? null : parseRepo(values.repo);
701
+
702
+ // **The focus is read over every OPEN issue in the REPOSITORY (#2037)**,
703
+ // claimed and blocked ones included (SC-2741) — the population
704
+ // `scripts/board-ready.ts` reads. It used to be the open cards on this
705
+ // board, so an earlier-phase issue that never reached the board (a failed
706
+ // intake run) moved this writer's focus and not the workflow's: two Ready
707
+ // writers, two answers.
708
+ //
709
+ // Read only under `--ready` with a repository, the one case that writes
710
+ // Ready. With no reading there is no focus — not a focus of "nothing",
711
+ // which `activeMilestone` reports as `title: null` and which puts every
712
+ // incumbent out of scope.
713
+ const openInRepo =
714
+ values.ready && repo
715
+ ? await readOpenIssueMilestones((q, v) => client.graphql(q, v), repo.owner, repo.name)
716
+ : null;
717
+ const active: ActiveMilestone =
718
+ openInRepo !== null
719
+ ? activeMilestone(openInRepo, enginePrefix)
720
+ : {
721
+ title: null,
722
+ why: !values.ready
723
+ ? "not computed — --ready was not passed"
724
+ : repo === null
725
+ ? "UNMEASURED — pass --repo owner/name; the focus is read from the repository's open issues"
726
+ : `UNMEASURED — the open issues of ${values.repo} could not be read, so no focus was computed`,
727
+ };
728
+ const expediteLabel = readExpediteLabel(root);
729
+
730
+ const { writable, occupied } = readyPopulation(items);
731
+ const readyChanges = writable
732
+ .map(i => ({ item: i, to: isReady(i) ? READY : BACKLOG }))
247
733
  .filter(c => c.to !== c.item.status);
734
+ // #2007: an incumbent outside the focus, which `isReady` alone keeps. A card
735
+ // already changing (blocked, so leaving for Backlog) is not added twice.
736
+ const changing = new Set(readyChanges.map(c => c.item.number));
737
+ // Only on a focus that was READ (#2037). An unread focus has `title: null`,
738
+ // and every incumbent is out of scope against that — a missing `--repo`
739
+ // would empty the lane.
740
+ if (openInRepo !== null) {
741
+ for (const d of scopeDemotions(writable, active, expediteLabel)) {
742
+ if (!changing.has(d.item.number)) readyChanges.push(d);
743
+ }
744
+ }
248
745
 
249
746
  // An assignee is a person saying "mine". Where their card sits is then
250
747
  // theirs to decide, and demoting a claimed issue to Backlog makes it look
@@ -253,9 +750,27 @@ export async function main(argv: string[]): Promise<number> {
253
750
  // may have claimed the issue.
254
751
  const mayWrite = (c: { item: Item }) =>
255
752
  MAY_OVERWRITE.includes(c.item.status) && c.item.assignees === 0;
256
- const readyWritable = readyChanges.filter(mayWrite);
753
+ const eligible = readyChanges.filter(mayWrite);
257
754
  const readySkipped = readyChanges.filter(c => !mayWrite(c));
258
755
 
756
+ // **Gated on `--ready`, not merely on `--repo`.** This pages every
757
+ // closed issue in the repository, and a plain Criteria sync that
758
+ // happens to pass `--repo` has no use for a depth. ai-review round 2
759
+ // of #1795.
760
+ const closedReadings =
761
+ values.ready && repo
762
+ ? await measureClosedIssues((q, v) => client.graphql(q, v), repo.owner, repo.name)
763
+ : null;
764
+ const cap = closedReadings === null ? null : readyCap(closedReadings.throughput);
765
+ const { readyWritable, heldByCap, outOfScope, selection, occ, workNext } = splitReadyChanges(
766
+ eligible,
767
+ cap,
768
+ occupied,
769
+ enginePrefix,
770
+ expediteLabel,
771
+ active,
772
+ );
773
+
259
774
  if (values.json) {
260
775
  console.log(
261
776
  JSON.stringify(
@@ -267,6 +782,50 @@ export async function main(argv: string[]): Promise<number> {
267
782
  fieldChanges: fieldChanges.map(c => ({ number: c.item.number, from: c.item.criteriaCell, to: c.to })),
268
783
  readyWritable: readyWritable.map(c => ({ number: c.item.number, from: c.item.status, to: c.to })),
269
784
  readySkipped: readySkipped.map(c => ({ number: c.item.number, status: c.item.status })),
785
+ // The depth and what it held back, so a consumer reading this
786
+ // JSON can tell "nothing was eligible" from "the lane is full"
787
+ // from "the depth could not be read". Three different facts
788
+ // that all used to come out as an empty `readyWritable`.
789
+ readyCap: cap,
790
+ readyOccupied: occupied,
791
+ readyHeldByCap: heldByCap.map(c => c.item.number),
792
+ // Both gated on `--ready`, like `workNext` below: without it no Ready
793
+ // decision was attempted (ai-review round 2 of #2006).
794
+ readyFocus: values.ready ? active.title : null,
795
+ readyOutOfScope: values.ready ? outOfScope.map(c => c.item.number) : null,
796
+ // ai-review round 4. The text branch below printed the work-next
797
+ // reading and this one did not, so a consumer parsing the JSON
798
+ // could not see that an ordering it is being handed was promoted
799
+ // — or REFUSED. The two branches render the same run; a field
800
+ // that exists in one of them is a field that silently does not
801
+ // exist for whoever reads the other.
802
+ //
803
+ // `honoured` is a Set and would serialise as `{}`, which is the
804
+ // Silent Default Substitution shape: present, empty, and
805
+ // indistinguishable from "nothing was promoted". Emitted as a
806
+ // sorted array.
807
+ //
808
+ // **Gated on `--ready`, exactly as the text branch is.** Round 5
809
+ // caught the first cut of this emitting unconditionally: with
810
+ // `--ready` absent, `cap` is forced `null` above, so a plain
811
+ // `--field Criteria --write --json` sync reported
812
+ // `status: "UNMEASURED"` and a `why` saying nothing was promoted
813
+ // — a claim about a promotion the run never attempted. That is
814
+ // round 2's finding, recommitted on the other surface by the fix
815
+ // for round 4.
816
+ //
817
+ // `null` is the honest value for "Ready was not requested", and
818
+ // it is distinguishable from the UNMEASURED object, which means
819
+ // "it was requested and the depth could not be read".
820
+ workNext: values.ready
821
+ ? {
822
+ status: workNext.status,
823
+ carrying: workNext.carrying,
824
+ honoured: [...workNext.honoured].sort((a, b) => a - b),
825
+ cap: workNext.cap,
826
+ why: workNext.why,
827
+ }
828
+ : null,
270
829
  wrote: values.write,
271
830
  },
272
831
  null,
@@ -285,9 +844,31 @@ export async function main(argv: string[]): Promise<number> {
285
844
  if (fieldChanges.length === 0) console.log(` every cell already agrees with its issue body`);
286
845
  if (values.ready) {
287
846
  console.log(
288
- `\n Ready lane — the frontier is ` +
289
- (frontier === null ? `nowhere: no open issue sits in a phase` : `Phase ${frontier}`),
847
+ `\n Ready lane — unblocked, unclaimed, and in the active milestone (SC-2741)`,
290
848
  );
849
+ console.log(` Focus: ${active.why}`);
850
+ if (outOfScope.length > 0) {
851
+ console.log(` ${outOfScope.length} eligible issue(s) wait outside the active milestone`);
852
+ }
853
+ console.log(` depth: ${cap ?? "UNMEASURED"}. ${selection.why}`);
854
+ // Under `--ready` only (#1962, round 2): this run did attempt a Ready
855
+ // promotion, so a refusal here is a true statement about it.
856
+ if (workNext.status !== "NONE") console.log(` ${workNext.why}`);
857
+ if (cap === null && !values.repo) {
858
+ console.log(
859
+ ` pass --repo owner/name to derive the depth; a board can span repositories ` +
860
+ `so there is nothing to default to, and nothing is promoted without it`,
861
+ );
862
+ }
863
+ for (const c of heldByCap) {
864
+ // `heldReason(cap)`, never a literal. The literal was the exact
865
+ // defect ai-review found in `scripts/board-ready.ts` on #1794 —
866
+ // an unmeasured depth reported as a full lane — and I wrote it
867
+ // fresh here one pull request later, with the fix exported and
868
+ // in the tree. `test/board-ready-rule.test.ts` now refuses the
869
+ // string anywhere but its own binding.
870
+ console.log(` #${c.item.number} eligible but held: ${heldReason(occ)}`);
871
+ }
291
872
  for (const c of readyWritable) {
292
873
  console.log(` #${c.item.number} ${c.item.status || "(none)"} -> ${c.to} (${c.item.milestone || "no milestone"}; ${c.item.blockedByOpen} open of ${c.item.blockedByTotal} blockers, ${c.item.assignees} assignee(s))`);
293
874
  }