@feigi/fleet-ctl 0.0.0

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 (245) hide show
  1. package/.claude-plugin/plugin.json +9 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/agents/fleet-finisher.agent.md +7 -0
  5. package/agents/fleet-implementer-alt.agent.md +210 -0
  6. package/agents/fleet-implementer.agent.md +210 -0
  7. package/agents/fleet-merge-bot.agent.md +7 -0
  8. package/agents/fleet-review-comments.agent.md +40 -0
  9. package/agents/fleet-review-correctness.agent.md +43 -0
  10. package/agents/fleet-review-runner.agent.md +73 -0
  11. package/agents/fleet-review-silent-failure.agent.md +49 -0
  12. package/agents/fleet-review-simplify.agent.md +46 -0
  13. package/agents/fleet-review-snapshot.agent.md +24 -0
  14. package/agents/fleet-review-tests.agent.md +46 -0
  15. package/agents/fleet-review-types.agent.md +41 -0
  16. package/agents/fleet-review-verifier.agent.md +29 -0
  17. package/commands/review-and-fix.md +98 -0
  18. package/commands/run-merge-bot.md +357 -0
  19. package/commands/run-team-help.md +17 -0
  20. package/package.json +23 -0
  21. package/scripts/agent-test-dir-prose.test.mjs +59 -0
  22. package/scripts/agent-test.test.mjs +1636 -0
  23. package/scripts/ambient-git-vars-mjs-prose.test.mjs +354 -0
  24. package/scripts/ambient-git-vars-prose.test.mjs +192 -0
  25. package/scripts/ancestry-check-position-prose.test.mjs +175 -0
  26. package/scripts/apply-ruleset.test.mjs +420 -0
  27. package/scripts/arg-header-probes-prose.test.mjs +393 -0
  28. package/scripts/arg.mjs +600 -0
  29. package/scripts/arg.test.mjs +1354 -0
  30. package/scripts/board-cli.test.mjs +694 -0
  31. package/scripts/board-identity.test.mjs +429 -0
  32. package/scripts/board-liveness-banner.test.mjs +119 -0
  33. package/scripts/board-prev-shape.test.mjs +229 -0
  34. package/scripts/board-tryparse-null.test.mjs +119 -0
  35. package/scripts/board.html +471 -0
  36. package/scripts/board.mjs +2037 -0
  37. package/scripts/board.test.mjs +3086 -0
  38. package/scripts/brief-after-cut-prose.test.mjs +53 -0
  39. package/scripts/candidates-exit3-prose.test.mjs +302 -0
  40. package/scripts/candidates.mjs +674 -0
  41. package/scripts/candidates.test.mjs +2101 -0
  42. package/scripts/caveat-unification-prose.test.mjs +98 -0
  43. package/scripts/ci-comment-rot-prose.test.mjs +2025 -0
  44. package/scripts/ci-completes-premise-prose.test.mjs +257 -0
  45. package/scripts/ci-state-prose.test.mjs +113 -0
  46. package/scripts/ci-state.mjs +761 -0
  47. package/scripts/ci-state.test.mjs +1640 -0
  48. package/scripts/ci-vacuous-green.test.mjs +368 -0
  49. package/scripts/citation-sweep-prose.test.mjs +1572 -0
  50. package/scripts/claim-lifecycle.test.mjs +185 -0
  51. package/scripts/claim-ticket.sh +417 -0
  52. package/scripts/claim-ticket.test.mjs +1121 -0
  53. package/scripts/closing-keyword-prose.test.mjs +193 -0
  54. package/scripts/cockpit-launch-idempotent-prose.test.mjs +165 -0
  55. package/scripts/cockpit-tick-nonblocking.test.mjs +210 -0
  56. package/scripts/compute-board.mjs +579 -0
  57. package/scripts/compute-board.test.mjs +1060 -0
  58. package/scripts/compute-spend.mjs +329 -0
  59. package/scripts/compute-spend.test.mjs +451 -0
  60. package/scripts/cross-repo-citation-prose.test.mjs +156 -0
  61. package/scripts/cwd-isolation-pins.mjs +83 -0
  62. package/scripts/dedupe-guard-prose.test.mjs +243 -0
  63. package/scripts/derive-testcmd.sh +239 -0
  64. package/scripts/derive-testcmd.test.mjs +380 -0
  65. package/scripts/diff-stats.mjs +231 -0
  66. package/scripts/diff-stats.test.mjs +408 -0
  67. package/scripts/dispatch-block-golden-prose.test.mjs +1024 -0
  68. package/scripts/dispatch-block-pins-prose.test.mjs +615 -0
  69. package/scripts/drop-merged-label.sh +173 -0
  70. package/scripts/drop-merged-label.test.mjs +480 -0
  71. package/scripts/expected-jobs-prose.test.mjs +80 -0
  72. package/scripts/filing-bar-seat-prose.test.mjs +242 -0
  73. package/scripts/filing-claim-bar-prose.test.mjs +166 -0
  74. package/scripts/finisher-dispatch-premise-prose.test.mjs +312 -0
  75. package/scripts/finisher-halt-prose.test.mjs +106 -0
  76. package/scripts/finisher-name-prose.test.mjs +134 -0
  77. package/scripts/finisher-own-tree-prose.test.mjs +285 -0
  78. package/scripts/finisher-pin-race-prose.test.mjs +339 -0
  79. package/scripts/fix-applier-correction-rules-prose.test.mjs +201 -0
  80. package/scripts/fix-applier-result-file-prose.test.mjs +100 -0
  81. package/scripts/fleet-bootstrap +155 -0
  82. package/scripts/fleet-heartbeat.mjs +272 -0
  83. package/scripts/fleet-heartbeat.test.mjs +450 -0
  84. package/scripts/fleet-provenance +207 -0
  85. package/scripts/fleet-provenance.test.mjs +64 -0
  86. package/scripts/fleet-run +148 -0
  87. package/scripts/fleet-run.test.mjs +90 -0
  88. package/scripts/fleet-state.mjs +400 -0
  89. package/scripts/fleet-state.test.mjs +373 -0
  90. package/scripts/fleet-tick-prose.test.mjs +299 -0
  91. package/scripts/fleet-tick.mjs +832 -0
  92. package/scripts/fleet-tick.test.mjs +1332 -0
  93. package/scripts/force-with-lease-reason-prose.test.mjs +184 -0
  94. package/scripts/frontmatter-allowlist.json +64 -0
  95. package/scripts/frontmatter-check.mjs +256 -0
  96. package/scripts/frontmatter-check.test.mjs +436 -0
  97. package/scripts/git-env.mjs +124 -0
  98. package/scripts/git-env.test.mjs +149 -0
  99. package/scripts/git-status-untracked-mode-sweep.test.mjs +216 -0
  100. package/scripts/gone-walk.test.mjs +213 -0
  101. package/scripts/gp-sep-invariant-prose.test.mjs +188 -0
  102. package/scripts/head-moved-after-label-prose.test.mjs +233 -0
  103. package/scripts/immutable-body-claim-prose.test.mjs +413 -0
  104. package/scripts/implementer-model-tier.test.mjs +643 -0
  105. package/scripts/inflight-citation-prose.test.mjs +144 -0
  106. package/scripts/inflight-exit2-prose.test.mjs +81 -0
  107. package/scripts/inflight-probe-guard-prose.test.mjs +109 -0
  108. package/scripts/inflight-scan-scope-prose.test.mjs +57 -0
  109. package/scripts/inflight.sh +1106 -0
  110. package/scripts/inflight.test.mjs +2984 -0
  111. package/scripts/injection-control-prose.test.mjs +404 -0
  112. package/scripts/install-root-audit.test.mjs +464 -0
  113. package/scripts/instrument-check-prose.test.mjs +235 -0
  114. package/scripts/instruments.sh +394 -0
  115. package/scripts/instruments.test.mjs +787 -0
  116. package/scripts/issue-tracker-prose.test.mjs +71 -0
  117. package/scripts/json.sh +248 -0
  118. package/scripts/json.test.mjs +364 -0
  119. package/scripts/ledger-dispatch.test.mjs +516 -0
  120. package/scripts/ledger-grammar.mjs +85 -0
  121. package/scripts/ledger-grammar.test.mjs +142 -0
  122. package/scripts/ledger-read-require-file.test.mjs +197 -0
  123. package/scripts/ledger.mjs +1753 -0
  124. package/scripts/ledger.test.mjs +3554 -0
  125. package/scripts/line-distance-prose.test.mjs +245 -0
  126. package/scripts/liveness-rationale-prose.test.mjs +83 -0
  127. package/scripts/locale-pin-prose.test.mjs +189 -0
  128. package/scripts/member-outcome-prose.test.mjs +167 -0
  129. package/scripts/member-outcomes-header.test.mjs +148 -0
  130. package/scripts/member-outcomes-prose.test.mjs +63 -0
  131. package/scripts/member-outcomes.mjs +231 -0
  132. package/scripts/member-outcomes.test.mjs +507 -0
  133. package/scripts/member-prompt-prose.test.mjs +161 -0
  134. package/scripts/member-record.mjs +605 -0
  135. package/scripts/member-record.test.mjs +516 -0
  136. package/scripts/member-write-guard.mjs +279 -0
  137. package/scripts/member-write-guard.test.mjs +211 -0
  138. package/scripts/merge-commit-probe-prose.test.mjs +122 -0
  139. package/scripts/merge-gate.mjs +262 -0
  140. package/scripts/merge-gate.test.mjs +613 -0
  141. package/scripts/muted-git-guard-sweep.test.mjs +493 -0
  142. package/scripts/net-ssh-precedence-prose.test.mjs +91 -0
  143. package/scripts/net-watchdog-prose.test.mjs +79 -0
  144. package/scripts/net.sh +409 -0
  145. package/scripts/net.test.mjs +211 -0
  146. package/scripts/no-ci-gate-prose.test.mjs +108 -0
  147. package/scripts/no-undo-audit.sh +1134 -0
  148. package/scripts/no-undo-audit.test.mjs +3965 -0
  149. package/scripts/no-wave.test.mjs +138 -0
  150. package/scripts/node-floor-sweep.test.mjs +611 -0
  151. package/scripts/pointer-target-prose.test.mjs +186 -0
  152. package/scripts/pr-overlap.mjs +417 -0
  153. package/scripts/pr-overlap.test.mjs +695 -0
  154. package/scripts/printf-die-sweep.test.mjs +384 -0
  155. package/scripts/prompt-renderer.mjs +39 -0
  156. package/scripts/prompt-renderer.test.mjs +68 -0
  157. package/scripts/prose-pin.mjs +808 -0
  158. package/scripts/prose-pin.test.mjs +1034 -0
  159. package/scripts/prove-merge.sh +228 -0
  160. package/scripts/prove-merge.test.mjs +995 -0
  161. package/scripts/pull-table-relabel-prose.test.mjs +60 -0
  162. package/scripts/quiet-payload-prose.test.mjs +222 -0
  163. package/scripts/reap.sh +1768 -0
  164. package/scripts/reap.test.mjs +4395 -0
  165. package/scripts/reaping-prose.test.mjs +159 -0
  166. package/scripts/refuter-scratch-prose.test.mjs +135 -0
  167. package/scripts/release-label-required-prose.test.mjs +71 -0
  168. package/scripts/release-label-split-prose.test.mjs +169 -0
  169. package/scripts/release-ticket.sh +1716 -0
  170. package/scripts/release-ticket.test.mjs +5106 -0
  171. package/scripts/renovate-release-contract.test.mjs +379 -0
  172. package/scripts/repo-root.mjs +544 -0
  173. package/scripts/repo-root.test.mjs +873 -0
  174. package/scripts/reporter-output-rule-prose.test.mjs +208 -0
  175. package/scripts/review-agent-report-only.test.mjs +49 -0
  176. package/scripts/review-core-cwd-isolation.test.mjs +374 -0
  177. package/scripts/review-core-reads.test.mjs +478 -0
  178. package/scripts/review-core-refuter-scratch.test.mjs +148 -0
  179. package/scripts/review-core-snapshot-path.test.mjs +777 -0
  180. package/scripts/review-core-specialist-scratch.test.mjs +189 -0
  181. package/scripts/review-core-testcmd.test.mjs +288 -0
  182. package/scripts/review-core-unrun.test.mjs +530 -0
  183. package/scripts/review-core-unverified-discriminant.test.mjs +208 -0
  184. package/scripts/review-core.mjs +1028 -0
  185. package/scripts/review-eval-resolver-path.test.mjs +55 -0
  186. package/scripts/review-eval.mjs +197 -0
  187. package/scripts/review-host-fixture.mjs +73 -0
  188. package/scripts/review-in-run-retry.test.mjs +187 -0
  189. package/scripts/review-no-vendor-dispatch.test.mjs +45 -0
  190. package/scripts/review-path-default.test.mjs +796 -0
  191. package/scripts/review-runner-spawns.test.mjs +93 -0
  192. package/scripts/review-runner.test.mjs +155 -0
  193. package/scripts/review-tier-audit.test.mjs +140 -0
  194. package/scripts/run-artifact-pr-prose.test.mjs +341 -0
  195. package/scripts/run-merge-bot-prose.test.mjs +1391 -0
  196. package/scripts/scratch-partition-invariant-prose.test.mjs +74 -0
  197. package/scripts/scripts-path-citation-sweep.test.mjs +73 -0
  198. package/scripts/section-between-guard-prose.test.mjs +378 -0
  199. package/scripts/select-dimensions.test.mjs +674 -0
  200. package/scripts/shared-refusal.test.mjs +388 -0
  201. package/scripts/shell-traps-prose.test.mjs +507 -0
  202. package/scripts/shortlist.mjs +355 -0
  203. package/scripts/shortlist.test.mjs +366 -0
  204. package/scripts/slow-transport.mjs +72 -0
  205. package/scripts/snapshot-repo.test.mjs +772 -0
  206. package/scripts/snapshot-runner-audience-prose.test.mjs +129 -0
  207. package/scripts/spend-view.test.mjs +312 -0
  208. package/scripts/staleness-qualifier-prose.test.mjs +251 -0
  209. package/scripts/staleness-verdict-prose.test.mjs +142 -0
  210. package/scripts/staleness.mjs +414 -0
  211. package/scripts/staleness.test.mjs +893 -0
  212. package/scripts/stalled-member-liveness-prose.test.mjs +219 -0
  213. package/scripts/stash-prohibition-prose.test.mjs +313 -0
  214. package/scripts/strip-comments.mjs +44 -0
  215. package/scripts/tier-check.mjs +468 -0
  216. package/scripts/tier-check.test.mjs +726 -0
  217. package/scripts/tier-guard-gate-prose.test.mjs +216 -0
  218. package/scripts/tier-outcomes-header.test.mjs +586 -0
  219. package/scripts/tier-outcomes.mjs +441 -0
  220. package/scripts/tier-outcomes.test.mjs +342 -0
  221. package/scripts/tier-roles.mjs +250 -0
  222. package/scripts/tier-roles.test.mjs +316 -0
  223. package/scripts/tracker-block-copy-prose.test.mjs +288 -0
  224. package/scripts/triage-labels-gloss-prose.test.mjs +97 -0
  225. package/scripts/unattended-git-sweep.test.mjs +142 -0
  226. package/scripts/verify-sha-exit2-prose.test.mjs +269 -0
  227. package/scripts/verify-sha.sh +117 -0
  228. package/scripts/verify-sha.test.mjs +693 -0
  229. package/scripts/watcher-degraded-block.test.mjs +372 -0
  230. package/scripts/watcher-key-prose.test.mjs +106 -0
  231. package/scripts/within-run-pair-prose.test.mjs +208 -0
  232. package/scripts/worktree-audit.sh +482 -0
  233. package/scripts/worktree-audit.test.mjs +1407 -0
  234. package/scripts/worktree-head-prose.test.mjs +276 -0
  235. package/scripts/worktree-listing-sweep.test.mjs +217 -0
  236. package/scripts/worktree-model-prose.test.mjs +216 -0
  237. package/scripts/worktree.sh +470 -0
  238. package/skills/next-ticket/SKILL.md +138 -0
  239. package/skills/run-team/SKILL.md +3603 -0
  240. package/skills/run-team/references/ci-and-staleness.md +75 -0
  241. package/skills/run-team/references/correction-tickets.md +37 -0
  242. package/skills/run-team/references/isolation.md +23 -0
  243. package/skills/run-team/references/member-lifecycle.md +73 -0
  244. package/skills/run-team/references/reaping.md +73 -0
  245. package/skills/sizing-a-ticket/SKILL.md +39 -0
