rungate 0.8.13 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -0,0 +1,979 @@
1
+ /**
2
+ * The entry point #1744's workflow runs: a blocker closed, so move whatever
3
+ * it freed to Ready.
4
+ *
5
+ * The decisions are `lib/board-ready-fanout.ts`'s and the readiness rule is
6
+ * `isReady`'s. This file is the I/O: read the closed issue's `blocking` list
7
+ * and the board, ask, and perform only the moves it was handed.
8
+ *
9
+ * ## Two candidate sources, one decider (#1842, G1)
10
+ *
11
+ * The fan-out above answers "what did THIS close free", and that is the whole
12
+ * of what it can answer. An issue that was **never blocked** appears in no
13
+ * `blocking` list, so no close can ever reach it — this file's own header used
14
+ * to say *"there is no 'became unblocked' event"* and stopped one sentence
15
+ * short of the consequence: a repository whose next piece of work has no
16
+ * dependencies had no event at all that could put it in Ready, and the lane
17
+ * was refilled by somebody running a command by hand. That is Claim 7's third
18
+ * falsification verbatim, surviving inside the mechanism written to remove it.
19
+ *
20
+ * `--top-up` is the second candidate source: every OPEN issue in the
21
+ * repository, asked the same question. It is deliberately a source and not a
22
+ * second decider — both paths converge on one `candidates.map(...)`, one
23
+ * `fanoutDecisions`, one `readyCap`, one `selectReady`. A mutation of any of
24
+ * those reddens both modes, which is the only reason a second entry point is
25
+ * safe here (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
26
+ *
27
+ * **The cap is what makes this safe to run on an ordinary event.** Top-up's
28
+ * eligible set is the 36-of-46 population `lib/board-ready-rule.ts` was
29
+ * written about; `selectReady` promotes at most `cap - occupied` of it and
30
+ * says so. Without that bound this mode would be "move the backlog to Ready".
31
+ *
32
+ * **It never adds an item to the board** and it never writes a field other
33
+ * than Status. Both are `board-mirror`'s, and an Action that grew either
34
+ * would make the board's contents depend on which issues happened to close.
35
+ *
36
+ * Exits non-zero only on a refusal, through `EXIT_REFUSED`. An absent
37
+ * credential is one: `GITHUB_TOKEN` cannot write ProjectsV2, and a run that
38
+ * could not look has not found nothing.
39
+ */
40
+ import {
41
+ actorMayWrite,
42
+ fanoutDecisions,
43
+ incumbentDecisions,
44
+ mergeCandidateSources,
45
+ readBoardCredential,
46
+ truncatedReadings,
47
+ type Dependent,
48
+ type Incumbent,
49
+ } from "../lib/board-ready-fanout";
50
+ import { enginePrefixReading, readExpediteLabel } from "../lib/config-readers";
51
+ import {
52
+ heldReason,
53
+ holdsReadySlot,
54
+ readyCap,
55
+ readyOccupancy,
56
+ activeMilestone,
57
+ scopedCandidates,
58
+ selectReady,
59
+ workNextReading,
60
+ } from "../lib/board-ready-rule";
61
+ import { measureClosedIssues } from "../lib/board-throughput";
62
+ // #1935: the endpoint is resolved, not hard-coded, so this script can be RUN
63
+ // by a test rather than only read. Loopback only — it carries a PAT.
64
+ import { API_BASE_ENV, resolveApiBase } from "../lib/github-api-base";
65
+ import { nextCursor } from "../lib/graphql-cursor";
66
+
67
+ /**
68
+ * Every refusal leaves through this one constant, so a mutant copy with it
69
+ * set to 0 proves each negative case observed the refusal and not something
70
+ * that happened to exit non-zero (`.claude/rules/checks-must-be-able-to-fail.md`).
71
+ */
72
+ export const EXIT_REFUSED = 2;
73
+
74
+ const READY_COLUMN = "Ready";
75
+
76
+ /**
77
+ * One query for the first page and every page after it.
78
+ *
79
+ * It was typed out twice, which is one edit away from two pages reading
80
+ * different fields — and a page that stopped carrying `fieldValues` would
81
+ * undercount Ready's occupancy and promote past the cap with nothing red.
82
+ */
83
+ // `number` is selected so the occupancy pass can recognise the ONE card the
84
+ // current event is moving out of Ready (#1905). A scalar, so it costs no
85
+ // page and nothing for BR-19 or BR-46 to weigh.
86
+ // `id` and `issueDependenciesSummary{blockedBy}` are both SCALAR selections —
87
+ // neither takes a `first:`, so BR-46's product is unchanged at 100 × 50 =
88
+ // 5,000, which is **a hundred times** under GitHub's 500,000 ceiling (#1929).
89
+ //
90
+ // That figure is load-bearing: the next person adding a selection here sizes
91
+ // it against this headroom. The first draft said "five hundred times", and
92
+ // round 2 of ai-review was right that round 1's fix had APPENDED a correction
93
+ // while leaving the wrong number as the leading claim — a reader who stops at
94
+ // the first number is told the margin is five times larger than it is.
95
+ //
96
+ // They are here because the occupancy pass is the only walk that
97
+ // already visits every card in Ready, and re-asking Ready's entry condition
98
+ // of its incumbents needs exactly two things the walk did not carry: the item
99
+ // to write through, and the blocker count to judge.
100
+ const BOARD_PAGE_QUERY = `query($p:ID!,$c:String){node(id:$p){... on ProjectV2{items(first:100,after:$c){
101
+ pageInfo{hasNextPage endCursor}
102
+ nodes{
103
+ id
104
+ fieldValues(first:50){pageInfo{hasNextPage} nodes{
105
+ ... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2FieldCommon{name}}}}}
106
+ content{__typename ... on Issue{number state milestone{title} issueDependenciesSummary{blockedBy}}}}}}}}`;
107
+
108
+ function arg(name: string): string | null {
109
+ const i = process.argv.indexOf(`--${name}`);
110
+ return i >= 0 && i + 1 < process.argv.length ? process.argv[i + 1] : null;
111
+ }
112
+
113
+ async function gql(
114
+ token: string,
115
+ base: string,
116
+ query: string,
117
+ variables: Record<string, unknown>,
118
+ ): Promise<any> {
119
+ const r = await fetch(`${base}/graphql`, {
120
+ method: "POST",
121
+ headers: {
122
+ authorization: `bearer ${token}`,
123
+ "content-type": "application/json",
124
+ accept: "application/vnd.github+json",
125
+ },
126
+ body: JSON.stringify({ query, variables }),
127
+ });
128
+ // **`r.ok` first, before the body means anything.** A GraphQL *query* error
129
+ // comes back 200 with an `errors` array, which is the check below and the
130
+ // usual path. An expired PAT, a secondary-rate-limit 403 and a 5xx come back
131
+ // with a plain `{"message": "..."}` body carrying NEITHER key — so `errors`
132
+ // was falsy, `data` was `undefined`, and this returned it. Every caller
133
+ // dereferences the result directly (`d.repository?.issue`, `all.node.items`,
134
+ // `.node?.field`), so an expired credential died as `Cannot read properties
135
+ // of undefined` rather than as this file's own UNMEASURED refusal. Caught in
136
+ // review of #1747; the same defect round 8 of #1740 fixed in
137
+ // `scripts/work-status.ts`. BR-38..BR-39 assert it across BOTH fetches here.
138
+ if (!r.ok) throw new Error(`${r.status} from the GraphQL endpoint`);
139
+ const j = (await r.json()) as { data?: any; errors?: unknown };
140
+ if (j.errors) throw new Error(JSON.stringify(j.errors));
141
+ return j.data;
142
+ }
143
+
144
+ /**
145
+ * The acting identity's permission ON THIS REPOSITORY, or `null` when the
146
+ * answer could not be read. `null` is UNMEASURED and refuses — see
147
+ * `actorMayWrite`.
148
+ */
149
+ async function actorPermission(
150
+ token: string,
151
+ base: string,
152
+ repo: string,
153
+ actor: string,
154
+ ): Promise<string | null> {
155
+ const r = await fetch(`${base}/repos/${repo}/collaborators/${actor}/permission`, {
156
+ headers: { authorization: `bearer ${token}`, accept: "application/vnd.github+json" },
157
+ });
158
+ // 404 is the documented answer for "not a collaborator", which is a READ
159
+ // of "no permission" rather than a failure to read. Everything else —
160
+ // 401, 403, 5xx — is unreadable and must not be flattened into it.
161
+ if (r.status === 404) return "none";
162
+ if (!r.ok) return null;
163
+ const j = (await r.json()) as { permission?: unknown };
164
+ return typeof j.permission === "string" ? j.permission : null;
165
+ }
166
+
167
+
168
+ async function main(): Promise<number> {
169
+ const repo = arg("repo");
170
+ const rawClosed = arg("closed-issue");
171
+ const project = arg("project");
172
+ const actor = arg("actor");
173
+ const apply = process.argv.includes("--write");
174
+ const topUp = process.argv.includes("--top-up");
175
+ // `Number(null)` is 0 and `Number.isFinite(0)` is true, so the first
176
+ // version of this guard passed a MISSING `--closed-issue` straight through
177
+ // and fanned out from issue 0. Caught in review of #1747. The absence is
178
+ // checked before the conversion, and the value must be a positive integer
179
+ // rather than merely finite — `1e9`, `0` and `-3` are all finite.
180
+ if (repo === null || project === null) {
181
+ console.error("UNMEASURED: --repo <owner/name> and --project <id> are both required");
182
+ return EXIT_REFUSED;
183
+ }
184
+ // **At least one candidate source.** An invocation with no source has
185
+ // nothing to look at and must not quietly become either one.
186
+ //
187
+ // BOTH used to be refused as well, on the reasoning that `--top-up` already
188
+ // contains every candidate `--closed-issue` can produce — true, and it is
189
+ // why the two are deduplicated below rather than concatenated. What that
190
+ // refusal cost is #1917: `closed` is the one event that reliably FREES a
191
+ // slot in Ready and it was the one event that could not refill the lane from
192
+ // the general pool, so a close that unblocked nothing left the lane one
193
+ // short until a person ran a command. Both sources now run in one
194
+ // invocation and both report, so neither loses silently.
195
+ if (!topUp && rawClosed === null) {
196
+ console.error(
197
+ "UNMEASURED: pass at least one of --closed-issue <n> (fan out from what that close freed) " +
198
+ "or --top-up (consider every open issue). Neither was given.",
199
+ );
200
+ return EXIT_REFUSED;
201
+ }
202
+ // Only reachable with a `--closed-issue` present, by the `null` check.
203
+ const closed = rawClosed === null ? null : Number(rawClosed);
204
+ if (closed !== null && (!Number.isInteger(closed) || closed <= 0)) {
205
+ console.error(`UNMEASURED: --closed-issue must be a positive integer, got "${rawClosed}"`);
206
+ return EXIT_REFUSED;
207
+ }
208
+ // **The ONE card this event is moving out of Ready** (#1905) — the issue
209
+ // `board-flow` is relaning in a run racing this one. Absent means the
210
+ // caller does not know, and then nothing is excluded, which is the safe
211
+ // direction: the lane reads one fuller than it will be and the board's
212
+ // health check reports that, where the other direction promotes past the
213
+ // depth.
214
+ //
215
+ // Validated like `--closed-issue` and for the same reason: `Number(null)`
216
+ // is 0, `Number("x")` is NaN, and neither is an issue. A malformed value
217
+ // REFUSES rather than silently excluding nothing — a flag that is ignored
218
+ // when it is wrong is a flag nobody can tell is working.
219
+ const rawMoving = arg("moving-issue");
220
+ if (rawMoving !== null) {
221
+ const n = Number(rawMoving);
222
+ if (!Number.isInteger(n) || n <= 0) {
223
+ console.error(`UNMEASURED: --moving-issue must be a positive integer, got "${rawMoving}"`);
224
+ return EXIT_REFUSED;
225
+ }
226
+ }
227
+ const movingIssue = rawMoving === null ? undefined : Number(rawMoving);
228
+
229
+ // **Before the credential is touched, let alone sent** (#1935). A refused
230
+ // override must not reach a line that has a token in hand.
231
+ const resolved = resolveApiBase(process.env[API_BASE_ENV]);
232
+ if (resolved.base === null) {
233
+ console.log(`::warning::UNMEASURED — ${resolved.why}`);
234
+ return EXIT_REFUSED;
235
+ }
236
+ const apiBase = resolved.base;
237
+
238
+ const credential = readBoardCredential(process.env);
239
+ if (credential.kind === "UNMEASURED") {
240
+ // A warning annotation, not silence, and not a skipped step. Naming the
241
+ // variable is the difference between a warning somebody can act on and
242
+ // one they learn to scroll past.
243
+ console.log(`::warning::UNMEASURED — ${credential.why}`);
244
+ return EXIT_REFUSED;
245
+ }
246
+ const token = credential.token;
247
+ const [owner, name] = repo.split("/");
248
+
249
+ // **The trust gate, before the first read.** `issues: [closed]` is
250
+ // triggerable by anyone who can close an issue — including an outside
251
+ // contributor closing their own — and this job holds a ProjectsV2 PAT.
252
+ //
253
+ // It was first an Actions `if:` reading
254
+ // `github.event.issue.author_association`, which is the association of
255
+ // whoever OPENED the issue and never whoever closed it; the ordinary
256
+ // direction is the damaging one, since a maintainer closing an outsider's
257
+ // issue was refused and the feature silently did not work for exactly the
258
+ // issues most likely to come from outside.
259
+ //
260
+ // Moving it into the script fixed the predicate and then put it too late:
261
+ // an untrusted close still started a job that read the board with the PAT
262
+ // before refusing to write. Security review caught the relocation. The
263
+ // permission answer depends on no board data, so it is taken here —
264
+ // before any `gql()` — and nothing privileged happens until it clears.
265
+ if (actor === null) {
266
+ console.log("::warning::UNMEASURED — --actor was not supplied, so nothing could be authorised. Nothing was read.");
267
+ return EXIT_REFUSED;
268
+ }
269
+ const permission = await actorPermission(token, apiBase, repo, actor);
270
+ // `owner` is already destructured from `--repo` above — there is no new
271
+ // input to forget to wire. `GITHUB_TOKEN` cannot read the permission
272
+ // endpoint, so without the identity the person who owns the board is
273
+ // refused by an answer the run was never able to obtain.
274
+ if (!actorMayWrite(permission, { actor, owner: owner ?? "" })) {
275
+ console.log(
276
+ `::warning::refusing to run: ${actor} has permission "${permission ?? "UNMEASURED"}" on ${repo}, ` +
277
+ `and this job holds a board-writing credential.`,
278
+ );
279
+ return EXIT_REFUSED;
280
+ }
281
+
282
+ // What the closed issue was blocking, with everything isReady reads.
283
+ //
284
+ // **Paginated.** `first: 50` was the third unpaginated read caught on this
285
+ // changeset's sibling, and I wrote it anyway. A blocker freeing more than
286
+ // fifty issues is unlikely and is exactly the case where silently moving
287
+ // the first fifty is worst: the lane looks correct and the tail is
288
+ // invisible.
289
+ //
290
+ // **And then the page sizes made the query unsendable.** `100 × 100 × 100`
291
+ // is 1,000,000 possible nodes against GitHub's limit of 500,000, and the
292
+ // limit is computed from the `first:` values BEFORE anything executes — so
293
+ // this failed identically on an empty board and a full one. Run
294
+ // `42083551881` is the record, and it is the first run that ever got far
295
+ // enough to find out, because five earlier faults refused before this line.
296
+ //
297
+ // The smaller pages cost nothing, because every one of these connections
298
+ // reports its own truncation through `truncatedReadings` and the run
299
+ // refuses rather than silently reading a prefix. An issue sits on one or
300
+ // two projects, and a project item carries a handful of field values;
301
+ // 100 × 20 × 50 is 100,000 and leaves a 5× margin for a nested read
302
+ // somebody adds later. BR-46 asserts the product over EVERY query here,
303
+ // because a page size that cannot be sent is a population.
304
+ const BLOCKING_QUERY = `query($o:String!,$n:String!,$i:Int!,$c:String){repository(owner:$o,name:$n){issue(number:$i){
305
+ blocking(first:100,after:$c){
306
+ pageInfo{hasNextPage endCursor}
307
+ nodes{
308
+ number state milestone{title} assignees{totalCount}
309
+ issueDependenciesSummary{blockedBy}
310
+ projectItems(first:20){
311
+ pageInfo{hasNextPage endCursor}
312
+ nodes{
313
+ id project{id}
314
+ fieldValues(first:50){
315
+ pageInfo{hasNextPage endCursor}
316
+ nodes{... on ProjectV2ItemFieldSingleSelectValue{
317
+ name optionId field{... on ProjectV2FieldCommon{id name}}}}}}}}}}}}`;
318
+ // **The top-up source, same shape and same sub-selections.** `issues` is the
319
+ // repository's own OPEN list rather than one issue's `blocking` list, and
320
+ // everything below this point cannot tell which produced the array — that
321
+ // is the property, not a coincidence. `states:[OPEN]` is asked for rather
322
+ // than filtered afterwards: a CLOSED issue is refused by `whyNotReady`
323
+ // anyway, so filtering here only decides how many pages get fetched.
324
+ //
325
+ // Page sizes are the fan-out's exactly. 100 × 20 × 50 is 100,000 against
326
+ // GitHub's 500,000 node limit, which it computes from the `first:` values
327
+ // before executing anything — BR-46, and run `42083551881` is why.
328
+ const TOP_UP_QUERY = `query($o:String!,$n:String!,$c:String){repository(owner:$o,name:$n){
329
+ issues(first:100,after:$c,states:[OPEN]){
330
+ pageInfo{hasNextPage endCursor}
331
+ nodes{
332
+ number state milestone{title} assignees{totalCount}
333
+ issueDependenciesSummary{blockedBy}
334
+ projectItems(first:20){
335
+ pageInfo{hasNextPage endCursor}
336
+ nodes{
337
+ id project{id}
338
+ fieldValues(first:50){
339
+ pageInfo{hasNextPage endCursor}
340
+ nodes{... on ProjectV2ItemFieldSingleSelectValue{
341
+ name optionId field{... on ProjectV2FieldCommon{id name}}}}}}}}}}}`;
342
+
343
+ // One array, two sources. Named for what it holds rather than where it came
344
+ // from, because nothing after this line may branch on the mode.
345
+ //
346
+ // **Both sources may fill it in one invocation** (#1917), and the two sets
347
+ // are not disjoint: `states:[OPEN]` is every open issue, so it already
348
+ // contains every OPEN candidate a `blocking` list can produce. The fan-out
349
+ // therefore contributes no candidate the top-up lacks — what it contributes
350
+ // is the LOG, which names every issue this close freed and says why each one
351
+ // did or did not move. So the union is deduplicated by number, and the
352
+ // fan-out walks first so those issues are named first.
353
+ //
354
+ // Measured 2026-11-08: #1889 closed, run `42528160275` reported "#1889 was
355
+ // blocking nothing. No issue changed.", 33 eligible candidates sat untouched
356
+ // at a depth of 2 with one slot free, and a hand-run `mode=top-up` moved
357
+ // #1157 within seconds (run `42530702081`).
358
+ // The merge is `mergeCandidateSources`'s, not this file's — a `main()` that
359
+ // needs a live endpoint cannot be asked whether it deduplicates, and the
360
+ // dedupe is what stops one close counting against the cap twice.
361
+ const closeNodes: any[] = [];
362
+ const openNodes: any[] = [];
363
+ // **A cursor each.** They used to share one, which worked only because the
364
+ // first walk always left it `null` — a coupling nothing asserted and the
365
+ // second walk would have resumed from the first one's page.
366
+ let closedCursor: string | null = null;
367
+ while (closed !== null) {
368
+ const d = await gql(token, apiBase, BLOCKING_QUERY, { o: owner, n: name, i: closed, c: closedCursor });
369
+ // **`issue(number:)` resolves to null, with no `errors`, for a number
370
+ // that is not an Issue.** Issues and pull requests share one numbering
371
+ // space and this field resolves only Issues, so a PR number — or a
372
+ // deleted or mistyped one — returns a well-formed response whose `issue`
373
+ // is null. The `issues: closed` trigger always supplies a real issue, but
374
+ // this script is also reachable through `workflow_dispatch` with a
375
+ // free-text `issue` input, and there an operator's typo crashed with
376
+ // `Cannot read properties of null (reading 'blocking')` — an opaque
377
+ // stack trace where every other unreadable state in this file reports
378
+ // UNMEASURED and refuses. Caught in review of #1744.
379
+ if (!d.repository?.issue) {
380
+ console.log(
381
+ `::warning::#${closed} is not an issue on ${owner}/${name} — it may be a pull ` +
382
+ `request number, a deleted issue, or a typo. UNMEASURED, nothing written.`,
383
+ );
384
+ return EXIT_REFUSED;
385
+ }
386
+ const page = d.repository.issue.blocking;
387
+ closeNodes.push(...page.nodes);
388
+ const step = nextCursor(page.pageInfo);
389
+ if (step.kind === "unreadable") {
390
+ console.log(
391
+ `::warning::#${closed}'s blocking list stopped paging — ${step.why}. ` +
392
+ `A partial list moves SOME of the issues this close unblocked, which is worse ` +
393
+ `than moving none. UNMEASURED, nothing written.`,
394
+ );
395
+ return EXIT_REFUSED;
396
+ }
397
+ closedCursor = step.kind === "more" ? step.cursor : null;
398
+ if (closedCursor === null) break;
399
+ }
400
+ let cursor: string | null = null;
401
+ while (topUp) {
402
+ const d = await gql(token, apiBase, TOP_UP_QUERY, { o: owner, n: name, c: cursor });
403
+ // `repository` is null with no `errors` for a name the credential cannot
404
+ // see or that does not exist — the same well-formed-but-empty response
405
+ // BR-37 covers on the fan-out path, at the site that path does not reach.
406
+ if (!d.repository?.issues) {
407
+ console.log(
408
+ `::warning::${owner}/${name} did not resolve to a repository with issues — it may be ` +
409
+ `renamed, deleted, or unreadable by this credential. UNMEASURED, nothing written.`,
410
+ );
411
+ return EXIT_REFUSED;
412
+ }
413
+ const page = d.repository.issues;
414
+ openNodes.push(...page.nodes);
415
+ const step = nextCursor(page.pageInfo);
416
+ if (step.kind === "unreadable") {
417
+ console.log(
418
+ `::warning::the repository's open issues stopped paging — ${step.why}. ` +
419
+ `A partial list tops Ready up from SOME of the candidates, which silently ` +
420
+ `changes WHICH work is next. UNMEASURED, nothing written.`,
421
+ );
422
+ return EXIT_REFUSED;
423
+ }
424
+ cursor = step.kind === "more" ? step.cursor : null;
425
+ if (cursor === null) break;
426
+ }
427
+ const { candidates, freed } = mergeCandidateSources(closeNodes, openNodes);
428
+ if (candidates.length === 0) {
429
+ // **No candidate to PROMOTE is not no work to do** (#1929, ai-review
430
+ // round 1). The demotion walk lives below, inside the occupancy pass,
431
+ // and this return used to skip it: `--closed-issue N --write` where #N
432
+ // was blocking nothing exits here, so a card in Ready that acquired a
433
+ // blocker stayed offered as startable. The production workflow always
434
+ // passes `--top-up` and never reaches that combination, which is
435
+ // exactly why it would have gone unnoticed — the script is a general
436
+ // CLI and its `--closed-issue`-only mode predates `--top-up`.
437
+ //
438
+ // Reported rather than silently continued: a run that promotes nothing
439
+ // and a run that promotes nothing and demotes one are different events.
440
+ console.log(
441
+ topUp
442
+ ? `${owner}/${name} has no open issues` +
443
+ (closed === null ? "" : `, and #${closed} was blocking nothing`) +
444
+ ". Nothing to promote; still checking Ready's incumbents."
445
+ : `#${closed} was blocking nothing. Nothing to promote; still checking Ready's incumbents.`,
446
+ );
447
+ }
448
+
449
+ // **This pass counts how full Ready is**, which the cap needs. It also
450
+ // used to read the phase frontier; that went with the phase gate, and the
451
+ // pass stayed because occupancy still has to come from the whole board
452
+ // rather than from the dependents this fan-out happens to be holding.
453
+ // One query string, used for the first page and every page after it: it
454
+ // used to be typed out twice, which is one edit away from two pages
455
+ // reading different fields.
456
+ const all = await gql(token, apiBase, BOARD_PAGE_QUERY, { p: project, c: null });
457
+ // **`node(id:)` is null for an id GitHub cannot resolve**, and the inline
458
+ // fragment resolves to an empty object for an id that exists and is not a
459
+ // ProjectV2. Both are SUCCESSFUL responses — no `errors`, so `gql()` returns
460
+ // normally per its own contract — and `all.node.items` therefore threw
461
+ // `TypeError: Cannot read properties of null (reading 'items')`. A stale or
462
+ // mistyped `RUNGATE_PROJECT_ID` (project recreated, deleted, or a typo in
463
+ // the variable) crashed with an opaque stack trace, in the one script that
464
+ // reports UNMEASURED and returns EXIT_REFUSED for every other unreadable
465
+ // node. Caught in review of #1747 — the class BR-37 covers on the
466
+ // `issue(number:)` path, at the site it did not reach.
467
+ //
468
+ // Both reads of this query go through the helper, not just the one the
469
+ // finding named: the first page and every page after it. BR-40..BR-41.
470
+ const itemsPage = (d: any): any => d?.node?.items ?? null;
471
+ let page = itemsPage(all);
472
+ if (page === null) {
473
+ console.log(
474
+ `::warning::the project id ${project} did not resolve to a ProjectV2 with items — it may be ` +
475
+ `deleted, recreated under a new id, or not a project at all. UNMEASURED, nothing written.`,
476
+ );
477
+ return EXIT_REFUSED;
478
+ }
479
+ let occupied = 0;
480
+ let dispatchable = 0;
481
+ let occupancyTruncated = false;
482
+ // **Every card the walk finds in Ready, so its entry condition can be
483
+ // re-asked of the lane's incumbents** (#1929). Collected here rather than
484
+ // in a second walk: a second walk would be a second reading of the same
485
+ // lane taken at a different moment, and the two could disagree with
486
+ // nothing able to say which was current. `blockedByOpen` is `?? null`,
487
+ // never `?? 0` — a token that cannot see `issueDependenciesSummary` has
488
+ // not read zero blockers, it has not read.
489
+ const readyIncumbents: (Incumbent & { readonly itemId: string | null })[] = [];
490
+ for (;;) {
491
+ for (const n of page.nodes) {
492
+ // **Occupancy counts every card in Ready, issue or not.** The lane's
493
+ // size is what a puller sees, and a pull request parked there takes a
494
+ // slot exactly as an issue does. Filtering to issues here would let
495
+ // the lane exceed its depth by however many PRs it holds, silently.
496
+ const status = (n.fieldValues?.nodes ?? []).find(
497
+ (f: any) => f?.field?.name === "Status",
498
+ )?.name;
499
+ // **An assigned open issue is mid-transition and holds nothing**
500
+ // (#1905). `board-flow.yml` fires on the same `issues: assigned`
501
+ // event this run did and moves that card to In progress; counting it
502
+ // here read the lane as full and promoted nothing, and a second later
503
+ // the lane was empty. `holdsReadySlot` is the one binding that
504
+ // decides, so there is one site to mutate.
505
+ //
506
+ // **One card, named by the event.** `movingIssue` is the issue this
507
+ // run was triggered for; `board-flow` is moving it out of Ready in a
508
+ // run racing this one, so counting it reads the lane as full and
509
+ // promotes nothing. Excluding EVERY assigned issue was the first
510
+ // spelling and it was unbounded — a card whose move failed stayed in
511
+ // Ready and stayed uncounted forever. The fields go in raw: there is
512
+ // no mapping in this loop, because a mapping here is a decision the
513
+ // rule module's battery cannot see.
514
+ const holds =
515
+ status === READY_COLUMN &&
516
+ holdsReadySlot(
517
+ { typename: n.content?.__typename, state: n.content?.state, number: n.content?.number },
518
+ movingIssue,
519
+ );
520
+ if (holds) {
521
+ occupied++;
522
+ // **And the second number, from the SAME pass** (#1852). A slot is a
523
+ // slot, but a slot nobody can start is not work. Counting these
524
+ // separately in a different file is what let this script report
525
+ // `2 of 2, full` while the report said `1 of 2, short` — both right,
526
+ // about different questions, with no site that could reconcile them.
527
+ // One pass over one lane, so `readyOccupancy` can refuse a pair
528
+ // counted over different populations.
529
+ if (n.content?.__typename === "Issue" && n.content?.state === "OPEN") dispatchable++;
530
+ }
531
+ // **Gathered on `holds`, which is the same predicate the cap uses.**
532
+ // `holdsReadySlot` returns false for exactly one card: the issue this
533
+ // run's own event is moving out of Ready (#1905). That card is
534
+ // mid-transition — `board-flow` is writing In progress for it in a run
535
+ // racing this one — and demoting it to Backlog on top of that write is
536
+ // two writers on one card in the same second, with last-writer-wins
537
+ // deciding where it lands. It is about to leave the lane anyway, and
538
+ // the next qualifying event re-checks it if it does not.
539
+ if (holds && n.content?.number !== undefined) {
540
+ readyIncumbents.push({
541
+ number: n.content.number,
542
+ typename: n.content.__typename,
543
+ state: n.content.state ?? null,
544
+ boardStatus: status,
545
+ blockedByOpen: n.content.issueDependenciesSummary?.blockedBy ?? null,
546
+ milestone: n.content.milestone?.title ?? null,
547
+ // Filled from the label pass below, which runs after this walk.
548
+ labels: [],
549
+ itemId: n.id ?? null,
550
+ });
551
+ }
552
+ // A Status on page two and no Status at all produce the same
553
+ // `undefined`, and one means "this card is not in Ready" while the
554
+ // other means "I could not look". An undercount here promotes past
555
+ // the cap, so it refuses rather than guesses.
556
+ if (n.fieldValues?.pageInfo?.hasNextPage) occupancyTruncated = true;
557
+ }
558
+ const step = nextCursor(page.pageInfo);
559
+ if (step.kind === "unreadable") {
560
+ console.log(
561
+ `::warning::the board stopped paging — ${step.why}. Ready's occupancy ` +
562
+ `was read only in part. UNMEASURED, nothing written.`,
563
+ );
564
+ return EXIT_REFUSED;
565
+ }
566
+ if (step.kind === "done") break;
567
+ const next = itemsPage(await gql(token, apiBase, BOARD_PAGE_QUERY, { p: project, c: step.cursor }));
568
+ if (next === null) {
569
+ // Mid-pagination, so a partial occupancy is already in hand — and an
570
+ // occupancy read from SOME of the board undercounts, which promotes
571
+ // past the cap. Refuse rather than finish with what arrived.
572
+ console.log(
573
+ `::warning::the project id ${project} stopped resolving part-way through the board, so ` +
574
+ `Ready's occupancy was read only in part. UNMEASURED, nothing written.`,
575
+ );
576
+ return EXIT_REFUSED;
577
+ }
578
+ page = next;
579
+ }
580
+
581
+ // ── Labels, in a query of their own — #1853 ──────────────────────────────
582
+ //
583
+ // Ordering reads a label when no milestone places the issue, so every
584
+ // candidate needs its labels. **They are not a sub-selection of the two
585
+ // queries above**, and the reason is BR-46: that detector multiplies every
586
+ // `first:` in a query, the two big ones are already at 100 × 20 × 50 =
587
+ // 100,000, and any further selection puts them over GitHub's 500,000 node
588
+ // ceiling as the detector models it. BR-45's own message says what to do —
589
+ // *split the query rather than shrinking a selection until it fits* — so
590
+ // this is the split. 100 × 20 = 2,000, two hundred and fifty times under.
591
+ // (Swept here rather than only at the site the finding named: the same
592
+ // "five hundred times under" slip was in the #1929 comment above, and one
593
+ // of two instances repaired is the shape this repo keeps paying for.)
594
+ //
595
+ // It is one pass over the repository's open issues rather than a lookup per
596
+ // candidate: the candidate set is a subset of it on both source paths, and
597
+ // one paged read cannot disagree with itself the way N reads can.
598
+ const LABELS_QUERY = `query($o:String!,$n:String!,$c:String){repository(owner:$o,name:$n){
599
+ issues(first:100,after:$c,states:[OPEN]){
600
+ pageInfo{hasNextPage endCursor}
601
+ nodes{number milestone{title} labels(first:20){pageInfo{hasNextPage endCursor} nodes{name}}}}}}`;
602
+ const labelsOf = new Map<number, string[]>();
603
+ // **Every open issue's milestone, from the SAME complete pass** (SC-2741).
604
+ // The focus is the lowest engine phase with ANY open issue — claimed and
605
+ // blocked ones included — so it cannot be read off the candidates, and on a
606
+ // pure fan-out the candidates are one close's dependents. This pass pages
607
+ // the whole open list on both paths, so the focus is read here.
608
+ const openMilestones: { milestone: string | null }[] = [];
609
+ let labelCursor: string | null = null;
610
+ for (;;) {
611
+ const d = await gql(token, apiBase, LABELS_QUERY, { o: owner, n: name, c: labelCursor });
612
+ const page = d?.repository?.issues;
613
+ if (!page) {
614
+ console.log(
615
+ "::warning::UNMEASURED — the open-issue label read returned no issues connection, so " +
616
+ "no candidate could be ranked by label and every one would have read UNPLACED. " +
617
+ "Nothing written.",
618
+ );
619
+ return EXIT_REFUSED;
620
+ }
621
+ for (const n2 of page.nodes ?? []) {
622
+ // A truncated label list is UNMEASURED, not a short list: the ranked
623
+ // label could be the one on page two, and ranking without it silently
624
+ // demotes the issue. Refusing here is the same choice the field-value
625
+ // read above makes.
626
+ if (n2?.labels?.pageInfo?.hasNextPage) {
627
+ console.log(
628
+ `::warning::UNMEASURED — #${n2.number} carries more than 20 labels, so its ranked ` +
629
+ "label may be unread and its position would be wrong. Nothing written.",
630
+ );
631
+ return EXIT_REFUSED;
632
+ }
633
+ openMilestones.push({ milestone: n2?.milestone?.title ?? null });
634
+ labelsOf.set(
635
+ n2.number,
636
+ (n2?.labels?.nodes ?? []).map((l: any) => l?.name).filter((x: any) => typeof x === "string"),
637
+ );
638
+ }
639
+ // SC-2721: `hasNextPage` is never read here. A file that decides "is
640
+ // there another page" itself is how three variants of one silent
641
+ // truncation reached main one at a time — `nextCursor` is the single
642
+ // binding, and an unreadable pageInfo is UNMEASURED rather than the end
643
+ // of the list. ai-review round 1 of #1855 caught this shape in the
644
+ // sibling file; the suite caught it here.
645
+ const step = nextCursor(page.pageInfo);
646
+ if (step.kind === "unreadable") {
647
+ console.log(
648
+ `::warning::UNMEASURED — the open-issue label read could not tell whether more pages ` +
649
+ `exist: ${step.why}. Candidates past this page would have ranked UNPLACED for an ` +
650
+ "instrument reason. Nothing written.",
651
+ );
652
+ return EXIT_REFUSED;
653
+ }
654
+ if (step.kind === "done") break;
655
+ labelCursor = step.cursor;
656
+ }
657
+ // The incumbents' labels, from the same pass, so a card carrying the
658
+ // expedite label keeps its slot (SC-2741). A closed incumbent has none here,
659
+ // and `incumbentDecisions` never reaches the scope for a closed card.
660
+ for (let k = 0; k < readyIncumbents.length; k++) {
661
+ readyIncumbents[k] = { ...readyIncumbents[k]!, labels: labelsOf.get(readyIncumbents[k]!.number) ?? [] };
662
+ }
663
+ for (const c of candidates) {
664
+ // Shaped as the GraphQL response so the mapping below reads one way,
665
+ // whichever query produced the candidate.
666
+ c.labels = { nodes: (labelsOf.get(c.number) ?? []).map(name2 => ({ name: name2 })) };
667
+ }
668
+
669
+ // A truncated sub-selection means this run saw PART of a dependent's board
670
+ // membership or part of its fields, and "I did not find the Status field"
671
+ // and "the Status field was on page two" produce the same `null`. Refuse
672
+ // the whole run rather than write a subset: a board half-moved is harder to
673
+ // notice than one that did not move.
674
+ const unreadable = truncatedReadings(candidates);
675
+ if (unreadable.length > 0) {
676
+ console.log(
677
+ `::warning::UNMEASURED — ${unreadable.map(n => `#${n}`).join(", ")} ` +
678
+ `returned more project items or field values than one page holds, so their board ` +
679
+ `membership was read only in part. Nothing was written.`,
680
+ );
681
+ return EXIT_REFUSED;
682
+ }
683
+
684
+ // **The item id, and nothing else.** This used to carry the Status field
685
+ // id read off the item's OWN Status value node, so an item with no Status
686
+ // at all produced no entry here and the write loop below logged "its
687
+ // Status field could not be located — UNMEASURED" for an item whose field
688
+ // id was perfectly resolvable, just not from there. An issue freshly added
689
+ // to the board with no column yet is the one this lane most needs to move,
690
+ // and it was the one guaranteed to be skipped. The field belongs to the
691
+ // PROJECT; it is resolved once, below. BR-34..BR-36.
692
+ const itemOf = new Map<number, { itemId: string }>();
693
+ const dependents: Dependent[] = candidates.map((b: any) => {
694
+ const item = (b.projectItems?.nodes ?? []).find((i: any) => i.project?.id === project);
695
+ const statusValue = item?.fieldValues?.nodes?.find((f: any) => f?.field?.name === "Status");
696
+ if (item) {
697
+ itemOf.set(b.number, { itemId: item.id });
698
+ }
699
+ return {
700
+ number: b.number,
701
+ state: b.state,
702
+ milestone: b.milestone?.title ?? null,
703
+ // The ordering's second source (#1853). Not `?? []` as a convenience:
704
+ // a page that could not carry labels would read as an issue with none,
705
+ // and that is UNPLACED rather than unmeasured. The LABELS_QUERY pass
706
+ // above refuses the run on a truncated label list and sets this on
707
+ // every candidate, so the only way it is empty is that the issue
708
+ // genuinely has none.
709
+ labels: (b.labels?.nodes ?? []).map((l: any) => l?.name).filter((n: any) => typeof n === "string"),
710
+ // NOT `?? 0`. An absent summary means the field could not be read —
711
+ // a token not scoped for it returns no object — and calling that zero
712
+ // says "nothing is blocking this", which moves a genuinely blocked
713
+ // issue to Ready. `null` is UNMEASURED and never moves.
714
+ blockedByOpen:
715
+ typeof b.issueDependenciesSummary?.blockedBy === "number"
716
+ ? (b.issueDependenciesSummary.blockedBy as number)
717
+ : null,
718
+ // NOT `?? 0`, for the same reason and in the damaging direction: a
719
+ // count read as zero says "nobody has claimed it", which MOVES an
720
+ // issue somebody is already working on into Ready.
721
+ assignees: typeof b.assignees?.totalCount === "number" ? (b.assignees.totalCount as number) : null,
722
+ // Two questions, two fields. `statusValue` is absent both when the
723
+ // issue is not on the board and when it is on the board with no
724
+ // Status value set, and only `item` can tell those apart.
725
+ onBoard: item !== undefined,
726
+ boardStatus: statusValue?.name ?? null,
727
+ };
728
+ });
729
+
730
+ const decisions = fanoutDecisions(dependents, READY_COLUMN);
731
+ // Each source says what IT brought, so a run given both cannot report one
732
+ // and perform the other — and each counts its own nodes rather than the
733
+ // merged array. ai-review round 1 of #1919 caught the merged count here:
734
+ // `BLOCKING_QUERY` has no `states:` filter where `TOP_UP_QUERY` asks for
735
+ // `[OPEN]`, so a close whose `blocking` list holds an already-closed
736
+ // dependent inflated a line that calls every one of them an open issue.
737
+ // The dependent is still named below, with `the issue is CLOSED` as its
738
+ // reason — it is the SUMMARY that was wrong, not the walk.
739
+ console.log(
740
+ [
741
+ closed === null ? null : `#${closed} closed, blocking ${freed.size} issue(s).`,
742
+ topUp ? `Top-up: ${openNodes.length} open issue(s) considered.` : null,
743
+ ]
744
+ .filter(l => l !== null)
745
+ .join(" "),
746
+ );
747
+ // **Every issue this close freed, and otherwise only the movers.** Naming
748
+ // each dependent and why it did or did not move is the fan-out's whole
749
+ // contribution — its candidates are already a subset of the top-up's — and
750
+ // a top-up holds every open issue, where ~250 lines of "somebody has
751
+ // claimed it" is a log nobody reads and the one line that mattered is
752
+ // missed. `freed` is empty on a pure top-up and holds every candidate on a
753
+ // pure fan-out, so this one expression is what both modes always did.
754
+ for (const dec of decisions) {
755
+ if (!freed.has(dec.number) && !dec.move) continue;
756
+ // "eligible", not "-> Ready": this runs BEFORE the focus and the cap, so
757
+ // a move announced here could be one the run then does not make (ai-review
758
+ // round 1 of #2006). What actually moves is printed with the selection.
759
+ console.log(dec.move ? ` #${dec.number} eligible for ${READY_COLUMN}` : ` #${dec.number} unchanged: ${dec.why}`);
760
+ }
761
+
762
+ // **The cap, between deciding and writing.** `fanoutDecisions` answers
763
+ // "may this issue be in Ready"; it does not and must not answer "is there
764
+ // room", because that is a property of the lane rather than of the issue,
765
+ // and putting both in one function means no mutation can tell them apart.
766
+ if (occupancyTruncated) {
767
+ console.log(
768
+ `::warning::at least one card's field values were read only in part, so Ready's occupancy ` +
769
+ `is a floor and not a count. UNMEASURED, nothing written.`,
770
+ );
771
+ return EXIT_REFUSED;
772
+ }
773
+ const closedReadings = await measureClosedIssues(
774
+ (query, variables) => gql(token, apiBase, query, variables),
775
+ owner,
776
+ name,
777
+ );
778
+ const throughput = closedReadings?.throughput ?? null;
779
+ const cap = throughput === null ? null : readyCap(throughput);
780
+ const milestoneOfNumber = new Map(dependents.map(d => [d.number, d.milestone]));
781
+ // Labels travel with the phase because ordering now reads both (#1853).
782
+ // A decision whose issue is not in `dependents` cannot be ranked by label
783
+ // either, and `[]` is the honest reading for it: UNPLACED, sorted behind
784
+ // everything the plan does place.
785
+ const labelsOfNumber = new Map(dependents.map(d => [d.number, d.labels]));
786
+ const eligible = decisions
787
+ .filter(dec => dec.move)
788
+ .map(dec => ({
789
+ ...dec,
790
+ milestone: milestoneOfNumber.get(dec.number) ?? null,
791
+ labels: labelsOfNumber.get(dec.number) ?? [],
792
+ }));
793
+ const occ = readyOccupancy(occupied, dispatchable, cap);
794
+ // The ENGINE milestone family, from this project's own config (#1943):
795
+ // a phase number only orders inside its own family. It SAYS when it could
796
+ // not read one, because a `null` prefix is the pre-#1943 ordering and a run
797
+ // from a directory with no config would otherwise turn the fix off in
798
+ // silence — round 2 of #1965's review.
799
+ const engine = enginePrefixReading(process.cwd());
800
+ if (engine.unmeasured !== null) console.error(` ${engine.unmeasured}`);
801
+ // The `work-this-next` promotion, bounded by the SAME depth the lane is
802
+ // judged against (#1962) — `cap`, two lines up, not a second reading. Over
803
+ // the bound or with the depth unreadable it promotes nothing and says so,
804
+ // so the lane can only ever be reordered by an ask somebody can audit.
805
+ // **`SLICE` on a fan-out, `COMPLETE` on a top-up** — round 2 of #1971's
806
+ // review. `--top-up` considers every open issue, so a ratio over its
807
+ // candidates has a denominator somebody chose; `--closed-issue N` walks
808
+ // only the direct dependents of that one close, and one labelled card out
809
+ // of three would otherwise read HONOURED while the repository held thirty
810
+ // carriers. A run given both is a top-up, because the fan-out's candidates
811
+ // are already a subset of it — the same sentence the dependent log above
812
+ // is written on.
813
+ const workNext = workNextReading(
814
+ eligible,
815
+ cap,
816
+ topUp ? "COMPLETE" : "SLICE",
817
+ readExpediteLabel(process.cwd()),
818
+ );
819
+ if (workNext.status !== "NONE") console.log(` ${workNext.why}`);
820
+ // **The focus, between eligibility and selection** (SC-2741, ADR-013 row
821
+ // 8). Ready refills from the active milestone and the expedite lane only;
822
+ // everything else eligible waits, counted rather than listed, because a
823
+ // top-up holds every open issue and the count is what a reader needs.
824
+ const active = activeMilestone(openMilestones, engine.prefix);
825
+ console.log(` Focus: ${active.why}`);
826
+ const scoped = scopedCandidates(eligible, active, workNext.honoured);
827
+ if (scoped.outOfScope.length > 0) {
828
+ console.log(` ${scoped.outOfScope.length} eligible issue(s) wait outside the active milestone.`);
829
+ }
830
+ const selection = selectReady(scoped.inScope, occ, engine.prefix, workNext.honoured);
831
+ console.log(
832
+ ` depth: ${cap ?? "UNMEASURED"}` +
833
+ (throughput === null
834
+ ? " (throughput could not be read)"
835
+ : ` (${throughput.delivered} delivered in ${throughput.days} days)`) +
836
+ `. ${selection.why}`,
837
+ );
838
+ // **An annotation, not a log line.** A WEDGED lane will not unstick on its
839
+ // own: no event refills it, because by cards it is full, and nothing ages
840
+ // out a draft or a parked pull request. It needs a person, so it is said
841
+ // where a person sees it without reading the job output.
842
+ if (occ.verdict === "WEDGED") {
843
+ console.log(`::warning::Ready is WEDGED — ${occ.why}`);
844
+ }
845
+ // Named, not merely dropped. An eligible issue that did not move because
846
+ // the queue is full is a different fact from one that was never eligible,
847
+ // and a reader who cannot tell them apart goes looking for a bug in the
848
+ // decider.
849
+ for (const dec of scoped.inScope) {
850
+ if (!selection.promote.includes(dec)) {
851
+ console.log(` #${dec.number} eligible but held: ${heldReason(occ)}`);
852
+ }
853
+ }
854
+
855
+ const moving = selection.promote;
856
+
857
+ // **Ready's entry condition, re-asked of the cards already in it** (#1929).
858
+ // Computed here, beside the promotions, because they are the same claim
859
+ // about the same lane: `isReady` says who may enter, `incumbentDecisions`
860
+ // says who may stay, and both read `whyNotReady` for the reason. Reported
861
+ // separately throughout — a run that promoted two and a run that promoted
862
+ // two and demoted one are different events, and a single total hides the
863
+ // half that is new.
864
+ const demoting = incumbentDecisions(readyIncumbents, READY_COLUMN, {
865
+ active,
866
+ expediteLabel: readExpediteLabel(process.cwd()),
867
+ }).filter(d => d.demote);
868
+ for (const d of demoting) {
869
+ console.log(` #${d.number} is in ${READY_COLUMN} and ${d.why} -> ${d.to}`);
870
+ }
871
+
872
+ if (!apply) {
873
+ console.log(
874
+ `\nDry run. ${moving.length} issue(s) would be promoted and ${demoting.length} demoted. ` +
875
+ `Pass --write to perform it.`,
876
+ );
877
+ return 0;
878
+ }
879
+
880
+ // **Nothing to move, so nothing to resolve.** This block ran whenever
881
+ // `--write` was passed, so a correctly-idle run — every dependent already
882
+ // Ready, still blocked, or claimed — against a board whose "Ready" column
883
+ // had been renamed exited `EXIT_REFUSED` instead of 0. A no-op success
884
+ // reported as a failure is red CI for a scenario where nothing needed
885
+ // writing, and the `candidates.length === 0` case above already short-circuits
886
+ // for exactly this reason. Caught in review of #1747; BR-42. Same class as
887
+ // BS-38 in `scripts/board-status-sweep.ts`, found one round earlier in the
888
+ // other script.
889
+ // A demotion is a move, so this short-circuit has to count both or a run
890
+ // whose only work is a demotion exits before resolving the Status field.
891
+ if (moving.length === 0 && demoting.length === 0) {
892
+ console.log(`\nNothing to move. No issue changed.`);
893
+ return 0;
894
+ }
895
+
896
+ // **One resolve, from the project, before the loop.** `ProjectV2.field` is
897
+ // a by-name lookup that takes no cursor — introspected 2026-11-04 against
898
+ // the live schema rather than read off this query — so it adds no `first:`
899
+ // for BR-19's census to police, and it costs one round trip instead of one
900
+ // per moved item.
901
+ const statusField = (
902
+ await gql(
903
+ token,
904
+ apiBase,
905
+ `query($p:ID!){node(id:$p){... on ProjectV2{
906
+ field(name: "Status"){... on ProjectV2SingleSelectField{id options{id name}}}}}}`,
907
+ { p: project },
908
+ )
909
+ ).node?.field;
910
+ if (!statusField?.id) {
911
+ console.log(`::warning::the board has no Status field — UNMEASURED, nothing written`);
912
+ return EXIT_REFUSED;
913
+ }
914
+ // One lookup, used for both directions. A second `find` spelled inline for
915
+ // the demotion target would be a second place that decides what an option
916
+ // id is, and the two would agree on every board anybody tests.
917
+ const optionFor = (name: string): { id: string } | undefined =>
918
+ (statusField.options ?? []).find((o: any) => o.name === name);
919
+ const option = optionFor(READY_COLUMN);
920
+ if (!option) {
921
+ console.log(`::warning::the board has no "${READY_COLUMN}" option — UNMEASURED, nothing written`);
922
+ return EXIT_REFUSED;
923
+ }
924
+
925
+ // Demotions first, and the ordering is load-bearing: a demotion frees a
926
+ // slot, and a promotion computed against the pre-demotion occupancy is
927
+ // conservative — it under-promotes rather than exceeding the cap. The
928
+ // reverse order could write a card into a lane this run was about to
929
+ // empty, which is the direction that breaks #1852's bound.
930
+ for (const dec of demoting) {
931
+ const target = readyIncumbents.find(c => c.number === dec.number);
932
+ const to = optionFor(dec.to);
933
+ if (!target?.itemId) {
934
+ console.log(`::warning::#${dec.number} is in ${READY_COLUMN} with no item id — UNMEASURED`);
935
+ continue;
936
+ }
937
+ if (!to) {
938
+ // The lane the one backwards rule names does not exist on this board.
939
+ // Loud and skipped, never silently left in Ready: a card that should
940
+ // not be startable staying startable is the whole defect.
941
+ console.log(
942
+ `::warning::the board has no "${dec.to}" option, so #${dec.number} could not be ` +
943
+ `demoted out of ${READY_COLUMN} — UNMEASURED, it is still being offered as startable`,
944
+ );
945
+ continue;
946
+ }
947
+ await gql(
948
+ token,
949
+ apiBase,
950
+ `mutation($p:ID!,$i:ID!,$f:ID!,$o:String!){updateProjectV2ItemFieldValue(
951
+ input:{projectId:$p,itemId:$i,fieldId:$f,value:{singleSelectOptionId:$o}}){projectV2Item{id}}}`,
952
+ { p: project, i: target.itemId, f: statusField.id, o: to.id },
953
+ );
954
+ console.log(` wrote #${dec.number} -> ${dec.to} (${dec.why})`);
955
+ }
956
+
957
+ for (const dec of moving) {
958
+ const target = itemOf.get(dec.number);
959
+ if (!target) {
960
+ // Decided to move and nothing to move it with. Loud, because a silent
961
+ // skip here is indistinguishable from "it moved". This now means only
962
+ // ONE thing — the issue is not on this board — because the field id no
963
+ // longer comes from the item.
964
+ console.log(`::warning::#${dec.number} is Ready but is not an item on this board — UNMEASURED`);
965
+ continue;
966
+ }
967
+ await gql(
968
+ token,
969
+ apiBase,
970
+ `mutation($p:ID!,$i:ID!,$f:ID!,$o:String!){updateProjectV2ItemFieldValue(
971
+ input:{projectId:$p,itemId:$i,fieldId:$f,value:{singleSelectOptionId:$o}}){projectV2Item{id}}}`,
972
+ { p: project, i: target.itemId, f: statusField.id, o: option.id },
973
+ );
974
+ console.log(` wrote #${dec.number} -> ${READY_COLUMN}`);
975
+ }
976
+ return 0;
977
+ }
978
+
979
+ process.exit(await main());