@@ -0,0 +1,761 @@
1
+ #!/usr/bin/env node
2
+ // Bind a CI run to a PR's head and report whether it is genuinely green.
3
+ //
4
+ // Replaces the four-way run-binding check restated in three fleet documents.
5
+ // The failure it prevents: `gh pr checks` aggregates conclusions ACROSS runs and
6
+ // reports a `pass` inherited from a cancelled run on a superseded SHA. Head-SHA
7
+ // binding alone misses it, because the head is right and only the conclusions
8
+ // belong elsewhere.
9
+ //
10
+ // Nothing here is cached. A rerun rewrites a run in place, so a conclusion can
11
+ // invert under a fixed run id with nothing pushed. The only safe design is to
12
+ // re-query at the moment of decision, which is what this script is for.
13
+
14
+ import { execFileSync } from "node:child_process";
15
+ import { gitEnv } from "./git-env.mjs";
16
+ import { readdirSync, readFileSync } from "node:fs";
17
+ import { makeDie, defineFlags, writeAll } from "./arg.mjs";
18
+
19
+ const NAME = "ci-state";
20
+
21
+ // die()/arg()/numArg()/has() shared with the other fleet scripts — see
22
+ // arg.mjs for the fail-open (#61/#169/#364/#878) and pipe-safety
23
+ // (#176/#328/#363) rationale.
24
+ // `base`/`workflow`/`workflow-file` below all fall back with `||`, so a
25
+ // trailing `--base` (nothing after it) used to read as omitted and silently
26
+ // compare against the DEFAULT base — `ci-state.mjs --pr 5 --base` gave a
27
+ // real, wrong verdict at exit 0/1 with no refusal, reached here because THIS
28
+ // is the verdict the fleet gates on. die() also has to survive --quiet,
29
+ // which is the mode the controller's CI Monitor polls in.
30
+ const die = makeDie(NAME);
31
+ const { arg, numArg, has, sweep, stray } = defineFlags(die, {
32
+ flags: {
33
+ pr: "value",
34
+ base: "value",
35
+ workflow: "value",
36
+ "workflow-file": "value",
37
+ "declare-no-ci": "bool",
38
+ quiet: "bool",
39
+ },
40
+ });
41
+
42
+ // `--quiet` suppresses the diagnostic stream (command echoes, per-job/per-field
43
+ // lines) and drops `jobs` and `missing` from the payload. The controller's CI
44
+ // Monitor (and, standalone, the reviewer's own watch loop) polls this hot, and
45
+ // none of that stream is acted on — `reasons` already names every failing job,
46
+ // and the exit code already encodes green/not-green. die() and the one-line
47
+ // verdict summary still print, so a caller loses nothing it decides on.
48
+ const quiet = has("quiet");
49
+ const vlog = (...a) => {
50
+ if (!quiet) console.error(...a);
51
+ };
52
+
53
+ // #262. A refusal from an exhausted REST quota reached the same arm as every
54
+ // other gh read failure, so a caller could not tell an outage that clears on
55
+ // its own from a repo or token that will still be unreadable after any wait.
56
+ // The cause is only ever in gh's own stderr, which execFileSync BOTH forwards
57
+ // to our fd 2 and captures on the thrown error (measured) — so it is matched
58
+ // here without being reprinted, for the reason run() gives below: interpolating
59
+ // it emits every byte twice.
60
+ //
61
+ // Matched on the quota wording rather than on the 403 status, because 403 also
62
+ // carries refusals no amount of waiting clears. One expression spans the
63
+ // spellings a quota is refused with: the primary limit, the secondary one, and
64
+ // the abuse-detection wording GitHub used for that same secondary limit before
65
+ // renaming it — which a GitHub Enterprise Server predating the rename still
66
+ // emits, and this script does reach GHE (the behind probe passes --hostname).
67
+ //
68
+ // `abuse detection` in full, never a bare `abuse`: "disabled for abuse of
69
+ // GitHub's terms of service" is a permanent refusal, and the short form
70
+ // relabels it a blip that clears itself (measured).
71
+ const RATE_LIMITED = /rate limit|abuse detection/i;
72
+
73
+ // The outage payload, on stdout at the unchanged exit 2 — where this arm
74
+ // printed nothing at all. A caller reading only the exit code is unaffected;
75
+ // one parsing stdout gets a named cause instead of the empty capture
76
+ // `merge-gate.mjs` reads as `ci-unreadable` there: a probe that could not
77
+ // look, never a reading about the PR (ADR 0012 Decision 3).
78
+ //
79
+ // It reports the refused query and nothing else. A quota refusal is a probe
80
+ // that could not look, so every field this script would otherwise observe is
81
+ // ABSENT rather than null. A null is a reading, and nothing here was read.
82
+ //
83
+ // Absence is what a direct reader needs: `merge-gate.mjs` gates every merge
84
+ // on this payload's own fields — `verdict`, `behind`, `missing`, the per-job
85
+ // conclusions, and `prHead == runHeadSha` — and an absent `missing` refuses
86
+ // that gate where an empty array would have told it nothing was missing.
87
+ // board.mjs is not that reader — it takes exit 2 as a failed read whatever
88
+ // was printed on the way out, and carries its previous CI value for the PR
89
+ // forward instead.
90
+ //
91
+ // Every write this script makes on its way out goes through arg.mjs's
92
+ // writeAll(), for die()'s reason in that file: on a pipe, console.log and
93
+ // console.error hand the bytes to an ASYNC stream, and process.exit()
94
+ // discards whatever is still queued rather than draining it. The kernel takes
95
+ // one pipe buffer synchronously and the rest is dropped, so a payload past
96
+ // that size is cut mid-JSON while the exit code arrives intact — the caller
97
+ // reading the code sees a normal verdict and the caller parsing stdout gets
98
+ // bytes it cannot parse. writeSync goes straight to the fd, which is what
99
+ // survives process.exit(). It also takes no newline of its own, which is why
100
+ // every call site below embeds its own trailing newline in the string it passes to writeAll().
101
+ //
102
+ // #1549: this file used to carry its own copy of that write loop, called
103
+ // emit(), and the copy had DRIFTED — of the three hand-mirrored copies it was
104
+ // the only one that never grew #889's retry cap, so a reader that stayed open
105
+ // but never drained left it spinning forever. That is what a comment reading
106
+ // "mirrors emit()" buys and what shared code buys instead. The loop, its cap
107
+ // and its 1ms Atomics.wait are arg.mjs's now.
108
+ //
109
+ // What stays this file's own is the exit-code contract those writes protect,
110
+ // and it is why writeAll's false return is ignored at every call site here.
111
+ // Once the bytes are lost they are lost; this script reserves exit 1 for
112
+ // not-green and 2 for could-not-answer, so a verdict that failed to WRITE
113
+ // must not also take the process down a different exit path and turn a
114
+ // missing answer into a wrong one. Losing a green verdict's bytes is bad;
115
+ // reporting green as not-green because the write failed is worse, and that is
116
+ // the trade this file made before the extraction and keeps after it.
117
+
118
+ function emitRateLimited(query) {
119
+ const payload = {
120
+ pr,
121
+ verdict: "rate-limited",
122
+ reasons: [`${query} was refused by the GitHub API rate limit — no CI state was read. A quota refusal clears on its own: re-probe rather than reading this as a CI verdict`],
123
+ };
124
+ writeAll(1, `${JSON.stringify(payload)}\n`);
125
+ }
126
+
127
+ function run(cmd, args) {
128
+ vlog(`$ ${cmd} ${args.join(" ")}`);
129
+ try {
130
+ return execFileSync(cmd, args, { encoding: "utf8" });
131
+ } catch (e) {
132
+ // Names the cause, never the child's stderr — execFileSync forwarded it
133
+ // already (no `stdio` above), so interpolating it emits every byte twice.
134
+ // `e.message` is the same string, not a fallback: Node builds it as
135
+ // `Command failed: <cmd>\n<stderr>`. Three disjoint shapes — Node-aborted
136
+ // (ENOENT/ENOBUFS), signal, exit (#176).
137
+ // A quota refusal names itself first (#262); every other cause reports
138
+ // exactly as it always has, on this same line and this same exit code.
139
+ // `?? ""` stays — RegExp.test would coerce an absent stderr to the string
140
+ // "undefined", which a future looser pattern could match. String() around
141
+ // it does nothing: encoding: "utf8" above makes e.stderr a string whenever
142
+ // a child ran, and test() ToString-coerces anything else regardless.
143
+ if (RATE_LIMITED.test(e.stderr ?? "")) emitRateLimited(`${cmd} ${args[0]} ${args[1]}`);
144
+ die(`${cmd} failed: ${e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`)}`);
145
+ }
146
+ }
147
+
148
+ // One truncation rule for every raw gh value this script quotes into a
149
+ // refusal: cut at n chars behind a visible marker, shared by the non-JSON
150
+ // die below and by `saw` further down. An unmarked cut reads as the whole
151
+ // value — the length quoted is gh's, not this script's — so a bare
152
+ // `raw.trim().slice(0, n)` here would be exactly the lie `saw`'s own
153
+ // comment (below) declares unacceptable one screen away.
154
+ const cut = (s, n = 120) => (s.length > n ? `${s.slice(0, n)}… (truncated)` : s);
155
+
156
+ // Every gh read in this file is JSON, and a bare JSON.parse of a child's stdout
157
+ // fails OPEN: gh can exit 0 with a non-JSON body (a proxy's HTML error page is
158
+ // the measured case) and the uncaught SyntaxError exits 1 — which in THIS
159
+ // script is the code for not-green, so a crash renders as a CI verdict.
160
+ //
161
+ // The parse succeeding is not the shape succeeding: an error object where an
162
+ // array of runs is expected, a run view missing its jobs, parse cleanly and
163
+ // flow on unchecked until the first dereference throws — same exit-1-as-
164
+ // verdict failure, one layer further in (#269). `shape`, given, is
165
+ // `(parsed) => string | null` — a reason the payload isn't what the caller
166
+ // is about to read, or null when it's fine — checked here so each call site
167
+ // declares what it expects instead of hand-rolling its own, the way the two
168
+ // siblings do: candidates.mjs's `!Array.isArray(rows)` and its per-row field
169
+ // check, ledger.mjs's "gh returned JSON that is not an issue list". Named
170
+ // rather than cited by line, since both files move. Parity with them is
171
+ // partial on purpose: those check the discriminating field of every row, the
172
+ // row-level checks here refuse on object-ness alone — see the next comment.
173
+ function runJson(cmd, args, shape) {
174
+ const raw = run(cmd, args);
175
+ let parsed;
176
+ try {
177
+ parsed = JSON.parse(raw);
178
+ } catch {
179
+ die(`${cmd} ${args[0]} ${args[1]} returned no JSON — ${cut(raw.trim())}`);
180
+ }
181
+ const problem = shape?.(parsed);
182
+ if (problem) die(`${cmd} ${args[0]} ${args[1]} returned JSON but not the expected shape — ${problem}`);
183
+ return parsed;
184
+ }
185
+
186
+ // Shared by every shape check below. The fields actually read off a row
187
+ // (r.headSha, j.name, ...) are bare property reads, safe on any object even
188
+ // one missing that field — undefined flows into a comparison or a String(),
189
+ // never a throw. Only a `null` throws on that first read — an array, string,
190
+ // number or boolean reads back `undefined` like any other missing field
191
+ // (measured). Refusing all of them is still right: none is a row, and the
192
+ // silent ones are the same failure one notch quieter, a wrong-shape reply
193
+ // read as a field-less one. Object-ness is the refusal, not each field's
194
+ // type — checking e.g. that a job's `conclusion` were a string would wrongly
195
+ // refuse a legitimate in-progress job, whose conclusion is `null`.
196
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
197
+
198
+ // What a shape refusal is FOR is telling a reader what gh actually sent, and
199
+ // "missing <field>" told them the opposite of it. The two `gh pr view` field
200
+ // guards below each cover three faults at once — the key absent, the value an
201
+ // empty string, the value not a string — and the `jobs` guard two of the same
202
+ // kind, and every one of them printed a single identical "missing" line
203
+ // (#926, measured), so a reader went hunting for a key gh had in fact
204
+ // returned as `""`, `42` or `null`. `saw` reports the value instead, and
205
+ // claims absence only when the key really is absent.
206
+ //
207
+ // `Object.hasOwn`, not `key in obj`: `in` answers for the prototype chain
208
+ // too, and throws outright on a non-object (measured: TypeError, "Cannot use
209
+ // 'in' operator"). Every call site refuses a non-object ahead of any field
210
+ // check, so `in` would work there today — but a field guard reordered past
211
+ // that refusal would turn this diagnostic into the very exit-1-as-verdict
212
+ // crash the shape checks exist to prevent (#269), where `hasOwn` just answers
213
+ // `false`.
214
+ //
215
+ // JSON.stringify, not the raw value: it is what makes `""` visible at all and
216
+ // what tells the string `"42"` from the number 42. It always returns a string
217
+ // here — the value came from JSON.parse, and no JSON value stringifies to
218
+ // `undefined`. Cut through the shared `cut()` above — the same visible-
219
+ // marker rule the non-JSON die uses, because the length quoted here is
220
+ // gh's, not this script's, same as there.
221
+ const saw = (obj, key) => {
222
+ if (!Object.hasOwn(obj, key)) return "the key is absent";
223
+ const shown = JSON.stringify(obj[key]);
224
+ return `got ${cut(shown)}`;
225
+ };
226
+
227
+ // #840: `pr` was validated for truthiness alone, so `--pr abc` survived to
228
+ // every payload site — each built `pr: Number(pr)`, and `JSON.stringify(NaN)`
229
+ // is `null`. The normal path is the worse of them: an unidentifiable payload
230
+ // at exit 0 with `verdict: "green"`, which is the verdict the fleet gates on.
231
+ // `pr` is that payload's only identifying field, and the fleet polls this
232
+ // script for several PRs at once — so a null there is not a cosmetic gap, it is
233
+ // a report that cannot be attributed to the PR it answered for. Reaching gh at
234
+ // all is the other harm: `gh pr view` resolves a non-numeric ref as a BRANCH,
235
+ // so `--pr abc` could return a genuine verdict for whatever PR that branch
236
+ // belongs to.
237
+ //
238
+ // #878 moved the rule itself into arg.mjs's numArg(), because the identical
239
+ // shape was still live in diff-stats.mjs and pr-overlap.mjs and a fourth
240
+ // spelling of it here is what the fix had to stop. What stays this file's own
241
+ // is the usage line below — absent and malformed are different mistakes, and
242
+ // numArg() refuses only the second.
243
+ //
244
+ // `=== null`, not `!pr`: numArg() returns a NUMBER, so `--pr 0` — a value the
245
+ // caller did give — would otherwise be answered with a usage line claiming
246
+ // `--pr` is required. `gh` answers it truthfully instead, as no such PR.
247
+ // numArg() also no longer needs the placement #840's regex did: that one had
248
+ // to sit below this die because test() coerces `null` to the string "null",
249
+ // and numArg() never tests a value it did not read. It still lands above
250
+ // sweep(), per arg.mjs — where both would refuse, the more specific wording
251
+ // wins — and still before the first gh read.
252
+ const pr = numArg("pr");
253
+ if (pr === null) {
254
+ die(
255
+ "usage: ci-state.mjs --pr <number> [--base main] [--workflow CI] " +
256
+ "[--workflow-file <path>] [--declare-no-ci] [--quiet]",
257
+ );
258
+ }
259
+
260
+ const base = arg("base") || "main";
261
+ const workflow = arg("workflow") || "CI";
262
+ // --declare-no-ci is the caller's opt-out, never inferred: without it, a repo
263
+ // with no workflow file yields verdict=no-ci but still exits non-zero (#111),
264
+ // so absence never silently reads as pass. Fits the argv-flag surface every
265
+ // other option here already uses, rather than a repo-committed marker file
266
+ // that would sit uncommitted or drift stale.
267
+ const declareNoCi = has("declare-no-ci");
268
+
269
+ // #365: every flag above is read by looking for its own name, so a name
270
+ // nothing reads was never looked for — `--basee main` left `base` on its
271
+ // default and this file returned a real, wrong verdict at exit 0/1. That is
272
+ // the verdict the fleet gates PR-green on. Placed below the reads, per
273
+ // arg.mjs, so `--base --quiet` keeps #169's "--base needs a value"; still
274
+ // above the first gh call, which is the next statement.
275
+ //
276
+ // `--workflow-file` is read here rather than where its value is first needed,
277
+ // which is the whole reason the read is a statement of its own: measured,
278
+ // with it below the guards `--pr 42 --workflow-file --base main` refused with
279
+ // `unexpected argument 'main'` — naming --base's innocent value instead of
280
+ // the flag actually given wrong. Immediately above the sweep, not higher, so
281
+ // it cannot take the `--declare-no-ci=` refusal off the boolean guard that
282
+ // words it better.
283
+ const workflowFileArg = arg("workflow-file");
284
+
285
+ sweep();
286
+
287
+ // #463: sweep() above only ever refuses a `--`-prefixed token, so a bare or
288
+ // single-dash stray rode along in silence — `--pr 42 basee main` ignored
289
+ // `basee`/`main` and still compared against the default base, the same
290
+ // fail-open harm #365 closed for a misspelled FLAG name. This file takes no
291
+ // positional of its own, so any leftover token is one.
292
+ stray();
293
+
294
+ // --- PR facts -------------------------------------------------------------
295
+ const prInfo = runJson(
296
+ "gh",
297
+ ["pr", "view", String(pr), "--json", "headRefName,headRefOid,state,mergeStateStatus"],
298
+ (v) => {
299
+ if (!isObject(v)) return "expected an object";
300
+ if (typeof v.headRefName !== "string" || !v.headRefName) return `headRefName (the branch) is not a non-empty string (${saw(v, "headRefName")})`;
301
+ if (typeof v.headRefOid !== "string" || !v.headRefOid) return `headRefOid (the head sha) is not a non-empty string (${saw(v, "headRefOid")})`;
302
+ return null;
303
+ },
304
+ );
305
+ const branch = prInfo.headRefName;
306
+ const prHead = prInfo.headRefOid;
307
+ vlog(` branch=${branch} head=${prHead} state=${prInfo.state} mergeState=${prInfo.mergeStateStatus}`);
308
+
309
+ // --- Workflow file: discovered, not assumed --------------------------------
310
+ // A hard-coded `.github/workflows/ci.yml` default made every fleet CI read
311
+ // exit 2 the moment a repo's workflow had a different filename — no caller
312
+ // anywhere passed --workflow-file to work around it (#111). Locate the file
313
+ // by the SAME workflow identity `--workflow` already selects runs by (default
314
+ // "CI"), read off disk rather than another `gh api` round trip (#262 budget).
315
+ // --workflow-file stays as the explicit override for the one case discovery
316
+ // cannot settle by itself: two workflow files sharing a name.
317
+ const WORKFLOWS_DIR = ".github/workflows";
318
+
319
+ // Anchored to the repo root, never to the cwd. Every other fact in this script
320
+ // comes from `gh`, which resolves the repo from any depth, so a cwd-relative
321
+ // read made the SAME repo answer `no-ci` from a subdirectory while answering
322
+ // not-green from its root — and board.mjs spawns this with whatever cwd the
323
+ // cockpit happens to have. `git rev-parse` is a local read, so anchoring costs
324
+ // no REST call (#262). A root we cannot locate is exit 2, never `no-ci`:
325
+ // absence has to be established, and failing to find the root establishes
326
+ // nothing at all. Called only when discovery actually runs — an explicit
327
+ // --workflow-file answers the question without a repo root and must not die
328
+ // for want of one.
329
+ function workflowsPath() {
330
+ const root = tryRun("git", ["rev-parse", "--show-toplevel"])?.trim();
331
+ if (!root) {
332
+ die(`git rev-parse --show-toplevel failed — cannot locate ${WORKFLOWS_DIR}/ to answer whether this repo has CI`);
333
+ }
334
+ return `${root}/${WORKFLOWS_DIR}`;
335
+ }
336
+
337
+ // Returns the workflow's path, or null ONLY where this repo genuinely has no
338
+ // CI: no workflows directory, or a directory holding no YAML at all. Every
339
+ // other outcome is die() (exit 2, "could not be answered") — the directory
340
+ // unreadable, the target unreadable, or YAML present under other names. #111's
341
+ // whole point is that absence must be DECLARED, never inferred from an error:
342
+ // a repo whose CI is merely misconfigured must never read as one with no CI.
343
+ function discoverWorkflowFile(dir, workflowName) {
344
+ let entries;
345
+ try {
346
+ entries = readdirSync(dir);
347
+ } catch (e) {
348
+ // ENOENT is the one and only condition that means "no CI configured".
349
+ // EACCES, ENOTDIR, ELOOP and friends all mean the directory is there and
350
+ // we could not read it — unanswerable, exactly like the unreadable
351
+ // workflow file below. The bare `catch` this replaced relabelled every one
352
+ // of them `no-ci`, so a `chmod 000` on .github/workflows/ reported no-CI
353
+ // for a repo whose CI run was `failure` — and exit 0 under --declare-no-ci.
354
+ if (e.code === "ENOENT") return null;
355
+ die(`cannot read ${dir}: ${e.message}`);
356
+ }
357
+ const candidates = [];
358
+ const yamls = [];
359
+ const unreadable = [];
360
+ for (const f of entries) {
361
+ if (!/\.ya?ml$/.test(f)) continue;
362
+ const path = `${dir}/${f}`;
363
+ yamls.push(f);
364
+ let text;
365
+ try {
366
+ text = readFileSync(path, "utf8");
367
+ } catch (e) {
368
+ // NOT fatal on the spot: this entry may be an unrelated sibling, and
369
+ // dying on it blinds discovery to a target sitting readable right next
370
+ // to it (one chmod-000 workflow made a green repo exit 2). Fail closed
371
+ // only if nothing matched — then this file is the one that might have
372
+ // been the CI workflow. The ambiguity check below sees readable files
373
+ // only, so an unreadable second `CI` is invisible; a matched target wins.
374
+ unreadable.push(`${path}: ${e.message}`);
375
+ continue;
376
+ }
377
+ // Top-level `name:` only (column 0) — a job's own `name:` step is indented
378
+ // and expectedJobs() below already treats that as a different concern. The
379
+ // optional ` #…` tail is a YAML comment, not part of the name: without it
380
+ // `name: CI # main pipeline` parsed as a workflow called `CI # main
381
+ // pipeline`, so a correctly configured repo reported no-ci. ` #` with the
382
+ // space is what makes it a comment in YAML, so `name: CI#1` stays `CI#1`.
383
+ const m = text.match(/^name:\s*(.+?)(?:\s+#.*)?\s*$/m);
384
+ const name = m ? m[1].replace(/^['"]|['"]$/g, "") : null;
385
+ if (name === workflowName) candidates.push(path);
386
+ }
387
+ if (candidates.length > 1) {
388
+ die(
389
+ `${candidates.length} workflow files under ${dir}/ are named '${workflowName}' (${candidates.join(", ")}) — pass --workflow-file to pick one`,
390
+ );
391
+ }
392
+ if (candidates.length === 1) return candidates[0];
393
+ if (unreadable.length) {
394
+ // Nothing matched, so an unreadable file could have been the match.
395
+ die(`cannot read ${unreadable.join("; ")}`);
396
+ }
397
+ if (yamls.length) {
398
+ // Workflows ARE configured here, just none under this name: a --workflow /
399
+ // --workflow-file mismatch, not an absence. Saying "no CI configured" of a
400
+ // directory full of workflows is a false statement, and if
401
+ // --declare-no-ci let it through, it would hand the caller exit 0 for a repo
402
+ // whose CI it never looked at.
403
+ die(
404
+ `${yamls.length} workflow file(s) under ${dir}/ (${yamls.join(", ")}), none named '${workflowName}' — pass --workflow <name> or --workflow-file <path>`,
405
+ );
406
+ }
407
+ return null; // directory present, no workflow files in it — genuinely no CI
408
+ }
409
+
410
+ const workflowFile = workflowFileArg || discoverWorkflowFile(workflowsPath(), workflow);
411
+ // No workflows at all, so this repo has no CI configured for ci-state to read.
412
+ // That is its own verdict (`no-ci`), never the exit code reserved for "the
413
+ // question could not be answered" — every way of failing to READ a workflow
414
+ // (unreadable directory, unreadable file, malformed file) dies with exit 2
415
+ // instead, above or via expectedJobs() below.
416
+ const noCi = workflowFile === null;
417
+ if (noCi) {
418
+ vlog(` no workflow files under ${WORKFLOWS_DIR}/ — no-ci verdict`);
419
+ }
420
+
421
+ // --- Expected jobs, derived from the workflow file ------------------------
422
+ // Never hardcoded: expectedJobs() parses the `jobs:` block of the workflow file
423
+ // this run resolved (discoverWorkflowFile, or --workflow-file), so the expected
424
+ // set tracks that file and follows it across repos. A reader asking whether an
425
+ // empty `missing` is real should read that workflow for the current set. It is
426
+ // deliberately not restated here: a set written into this comment is wrong the
427
+ // moment a job is added.
428
+ //
429
+ // Not built from the fleet's own prose instead: `integration-docker` — a job in
430
+ // the agent-brain repo's CI workflow, which is on an internal GHE host and so
431
+ // cannot be settled from this repo — is named nowhere under the plugin's own
432
+ // component dirs but here (`git grep -l integration-docker -- commands scripts
433
+ // skills` matches only this file), so a
434
+ // list built from those documents would have accepted a run missing it.
435
+ function expectedJobs(file) {
436
+ let text;
437
+ try {
438
+ text = readFileSync(file, "utf8");
439
+ } catch (e) {
440
+ die(`cannot read ${file}: ${e.message}`);
441
+ }
442
+ const ids = [];
443
+ let inJobs = false;
444
+ let sawNameOverride = false;
445
+ for (const line of text.split("\n")) {
446
+ if (/^jobs:\s*$/.test(line)) {
447
+ inJobs = true;
448
+ continue;
449
+ }
450
+ if (inJobs && /^[A-Za-z]/.test(line)) break; // next top-level key ends the section
451
+ if (!inJobs) continue;
452
+ const m = line.match(/^ {2}([A-Za-z0-9_-]+):\s*$/);
453
+ if (m) ids.push(m[1]);
454
+ if (/^ {4}name:/.test(line)) sawNameOverride = true;
455
+ }
456
+ // Fail closed on the assumption this derivation rests on. If a job's
457
+ // reported name diverges from its YAML key, ids no longer equal the names
458
+ // `gh run view` reports, and every comparison below would silently compare
459
+ // the wrong strings.
460
+ //
461
+ // The reader most likely to cause that divergence is standing in the
462
+ // workflow, not here, so the same constraint is written at that end too:
463
+ // the NOTE heading the `rebase-check:` job in this repo's
464
+ // `.github/workflows/ci.yml`. It names this derivation as a live reader of
465
+ // that job's name, alongside the `main` ruleset, which requires a
466
+ // status-check context by the name the API reports — and records that a
467
+ // YAML job key and an API-reported display name coincide only while every
468
+ // job's reported name is its own key. This guard only catches one of the
469
+ // ways that can break: the canonical ` name:` spelling. A
470
+ // `strategy.matrix` block, or `name:` written as `name :` or `"name":`, sets
471
+ // (or changes) the reported name just as validly and slips past unnoticed —
472
+ // `sawNameOverride` stays false, and this function returns a verdict built
473
+ // on an id the API no longer reports under.
474
+ if (sawNameOverride) {
475
+ die(`${file} sets a job-level 'name:' — job ids no longer match reported job names, derivation invalid`);
476
+ }
477
+ if (ids.length === 0) die(`derived zero jobs from ${file} — refusing to answer`);
478
+ return ids;
479
+ }
480
+
481
+ // --- Find the run bound to this head --------------------------------------
482
+ // `--limit 1` is wrong: the newest run on a branch is frequently a label or
483
+ // policy workflow, which hides the CI result entirely. Filter by workflow, then
484
+ // match the head, then take the newest survivor.
485
+ //
486
+ // Skipped entirely under no-ci: there is no workflow to bind a run to, and
487
+ // asking anyway would spend the REST budget #262 is already tight on for a
488
+ // question this repo cannot answer either way.
489
+ const reasons = [];
490
+ let jobs = [];
491
+ let missing = [];
492
+ let runId = null;
493
+ let attempt = null;
494
+ let runHeadSha = null;
495
+ let status = null;
496
+ let conclusion = null;
497
+
498
+ if (noCi) {
499
+ reasons.push(
500
+ declareNoCi
501
+ ? `no workflows configured under ${WORKFLOWS_DIR}/ — --declare-no-ci passed, gating on the caller's verified suite run instead`
502
+ : `no workflows configured under ${WORKFLOWS_DIR}/ — pass --declare-no-ci once this repo is verified to gate on the reviewer's own suite run instead; absence never means pass`,
503
+ );
504
+ } else {
505
+ // Derived here rather than above the no-ci fork: `expected` is read on this
506
+ // arm alone, and the payload carries `missing`, not `expected`. Kept as this
507
+ // arm's first statement — expectedJobs() refuses on an underivable workflow,
508
+ // and that refusal belongs before the run query rather than after it.
509
+ const expected = expectedJobs(workflowFile);
510
+ vlog(` expected jobs (${expected.length}): ${expected.join(", ")}`);
511
+ const runs = runJson(
512
+ "gh",
513
+ ["run", "list", "--branch", branch, "--workflow", workflow, "--limit", "30", "--json", "databaseId,headSha,status,conclusion,event,createdAt"],
514
+ (v) => {
515
+ if (!Array.isArray(v)) return "expected an array of runs";
516
+ const bad = v.findIndex((r) => !isObject(r));
517
+ return bad === -1 ? null : `run list row ${bad} is not an object`;
518
+ },
519
+ );
520
+ const bySecond = (createdAt) => {
521
+ // GitHub's createdAt is already whole-second precision; this guards
522
+ // against any future sub-second drift silently hiding a genuine tie.
523
+ const s = String(createdAt);
524
+ const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})/.exec(s);
525
+ return m ? m[1] : s;
526
+ };
527
+ // Recency is the primary key — a newer run always outranks an older one,
528
+ // tied or not. The tie-break below fires ONLY when createdAt is equal to
529
+ // the second: two runs GitHub started in the same instant (measured on PR
530
+ // #1402, both 6 jobs green — one `cancelled`, one `completed`, and the
531
+ // stable sort below previously let API order pick the loser). Ranking
532
+ // conclusion ahead of createdAt here would let an older completed run beat
533
+ // a newer in-progress one on an unrelated, untied pair — a fresh
534
+ // regression, not a fix (#1410 review) — so conclusion only ever compares
535
+ // within a tie.
536
+ const compareRuns = (x, y) => {
537
+ const byCreatedAt = bySecond(y.createdAt).localeCompare(bySecond(x.createdAt));
538
+ if (byCreatedAt !== 0) return byCreatedAt;
539
+ // `status` is the run's LIFECYCLE (queued/in_progress/completed) and is
540
+ // NOT the outcome — a cancelled run reports status:"completed",
541
+ // conclusion:"cancelled", same as a successful one. Ranking a completed
542
+ // run's success against its cancellation on status here (as an earlier
543
+ // draft of this fix did) could never actually prefer the successful one
544
+ // over the cancelled sibling, because both share status:"completed".
545
+ // Rank a completed run's outcome on `conclusion` instead — see below
546
+ // for why the still-running middle tier ranks on `status` instead.
547
+ const rank = (r) => {
548
+ if (r.conclusion === "success" || r.conclusion === "skipped") return 0;
549
+ // Still running: no conclusion yet. `status` is this run's lifecycle
550
+ // field (queued/in_progress/completed) and is authoritative for "not
551
+ // done yet" — checked alone, not paired with a conclusion check.
552
+ // An earlier version additionally required `r.conclusion === null`,
553
+ // but live `gh run list --json conclusion` reports an empty string
554
+ // `""` for a non-completed run, never `null` (#1566) — that extra
555
+ // check silently never matched, so a still-running run fell through
556
+ // to the bottom tier below, indistinguishable from a failed/
557
+ // cancelled one. `status !== "completed"` alone is both sufficient
558
+ // (only a completed run has a real conclusion to rank on) and
559
+ // immune to whichever falsy shape gh chooses for "no conclusion yet".
560
+ if (r.status !== "completed") return 1;
561
+ return 2;
562
+ };
563
+ const byConclusion = rank(x) - rank(y);
564
+ if (byConclusion !== 0) return byConclusion;
565
+ // Last resort once createdAt (to the second) and conclusion rank both
566
+ // agree — total determinism, never expected to matter in practice.
567
+ // Numeric, not string, compare: "9" sorts ahead of "10" lexicographically
568
+ // but the higher/most-recent id is 10.
569
+ return Number(y.databaseId) - Number(x.databaseId);
570
+ };
571
+ const matching = runs.filter((r) => r.headSha === prHead).sort(compareRuns);
572
+
573
+ if (matching.length === 0) {
574
+ reasons.push(`no ${workflow} run whose headSha equals the PR head ${prHead}`);
575
+ } else {
576
+ const chosen = matching[0];
577
+ // A tie-break note is NOT pushed into `reasons` — reasons drives the
578
+ // green/not-green verdict below, and disambiguating between otherwise-
579
+ // identical candidates must never turn a green board red on its own.
580
+ // It goes to stderr unconditionally, like the verdict summary further
581
+ // down, rather than behind `vlog`/`--quiet`: the callers most likely to
582
+ // hit this — hot pollers that pass `--quiet` — are exactly the ones who
583
+ // need to know the pick required disambiguation rather than being the
584
+ // one unambiguous match.
585
+ const tiedAtCreatedAt = matching.filter((r) => bySecond(r.createdAt) === bySecond(chosen.createdAt));
586
+ if (tiedAtCreatedAt.length > 1) {
587
+ const others = tiedAtCreatedAt
588
+ .filter((r) => r.databaseId !== chosen.databaseId)
589
+ .map((r) => `#${r.databaseId} (${r.status}/${r.conclusion ?? "null"})`)
590
+ .join(", ");
591
+ writeAll(
592
+ 2,
593
+ `${NAME}: run selection tie-break — ${tiedAtCreatedAt.length} runs share head ${prHead} and createdAt ${bySecond(chosen.createdAt)}; chose #${chosen.databaseId} (${chosen.status}/${chosen.conclusion ?? "null"}) over ${others}\n`,
594
+ );
595
+ }
596
+ runId = chosen.databaseId;
597
+ // Re-query the run itself. The list's conclusion is a second read from a
598
+ // different moment; the authoritative job list is this one.
599
+ const view = runJson(
600
+ "gh",
601
+ ["run", "view", String(runId), "--json", "jobs,attempt,status,conclusion,headSha"],
602
+ (v) => {
603
+ if (!isObject(v)) return "expected an object";
604
+ if (!Array.isArray(v.jobs)) return `jobs is not an array (${saw(v, "jobs")})`;
605
+ const bad = v.jobs.findIndex((j) => !isObject(j));
606
+ return bad === -1 ? null : `job entry ${bad} is not an object`;
607
+ },
608
+ );
609
+ attempt = view.attempt;
610
+ runHeadSha = view.headSha;
611
+ status = view.status;
612
+ conclusion = view.conclusion;
613
+ jobs = view.jobs.map((j) => ({
614
+ name: j.name,
615
+ status: j.status,
616
+ conclusion: j.conclusion ?? null,
617
+ }));
618
+ for (const j of jobs) vlog(` ${j.name}: ${j.status}/${j.conclusion ?? "-"}`);
619
+ vlog(` attempt=${attempt} runHeadSha=${runHeadSha} status=${status} conclusion=${conclusion}`);
620
+
621
+ if (runHeadSha !== prHead) reasons.push(`run headSha ${runHeadSha} != PR head ${prHead}`);
622
+ if (status !== "completed") reasons.push(`run status is ${status}, not completed`);
623
+
624
+ const present = new Set(jobs.map((j) => j.name));
625
+ missing = expected.filter((e) => !present.has(e));
626
+ // An absent job reads as pending and is invisible in a checks summary. This is
627
+ // the case a force-push creates: the run is cancelled, finished jobs keep their
628
+ // conclusions, and the missing ones simply never appear.
629
+ if (missing.length) reasons.push(`expected jobs absent from the run: ${missing.join(", ")}`);
630
+
631
+ // `skipped` is NOT `passed`. When the currency check fails, the heavy suites
632
+ // report skipped — they did not execute.
633
+ for (const j of jobs) {
634
+ // `??` only falls through on null/undefined; gh reports an empty
635
+ // string `""` for an in-progress job's conclusion (same shape as the
636
+ // rank() tie-break bug this file fixed for #1566), so `??` alone
637
+ // would print the unreadable "job check is , not success". `||`
638
+ // treats the empty string as absent too and falls through to status.
639
+ if (j.conclusion !== "success") reasons.push(`job ${j.name} is ${j.conclusion || j.status}, not success`);
640
+ }
641
+ }
642
+ }
643
+
644
+ // --- Behind-count ---------------------------------------------------------
645
+ // `gh api` does NOT infer the host from the local remote the way `gh pr` and
646
+ // `gh run` do — on a GitHub Enterprise repo it silently 404s against github.com.
647
+ //
648
+ // This block MUST NOT use run(): run()'s failure path calls die(), which calls
649
+ // process.exit(2) and terminates before any surrounding catch can see it. An
650
+ // earlier version wrapped run() in a try/catch here, which made the catch
651
+ // unreachable — a transient failure on this purely informational side channel
652
+ // hard-exited the tool and discarded a fully computed CI verdict. Use a helper
653
+ // that returns null instead, so the behind-count can be unknown without costing
654
+ // the caller the answer it actually asked for.
655
+ //
656
+ // GIT_DIR/GIT_WORK_TREE scrubbed (#1599, gitEnv()): this is the ONE spawn
657
+ // primitive both of this file's git calls route through — `workflowsPath()`'s
658
+ // `rev-parse --show-toplevel` above and `remote get-url origin` below — so
659
+ // scrubbing it here protects both without a second copy. Harmless for the
660
+ // `gh` calls also routed through it: neither name means anything to `gh`.
661
+ // Measured: an ambient GIT_WORK_TREE alone answers `workflowsPath()`'s
662
+ // `rev-parse --show-toplevel` with the AMBIENT path outright, silently, at
663
+ // exit 0, regardless of the real cwd — sending workflow discovery to search
664
+ // a directory that is not this repository at all. An ambient GIT_DIR alone
665
+ // answers `remote get-url origin` for a DIFFERENT repository, silently, at
666
+ // exit 0 — binding `gh api`'s `--hostname` to a repo the caller never named,
667
+ // which behind-count's own comment above already treats as a 404 hazard for
668
+ // an unrelated reason (GHE host inference) and this closes for a second.
669
+ function tryRun(cmd, args) {
670
+ vlog(`$ ${cmd} ${args.join(" ")}`);
671
+ try {
672
+ return execFileSync(cmd, args, { encoding: "utf8", env: gitEnv() });
673
+ } catch (e) {
674
+ // Same discipline as run(), and it matters more here: --quiet suppresses
675
+ // vlog entirely, so under the controller's Monitor this line is discarded
676
+ // and the interpolated stderr would have been paid for and then thrown
677
+ // away. Name the cause; the child's own bytes already reached the caller.
678
+ vlog(
679
+ ` ${NAME}: ${cmd} failed: ${
680
+ e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`)
681
+ }`,
682
+ );
683
+ return null;
684
+ }
685
+ }
686
+
687
+ let behind = null;
688
+ try {
689
+ const remote = tryRun("git", ["remote", "get-url", "origin"]);
690
+ const repoJson = remote === null ? null : tryRun("gh", ["repo", "view", "--json", "nameWithOwner"]);
691
+ if (remote !== null && repoJson !== null) {
692
+ const host = remote.trim().replace(/^(git@|https:\/\/|ssh:\/\/git@)/, "").replace(/[:/].*$/, "");
693
+ const repo = JSON.parse(repoJson).nameWithOwner;
694
+ const cmpJson = tryRun("gh", ["api", "--hostname", host, `repos/${repo}/compare/${base}...${prHead}`]);
695
+ if (cmpJson !== null) {
696
+ const cmp = JSON.parse(cmpJson);
697
+ // Shaped like every other gh read here (#269), but fail-SOFT: a compare
698
+ // reply without a numeric `behind_by` — a 404 body from the wrong host
699
+ // or base is the live case — leaves `behind` null, this block's
700
+ // documented unknown, instead of `undefined`, which JSON.stringify drops
701
+ // from the payload entirely, taking the contract below and its
702
+ // unknown-vlog with it. Still never dies: the probe stays advisory.
703
+ behind = typeof cmp?.behind_by === "number" ? cmp.behind_by : null;
704
+ vlog(` behind_by=${behind} (status=${cmp?.status})`);
705
+ }
706
+ }
707
+ } catch (e) {
708
+ // JSON.parse of a malformed payload lands here; the subprocess failures are
709
+ // already handled by tryRun returning null.
710
+ vlog(` ${NAME}: behind-count unusable: ${e.message}`);
711
+ }
712
+
713
+ // `behind` stays null when unknown, and null NEVER enters `reasons`. The
714
+ // behind-count is context for the caller, not part of the green verdict:
715
+ // reviewers label without requiring currency, and only the merge bot
716
+ // establishes it. An earlier version pushed "behind-count unavailable" into
717
+ // reasons, which silently turned a fully green board into not-green over a
718
+ // number the verdict is not supposed to depend on.
719
+ //
720
+ // null is deliberately not 0 — 0 would read as "current", which is the one
721
+ // wrong answer that matters here.
722
+ if (behind === null) {
723
+ vlog(` ${NAME}: behind-count unknown (reported as null; verdict unaffected)`);
724
+ }
725
+
726
+ // no-ci is its own verdict, distinguishable from both green and not-green —
727
+ // board.mjs's mapCi() and any other caller that reads `verdict` by string
728
+ // value sees "no-ci" rather than either, so it cannot be silently folded into
729
+ // a pass or a red. reasons.length is never 0 here: the no-ci branch above
730
+ // always pushes exactly one, whichever way --declare-no-ci went.
731
+ const verdict = noCi ? "no-ci" : reasons.length === 0 ? "green" : "not-green";
732
+ writeAll(2, `\n${NAME}: verdict=${verdict}${reasons.length ? ` — ${reasons.join("; ")}` : ""}\n`);
733
+
734
+ // Compact, single-line: the consumer is an agent/script parsing JSON, and the
735
+ // pretty view already went to stderr. On the quiet hot path drop `jobs` and
736
+ // `missing` too — `reasons` already states every failing/absent job, so they
737
+ // are pure duplication in the two longest-lived contexts that poll this.
738
+ //
739
+ // no-ci drops them unconditionally, quiet or not — never folded into the
740
+ // `!quiet` check above, which is about duplication, not about what was read.
741
+ // `jobs`/`missing` stay at their `let jobs = []`/`let missing = []`
742
+ // initialisers on this path (the no-ci branch never reaches the run-binding
743
+ // arm that assigns them), so shipping them read as "checked, nothing
744
+ // missing" to a caller gating on `missing.length` when no workflow was ever
745
+ // read to check against. `emitRateLimited()` above already answers the same
746
+ // "nothing was read" question by omitting `jobs`/`missing` rather than
747
+ // emitting them empty; this is the no-ci arm agreeing with it, one
748
+ // convention for both places in this file that never bind a run.
749
+ const payload = { pr, branch, prHead, runId, attempt, runHeadSha, status, conclusion, behind, verdict, reasons };
750
+ if (!quiet && !noCi) Object.assign(payload, { jobs, missing });
751
+ writeAll(1, `${JSON.stringify(payload)}\n`);
752
+
753
+ // Exit vocabulary unchanged: 0 only when the gate is satisfied, 1 when it is
754
+ // not, 2 (via die(), above) only when the question could not be answered at
755
+ // all. no-ci without --declare-no-ci is a satisfiable question with an
756
+ // unsatisfied gate — exit 1, same bucket as not-green, so absence never reads
757
+ // as pass to a caller that checks only the exit code. no-ci WITH the
758
+ // declaration is the caller saying the gate is satisfied elsewhere (their own
759
+ // verified suite run) — exit 0.
760
+ const gateSatisfied = verdict === "green" || (verdict === "no-ci" && declareNoCi);
761
+ process.exit(gateSatisfied ? 0 : 1);