@feigi/fleet-ctl 3.23.35 → 3.23.37

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 (204) hide show
  1. package/package.json +1 -1
  2. package/scripts/main-checkout.mjs +1 -1
  3. package/scripts/member-write-guard.mjs +1 -1
  4. package/scripts/repo-root.mjs +1 -1
  5. package/skills/run-team/references/reaping.md +1 -1
  6. package/scripts/agent-test-dir-prose.test.mjs +0 -59
  7. package/scripts/agent-test.test.mjs +0 -1640
  8. package/scripts/ambient-git-vars-mjs-prose.test.mjs +0 -397
  9. package/scripts/ambient-git-vars-prose.test.mjs +0 -192
  10. package/scripts/ancestry-check-position-prose.test.mjs +0 -175
  11. package/scripts/apply-ruleset.test.mjs +0 -421
  12. package/scripts/arg-header-probes-prose.test.mjs +0 -394
  13. package/scripts/arg.test.mjs +0 -1354
  14. package/scripts/board-cli.test.mjs +0 -710
  15. package/scripts/board-identity.test.mjs +0 -429
  16. package/scripts/board-liveness-banner.test.mjs +0 -119
  17. package/scripts/board-prev-shape.test.mjs +0 -228
  18. package/scripts/board-tryparse-null.test.mjs +0 -119
  19. package/scripts/board.test.mjs +0 -3121
  20. package/scripts/brief-after-cut-prose.test.mjs +0 -53
  21. package/scripts/candidates-exit3-prose.test.mjs +0 -302
  22. package/scripts/candidates.test.mjs +0 -2312
  23. package/scripts/caveat-unification-prose.test.mjs +0 -98
  24. package/scripts/cell-readout.test.mjs +0 -615
  25. package/scripts/ci-comment-rot-prose.test.mjs +0 -2025
  26. package/scripts/ci-completes-premise-prose.test.mjs +0 -257
  27. package/scripts/ci-state-prose.test.mjs +0 -113
  28. package/scripts/ci-state.test.mjs +0 -1933
  29. package/scripts/ci-vacuous-green.test.mjs +0 -368
  30. package/scripts/citation-sweep-prose.test.mjs +0 -1712
  31. package/scripts/claim-lifecycle.test.mjs +0 -187
  32. package/scripts/claim-ticket.test.mjs +0 -1122
  33. package/scripts/closing-keyword-prose.test.mjs +0 -193
  34. package/scripts/cockpit-launch-idempotent-prose.test.mjs +0 -165
  35. package/scripts/cockpit-tick-nonblocking.test.mjs +0 -210
  36. package/scripts/compute-board.test.mjs +0 -1214
  37. package/scripts/compute-spend.test.mjs +0 -517
  38. package/scripts/consumer-technology-prose.test.mjs +0 -126
  39. package/scripts/cross-repo-citation-prose.test.mjs +0 -155
  40. package/scripts/cwd-isolation-pins.mjs +0 -83
  41. package/scripts/dedupe-guard-prose.test.mjs +0 -243
  42. package/scripts/delete-merged-branch.test.mjs +0 -576
  43. package/scripts/derive-testcmd.test.mjs +0 -595
  44. package/scripts/diff-stats.test.mjs +0 -404
  45. package/scripts/dispatch-block-golden-prose.test.mjs +0 -1130
  46. package/scripts/dispatch-block-pins-prose.test.mjs +0 -615
  47. package/scripts/dispositions-check.test.mjs +0 -936
  48. package/scripts/dispositions-gate-prose.test.mjs +0 -129
  49. package/scripts/drop-merged-label.test.mjs +0 -479
  50. package/scripts/exec-stub.mjs +0 -93
  51. package/scripts/exec-stub.test.mjs +0 -69
  52. package/scripts/expected-jobs-prose.test.mjs +0 -80
  53. package/scripts/fan-out-authorization-prose.test.mjs +0 -80
  54. package/scripts/filing-bar-seat-prose.test.mjs +0 -242
  55. package/scripts/filing-claim-bar-prose.test.mjs +0 -166
  56. package/scripts/finisher-died-prose.test.mjs +0 -31
  57. package/scripts/finisher-dispatch-premise-prose.test.mjs +0 -312
  58. package/scripts/finisher-halt-prose.test.mjs +0 -106
  59. package/scripts/finisher-name-prose.test.mjs +0 -134
  60. package/scripts/finisher-own-tree-prose.test.mjs +0 -299
  61. package/scripts/finisher-pin-race-prose.test.mjs +0 -339
  62. package/scripts/finisher-test-verdict-prose.test.mjs +0 -102
  63. package/scripts/fix-applier-correction-rules-prose.test.mjs +0 -202
  64. package/scripts/fix-applier-result-file-prose.test.mjs +0 -149
  65. package/scripts/fleet-bootstrap.test.mjs +0 -75
  66. package/scripts/fleet-heartbeat.test.mjs +0 -450
  67. package/scripts/fleet-provenance.test.mjs +0 -138
  68. package/scripts/fleet-run.test.mjs +0 -90
  69. package/scripts/fleet-state.test.mjs +0 -460
  70. package/scripts/fleet-tick-prose.test.mjs +0 -300
  71. package/scripts/fleet-tick.test.mjs +0 -2444
  72. package/scripts/force-with-lease-reason-prose.test.mjs +0 -184
  73. package/scripts/frontmatter-check.test.mjs +0 -436
  74. package/scripts/git-env.test.mjs +0 -149
  75. package/scripts/git-status-untracked-mode-sweep.test.mjs +0 -216
  76. package/scripts/gone-walk.test.mjs +0 -213
  77. package/scripts/gp-sep-invariant-prose.test.mjs +0 -188
  78. package/scripts/head-moved-after-label-prose.test.mjs +0 -233
  79. package/scripts/immutable-body-claim-prose.test.mjs +0 -204
  80. package/scripts/implementer-model-tier.test.mjs +0 -235
  81. package/scripts/inflight-citation-prose.test.mjs +0 -144
  82. package/scripts/inflight-exit2-prose.test.mjs +0 -81
  83. package/scripts/inflight-probe-guard-prose.test.mjs +0 -109
  84. package/scripts/inflight-scan-scope-prose.test.mjs +0 -57
  85. package/scripts/inflight.test.mjs +0 -2882
  86. package/scripts/injection-control-prose.test.mjs +0 -404
  87. package/scripts/install-root-audit.test.mjs +0 -464
  88. package/scripts/instrument-check-prose.test.mjs +0 -235
  89. package/scripts/instruments.test.mjs +0 -787
  90. package/scripts/is-cli.test.mjs +0 -99
  91. package/scripts/issue-tracker-prose.test.mjs +0 -71
  92. package/scripts/json.test.mjs +0 -364
  93. package/scripts/ledger-dispatch.test.mjs +0 -927
  94. package/scripts/ledger-grammar.test.mjs +0 -227
  95. package/scripts/ledger-read-require-file.test.mjs +0 -197
  96. package/scripts/ledger-rotate.test.mjs +0 -142
  97. package/scripts/ledger.test.mjs +0 -3436
  98. package/scripts/line-distance-prose.test.mjs +0 -245
  99. package/scripts/liveness-rationale-prose.test.mjs +0 -83
  100. package/scripts/locale-pin-prose.test.mjs +0 -189
  101. package/scripts/main-checkout.test.mjs +0 -332
  102. package/scripts/member-outcome-prose.test.mjs +0 -167
  103. package/scripts/member-outcomes-header.test.mjs +0 -129
  104. package/scripts/member-outcomes-prose.test.mjs +0 -63
  105. package/scripts/member-outcomes.test.mjs +0 -638
  106. package/scripts/member-prompt-prose.test.mjs +0 -165
  107. package/scripts/member-record.test.mjs +0 -541
  108. package/scripts/member-write-guard.test.mjs +0 -214
  109. package/scripts/merge-commit-probe-prose.test.mjs +0 -122
  110. package/scripts/merge-gate.test.mjs +0 -613
  111. package/scripts/muted-git-guard-sweep.test.mjs +0 -493
  112. package/scripts/net-ssh-precedence-prose.test.mjs +0 -91
  113. package/scripts/net-watchdog-prose.test.mjs +0 -79
  114. package/scripts/net.test.mjs +0 -211
  115. package/scripts/no-ci-gate-prose.test.mjs +0 -108
  116. package/scripts/no-undo-audit.test.mjs +0 -3961
  117. package/scripts/no-wave.test.mjs +0 -138
  118. package/scripts/node-floor-sweep.test.mjs +0 -611
  119. package/scripts/pointer-target-prose.test.mjs +0 -186
  120. package/scripts/pr-cost.test.mjs +0 -521
  121. package/scripts/pr-overlap.test.mjs +0 -692
  122. package/scripts/printf-die-sweep.test.mjs +0 -384
  123. package/scripts/prompt-renderer.mjs +0 -40
  124. package/scripts/prompt-renderer.test.mjs +0 -68
  125. package/scripts/prose-pin.mjs +0 -807
  126. package/scripts/prose-pin.test.mjs +0 -1034
  127. package/scripts/prove-merge.test.mjs +0 -995
  128. package/scripts/pull-table-relabel-prose.test.mjs +0 -60
  129. package/scripts/quiet-payload-prose.test.mjs +0 -222
  130. package/scripts/reap-cherry-check-prose.test.mjs +0 -80
  131. package/scripts/reap.test.mjs +0 -4432
  132. package/scripts/reaping-prose.test.mjs +0 -239
  133. package/scripts/reaping-reap-authorizers-prose.test.mjs +0 -112
  134. package/scripts/reaping-release-authorizers-prose.test.mjs +0 -85
  135. package/scripts/recipe-derivation-prose.test.mjs +0 -112
  136. package/scripts/recipe-prove.test.mjs +0 -1042
  137. package/scripts/refuter-scratch-prose.test.mjs +0 -135
  138. package/scripts/release-label-required-prose.test.mjs +0 -71
  139. package/scripts/release-label-split-prose.test.mjs +0 -184
  140. package/scripts/release-ticket-reap-pairing-prose.test.mjs +0 -63
  141. package/scripts/release-ticket.test.mjs +0 -5099
  142. package/scripts/renovate-release-contract.test.mjs +0 -379
  143. package/scripts/repo-root.test.mjs +0 -873
  144. package/scripts/reporter-output-rule-prose.test.mjs +0 -208
  145. package/scripts/review-agent-report-only.test.mjs +0 -49
  146. package/scripts/review-core-booking.test.mjs +0 -35
  147. package/scripts/review-core-cwd-isolation.test.mjs +0 -374
  148. package/scripts/review-core-reads.test.mjs +0 -478
  149. package/scripts/review-core-refuter-scratch.test.mjs +0 -148
  150. package/scripts/review-core-scratch-refusal.test.mjs +0 -64
  151. package/scripts/review-core-shared-test-run.test.mjs +0 -275
  152. package/scripts/review-core-snapshot-path.test.mjs +0 -830
  153. package/scripts/review-core-specialist-scratch.test.mjs +0 -191
  154. package/scripts/review-core-testcmd.test.mjs +0 -335
  155. package/scripts/review-core-unrun.test.mjs +0 -566
  156. package/scripts/review-core-unverified-discriminant.test.mjs +0 -208
  157. package/scripts/review-eval-resolver-path.test.mjs +0 -55
  158. package/scripts/review-host-fixture.mjs +0 -89
  159. package/scripts/review-in-run-retry.test.mjs +0 -211
  160. package/scripts/review-no-vendor-dispatch.test.mjs +0 -45
  161. package/scripts/review-path-default.test.mjs +0 -796
  162. package/scripts/review-runner-spawns.test.mjs +0 -95
  163. package/scripts/review-runner.test.mjs +0 -166
  164. package/scripts/review-tier-audit.test.mjs +0 -140
  165. package/scripts/run-artifact-pr-prose.test.mjs +0 -341
  166. package/scripts/run-merge-bot-prose.test.mjs +0 -1413
  167. package/scripts/run-team-local-hook.test.mjs +0 -442
  168. package/scripts/scratch-partition-invariant-prose.test.mjs +0 -74
  169. package/scripts/scripts-path-citation-sweep.test.mjs +0 -73
  170. package/scripts/section-between-guard-prose.test.mjs +0 -379
  171. package/scripts/select-dimensions.test.mjs +0 -674
  172. package/scripts/shared-refusal.test.mjs +0 -388
  173. package/scripts/shell-traps-prose.test.mjs +0 -504
  174. package/scripts/shortlist.test.mjs +0 -380
  175. package/scripts/slow-transport.mjs +0 -72
  176. package/scripts/snapshot-repo.test.mjs +0 -1006
  177. package/scripts/snapshot-runner-audience-prose.test.mjs +0 -130
  178. package/scripts/spend-view.test.mjs +0 -312
  179. package/scripts/staleness-qualifier-prose.test.mjs +0 -251
  180. package/scripts/staleness-verdict-prose.test.mjs +0 -142
  181. package/scripts/staleness.test.mjs +0 -893
  182. package/scripts/stalled-member-liveness-prose.test.mjs +0 -219
  183. package/scripts/stash-prohibition-prose.test.mjs +0 -313
  184. package/scripts/strip-comments.mjs +0 -44
  185. package/scripts/temp-dir.mjs +0 -47
  186. package/scripts/ticket-router.test.mjs +0 -981
  187. package/scripts/tier-check.test.mjs +0 -828
  188. package/scripts/tier-outcomes-header.test.mjs +0 -518
  189. package/scripts/tier-outcomes.test.mjs +0 -572
  190. package/scripts/tier-roles.test.mjs +0 -535
  191. package/scripts/tracker-block-copy-prose.test.mjs +0 -288
  192. package/scripts/triage-labels-gloss-prose.test.mjs +0 -97
  193. package/scripts/unattended-git-sweep.test.mjs +0 -142
  194. package/scripts/verify-sha-exit2-prose.test.mjs +0 -269
  195. package/scripts/verify-sha.test.mjs +0 -692
  196. package/scripts/watcher-degraded-block.test.mjs +0 -369
  197. package/scripts/watcher-key-prose.test.mjs +0 -106
  198. package/scripts/within-run-pair-prose.test.mjs +0 -212
  199. package/scripts/worktree-audit.test.mjs +0 -1408
  200. package/scripts/worktree-head-prose.test.mjs +0 -276
  201. package/scripts/worktree-listing-sweep.test.mjs +0 -217
  202. package/scripts/worktree-model-prose.test.mjs +0 -216
  203. package/scripts/worktree-porcelain.mjs +0 -35
  204. package/scripts/worktree-porcelain.test.mjs +0 -102
@@ -1,1933 +0,0 @@
1
- // Regression gate for the no-CI portability fix (#111): a repo with no
2
- // workflow file must get its own `no-ci` verdict rather than sharing exit 2
3
- // with "the question could not be answered", the workflow file must be
4
- // discovered by the workflow's `name:` rather than assumed to be
5
- // `.github/workflows/ci.yml`, and absence must never silently pass — only
6
- // `--declare-no-ci` flips the gate.
7
- //
8
- // `gh` is stubbed on PATH and logs every call it receives, so a test can
9
- // assert `run list`/`run view` were never reached under no-ci — the point of
10
- // skipping them (#262's REST budget) is unverifiable without that log. The
11
- // workflow trees are served by that stub too, as the GraphQL reply the
12
- // script reads them from at the PR's head and base commits: `repoFiles`
13
- // paths under `.github/workflows/` become both trees unless `headFiles` or
14
- // `baseFiles` says otherwise, and nothing is read off the fixture's disk.
15
- // The repository and its host come from the stub's `gh repo view` reply, as
16
- // the script takes them from gh's own resolution rather than from git.
17
-
18
- import { test } from "node:test";
19
- import assert from "node:assert/strict";
20
- import { spawnSync } from "node:child_process";
21
- import { mkdtempSync, mkdirSync, writeFileSync, chmodSync, rmSync, readFileSync, statSync, openSync, closeSync } from "node:fs";
22
- import { tmpdir } from "node:os";
23
- import { join } from "node:path";
24
- import { fileURLToPath } from "node:url";
25
- import { stripComments } from "./strip-comments.mjs";
26
- import { writeExecStub } from "./exec-stub.mjs";
27
-
28
- const SCRIPT = fileURLToPath(new URL("./ci-state.mjs", import.meta.url));
29
-
30
- // A `gh` failure carries a MESSAGE, not just an exit code, and the cause a
31
- // caller can act on lives only in that message. `$GH_FAIL_MSG` is how a test
32
- // picks which cause this stub refuses with; empty — the default every fixture
33
- // above already relies on — keeps the bare `exit 1` with a silent stderr.
34
- //
35
- // Two more behaviours of the real gh are reproduced because the script
36
- // depends on them. A GraphQL reply carrying `errors` is printed on stdout all
37
- // the same and exits 1 (measured: a `file(path:)` on a missing path). And gh
38
- // resolves the repository by running git, so an ambient GIT_DIR or
39
- // GIT_WORK_TREE reaching it would answer for another repository — the stub
40
- // logs either one it receives, so a test can assert none ever does.
41
- const GH_STUB = `#!/bin/sh
42
- [ -n "\${GIT_DIR+x}\${GIT_WORK_TREE+x}" ] && echo "ambient GIT_DIR=\${GIT_DIR-} GIT_WORK_TREE=\${GIT_WORK_TREE-}" >> "$GH_LOG"
43
- echo "$*" >> "$GH_LOG"
44
- fail() { [ -n "$GH_FAIL_MSG" ] && echo "$GH_FAIL_MSG" >&2; exit 1; }
45
- case "$1 $2" in
46
- "api graphql") case "$*" in *baseExpr=*) f="$BASE_READ_FILE" ;; *) f="$PR_READ_FILE" ;; esac
47
- [ -f "$f" ] || fail
48
- cat "$f"
49
- if grep -q '"errors":' "$f"; then echo "gh: Could not resolve file for path" >&2; exit 1; fi ;;
50
- "api repos/{owner}/{repo}/rules/branches/"*) [ -f "$RULES_FILE" ] && cat "$RULES_FILE" || fail ;;
51
- "api repos/{owner}/{repo}/branches/"*) [ -f "$PROTECTION_FILE" ] && cat "$PROTECTION_FILE" || fail ;;
52
- "run list") [ -f "$RUN_LIST_FILE" ] && cat "$RUN_LIST_FILE" || fail ;;
53
- "run view") [ -f "$RUN_VIEW_FILE" ] && cat "$RUN_VIEW_FILE" || fail ;;
54
- "repo view") [ -f "$REPO_VIEW_FILE" ] && cat "$REPO_VIEW_FILE" || fail ;;
55
- *) fail ;;
56
- esac
57
- `;
58
-
59
- const PR_HEAD = "abc123def";
60
- const BASE_OID = "bbb000bbb";
61
- const BRANCH = "fix/1";
62
- const PR_VIEW = JSON.stringify({
63
- headRefName: BRANCH,
64
- headRefOid: PR_HEAD,
65
- baseRefName: "main",
66
- baseRefOid: BASE_OID,
67
- state: "OPEN",
68
- mergeStateStatus: "CLEAN",
69
- });
70
- const RUN_LIST = JSON.stringify([
71
- { databaseId: 1, headSha: PR_HEAD, status: "completed", conclusion: "success", event: "pull_request", createdAt: "2026-01-01T00:00:00Z" },
72
- ]);
73
- const RUN_VIEW = JSON.stringify({
74
- jobs: [{ name: "check", status: "completed", conclusion: "success" }],
75
- attempt: 1,
76
- status: "completed",
77
- conclusion: "success",
78
- headSha: PR_HEAD,
79
- });
80
- const REPO_VIEW = JSON.stringify({ nameWithOwner: "acme/repo", url: "https://github.com/acme/repo" });
81
-
82
- const WF = ".github/workflows";
83
- const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
84
-
85
- // The GraphQL tree for `.github/workflows` at one commit, built from a
86
- // `{ path: content }` map: null when no path lies under it (the directory
87
- // does not exist there). A content that is an object stands for a blob the
88
- // API could not hand back whole — `{ text: null }` (binary or absent) or
89
- // `{ truncated: true }` — and `{ dir: true }` for a subdirectory entry.
90
- function treeOf(files) {
91
- const entries = Object.entries(files)
92
- .filter(([p]) => p.startsWith(`${WF}/`))
93
- .map(([p, c]) => {
94
- const name = p.slice(WF.length + 1);
95
- if (isObj(c) && c.dir) return { name, type: "tree", object: { __typename: "Tree" } };
96
- if (isObj(c)) return { name, type: "blob", object: { __typename: "Blob", text: c.truncated ? "name: CI\n" : (c.text ?? null), isTruncated: !!c.truncated } };
97
- return { name, type: "blob", object: { __typename: "Blob", text: c, isTruncated: false } };
98
- });
99
- return entries.length ? { __typename: "Tree", entries } : null;
100
- }
101
-
102
- // One commit's `file(path: ".github/workflows")` entry around such a tree, and
103
- // the error GitHub sends beside the null where the path does not exist.
104
- const entryOf = (tree) => (tree === null ? null : { type: "tree", object: tree });
105
- const notFoundAt = (...path) => ({ type: "NOT_FOUND", path, message: `Could not resolve file for path '${WF}'.` });
106
- const withErrors = (data, errors) => JSON.stringify(errors.length ? { data, errors } : { data });
107
-
108
- // The required-checks replies: `rules` is the contexts every ruleset requires,
109
- // `classic` the classic branch protection's own list.
110
- const rulesReply = (contexts) =>
111
- JSON.stringify([[{ type: "deletion" }, { type: "required_status_checks", parameters: { required_status_checks: contexts.map((context) => ({ context, integration_id: 15368 })) } }]]);
112
- const protectionReply = (contexts) =>
113
- JSON.stringify({ name: "main", protected: contexts.length > 0, protection: { enabled: contexts.length > 0, required_status_checks: { enforcement_level: contexts.length ? "non_admins" : "off", contexts, checks: [] } } });
114
-
115
- // repoFiles: { "relative/path": "content" } — the workflow files at BOTH
116
- // commits unless headFiles/baseFiles replaces one side. A side with none gets
117
- // a null `file` entry plus GitHub's NOT_FOUND for it, as the real API sends.
118
- // baseEntryRaw: the base's `file` entry verbatim, with no error beside it.
119
- // baseTip: the oid the base branch's tip reports; anything but BASE_OID sends
120
- // the script to its second, oid-bound base read, which answers baseReadOid.
121
- // headOid: what `refs/pull/N/head` resolves to.
122
- // prErrors: extra entries for the first GraphQL reply's `errors`.
123
- // rules/classic: required contexts (ruleset / classic protection); pass
124
- // rulesRaw/protectionRaw to serve a reply verbatim, `null` to make it fail.
125
- // cwd: repo-relative directory to run from.
126
- // pr: the `--pr` value, defaulting to the digits every other fixture wants;
127
- // `null` omits the flag entirely, for the tests that probe how the argument
128
- // itself is refused rather than what it selects.
129
- // gh responses default to the green fixtures above; pass `null` to make that gh
130
- // subcommand fail (exit 1) if reached, so an unexpected call surfaces as a
131
- // crash rather than silently serving the wrong fixture. `prView` is the
132
- // pullRequest object inside the first GraphQL reply; null fails that read.
133
- // `repoView` is gh's own resolution of the cwd's repository, which is where
134
- // the script takes the host from; `remotes` ({ name: url }) are added to the
135
- // fixture's git repository, which the script must never read a host from.
136
- function run(args, { repoFiles = {}, headFiles = null, baseFiles = null, tipFiles = null, baseEntryRaw, baseTip = BASE_OID, baseReadOid = BASE_OID, headOid = PR_HEAD, prErrors = [], rules = [], classic = [], rulesRaw, protectionRaw, cwd = ".", localFiles = {}, pr = "42", prView = PR_VIEW, runList = RUN_LIST, runView = RUN_VIEW, ghFailMsg = "", tolerateUnparsedStdout = false, readOnlyStdout = false, nonBlockingStdout = false, repoView = REPO_VIEW, remotes = {}, spawnEnv = {} } = {}) {
137
- const repoDir = mkdtempSync(join(tmpdir(), "ci-state-repo-"));
138
- spawnSync("git", ["init", "-q", repoDir], { stdio: "ignore" });
139
- for (const [name, url] of Object.entries(remotes)) spawnSync("git", ["remote", "add", name, url], { cwd: repoDir, stdio: "ignore" });
140
- const binDir = mkdtempSync(join(tmpdir(), "ci-state-bin-"));
141
- // localFiles: written into the caller's working tree, which the script must
142
- // never read — the cwd-independence tests put a DIFFERENT workflow here.
143
- for (const [rel, content] of Object.entries(localFiles)) {
144
- const full = join(repoDir, rel);
145
- mkdirSync(join(full, ".."), { recursive: true });
146
- writeFileSync(full, content);
147
- }
148
- mkdirSync(join(repoDir, cwd), { recursive: true });
149
- const gh = join(binDir, "gh");
150
- writeExecStub(gh, GH_STUB);
151
- const ghLog = join(binDir, "gh.log");
152
- writeFileSync(ghLog, "");
153
-
154
- const baseEntry = baseEntryRaw !== undefined ? baseEntryRaw : entryOf(treeOf(baseFiles ?? repoFiles));
155
- const baseAbsent = baseEntryRaw === undefined && baseEntry === null;
156
- const tipEntry = tipFiles === null ? baseEntry : entryOf(treeOf(tipFiles));
157
- const tipAbsent = tipFiles === null ? baseAbsent : tipEntry === null;
158
- const headEntry = entryOf(treeOf(headFiles ?? repoFiles));
159
- let firstReply = null;
160
- if (prView !== null) {
161
- const pull = JSON.parse(prView);
162
- const errors = [...prErrors];
163
- if (isObj(pull) && !Object.hasOwn(pull, "baseRef")) {
164
- pull.baseRef = { target: { oid: baseTip, file: tipEntry } };
165
- if (tipAbsent) errors.push(notFoundAt("repository", "pullRequest", "baseRef", "target", "file"));
166
- }
167
- if (headEntry === null) errors.push(notFoundAt("repository", "head", "file"));
168
- firstReply = withErrors({ repository: { pullRequest: pull, head: { oid: headOid, file: headEntry } } }, errors);
169
- }
170
- const fixtureFile = (name, content) => {
171
- if (content === null) return "";
172
- const p = join(binDir, name);
173
- writeFileSync(p, content);
174
- return p;
175
- };
176
- const env = {
177
- ...process.env,
178
- PATH: `${binDir}:${process.env.PATH}`,
179
- GH_LOG: ghLog,
180
- GH_FAIL_MSG: ghFailMsg,
181
- PR_READ_FILE: fixtureFile("pr-read.json", firstReply),
182
- BASE_READ_FILE: fixtureFile("base-read.json", withErrors({ repository: { base: { oid: baseReadOid, file: baseEntry } } }, baseAbsent ? [notFoundAt("repository", "base", "file")] : [])),
183
- RULES_FILE: fixtureFile("rules.json", rulesRaw === undefined ? rulesReply(rules) : rulesRaw),
184
- PROTECTION_FILE: fixtureFile("protection.json", protectionRaw === undefined ? protectionReply(classic) : protectionRaw),
185
- RUN_LIST_FILE: fixtureFile("run-list.json", runList),
186
- RUN_VIEW_FILE: fixtureFile("run-view.json", runView),
187
- REPO_VIEW_FILE: fixtureFile("repo-view.json", repoView),
188
- // Last, so a test can deliberately put back a var spawn()'s gitEnv()
189
- // scrub removes — that is the whole point of the ambient GIT_DIR test
190
- // below.
191
- ...spawnEnv,
192
- };
193
- // readOnlyStdout: hand the child a stdout it cannot write to, so its first
194
- // write fails with EBADF rather than by racing a reader. CLOSING fd 1 does
195
- // not do it — libuv reopens a closed standard fd onto /dev/null and the write
196
- // then succeeds (measured), which is why this opens /dev/null read-only and
197
- // passes that fd instead. spawnSync then reports no stdout for the child at
198
- // all, so the eager parse below has nothing to read and skips.
199
- const roStdout = readOnlyStdout ? openSync("/dev/null", "r") : null;
200
- // nonBlockingStdout: the child's fd 1 starts out blocking and the script
201
- // never opens a stream on it, so its writes there wait for the reader and
202
- // cannot raise EAGAIN. This preloads a module whose whole body touches
203
- // process.stdout, which opens that stream and puts fd 1 in O_NONBLOCK, the
204
- // same as one console.log anywhere in the script would.
205
- const preload = nonBlockingStdout ? ["--import", "data:text/javascript,process.stdout"] : [];
206
- let r;
207
- try {
208
- // maxBuffer: spawnSync's default 1 MiB kills the child mid-write once its
209
- // output passes it, and the pipe-survival fixtures below write past it on
210
- // purpose.
211
- r = spawnSync(process.execPath, [...preload, SCRIPT, ...(pr === null ? [] : ["--pr", pr]), ...args], {
212
- cwd: join(repoDir, cwd),
213
- encoding: "utf8",
214
- env,
215
- maxBuffer: 8 * 1024 * 1024,
216
- ...(roStdout === null ? {} : { stdio: ["ignore", roStdout, "pipe"] }),
217
- });
218
- } finally {
219
- if (roStdout !== null) closeSync(roStdout);
220
- }
221
- const log = readFileSync(ghLog, "utf8");
222
- // Parsing eagerly is what lets every other test assert straight off `payload`,
223
- // and a parse failure throwing here is the right default: it names a malformed
224
- // payload at the test that produced it. The pipe-survival tests are the one
225
- // exception — unparsed stdout is precisely their subject, so they opt out and
226
- // assert on the raw bytes themselves.
227
- let payload = null;
228
- if (r.stdout && r.stdout.trim()) {
229
- try {
230
- payload = JSON.parse(r.stdout.trim().split("\n").pop());
231
- } catch (e) {
232
- if (!tolerateUnparsedStdout) throw e;
233
- }
234
- }
235
- rmSync(repoDir, { recursive: true, force: true });
236
- rmSync(binDir, { recursive: true, force: true });
237
- return { ...r, payload, log };
238
- }
239
-
240
- const CI_WORKFLOW = `name: CI
241
- on: [pull_request]
242
- jobs:
243
- check:
244
- runs-on: ubuntu-latest
245
- steps:
246
- - run: echo hi
247
- `;
248
- const OTHER_WORKFLOW = `name: Release Label
249
- on: [push]
250
- jobs:
251
- label:
252
- runs-on: ubuntu-latest
253
- steps:
254
- - run: echo hi
255
- `;
256
-
257
- test("no .github/workflows directory: no-ci verdict, exit 1, never reads run list/view", () => {
258
- const r = run([]);
259
- assert.equal(r.status, 1);
260
- assert.equal(r.payload.verdict, "no-ci");
261
- assert.equal(r.payload.reasons.length, 1);
262
- assert.match(r.payload.reasons[0], /declare-no-ci/);
263
- assert.doesNotMatch(r.log, /run list/);
264
- assert.doesNotMatch(r.log, /run view/);
265
- });
266
-
267
- test("no CI + --declare-no-ci: still no-ci verdict, but gate satisfied — exit 0", () => {
268
- const r = run(["--declare-no-ci"]);
269
- assert.equal(r.status, 0);
270
- assert.equal(r.payload.verdict, "no-ci");
271
- assert.match(r.payload.reasons[0], /gating on the caller's verified suite run/);
272
- });
273
-
274
- test("workflow file discovered by name, not the hard-coded ci.yml path — repo behaviour unchanged", () => {
275
- const r = run([], {
276
- repoFiles: {
277
- ".github/workflows/pipeline.yml": CI_WORKFLOW, // not named ci.yml
278
- ".github/workflows/release-label.yml": OTHER_WORKFLOW, // sibling, different name — must not confuse discovery
279
- },
280
- });
281
- assert.equal(r.status, 0, r.stdout + r.stderr);
282
- assert.equal(r.payload.verdict, "green");
283
- assert.deepEqual(r.payload.reasons, []);
284
- });
285
-
286
- test("two workflow files share the target name: ambiguous, dies (exit 2) rather than guessing", () => {
287
- const r = run([], {
288
- repoFiles: {
289
- ".github/workflows/a.yml": CI_WORKFLOW,
290
- ".github/workflows/b.yml": CI_WORKFLOW,
291
- },
292
- });
293
- assert.equal(r.status, 2);
294
- assert.match(r.stderr, /pass --workflow-file to pick one/);
295
- });
296
-
297
- // Both routes to a workflow blob the API could not hand back whole refuse with
298
- // exit 2: discovery has to read every YAML blob to learn which one carries the
299
- // workflow's name, and an explicit --workflow-file names its target outright.
300
- // A text that is absent (binary) and one that is truncated are both cases: a
301
- // truncated text is not a shorter workflow, and parsing it would derive a job
302
- // set from half a file.
303
- for (const [route, args] of [
304
- ["the discovery scan", []],
305
- ["an explicit --workflow-file", ["--workflow-file", ".github/workflows/ci.yml"]],
306
- ]) {
307
- for (const [what, blob] of [["absent", { text: null }], ["truncated", { truncated: true }]]) {
308
- test(`a workflow blob whose text came back ${what}, reached through ${route}: exit 2, never no-ci`, () => {
309
- for (const extra of [[], ["--declare-no-ci"]]) {
310
- const r = run([...args, ...extra], { repoFiles: { ".github/workflows/ci.yml": blob } });
311
- assert.equal(r.status, 2, r.stdout + r.stderr);
312
- assert.match(r.stderr, /cannot read \.github\/workflows\/ci\.yml at the base commit/);
313
- assert.equal(r.payload, null);
314
- }
315
- });
316
- }
317
- }
318
-
319
- // --- Error policy (#111): only a genuinely absent workflow set is `no-ci` ---
320
- // The verdict must be reachable one way only: `.github/workflows/` absent at
321
- // the base, or present and holding no workflow files. Every other outcome —
322
- // the path not a directory, a blob not read whole, files present under other
323
- // names — is exit 2, "the question could not be answered", and
324
- // `--declare-no-ci` must not convert any of them to exit 0.
325
-
326
- const CI_WORKFLOW_COMMENTED = CI_WORKFLOW.replace("name: CI", `name: "CI" # main pipeline`);
327
-
328
- // Absence is what GitHub says NOT_FOUND about; anything else standing at the
329
- // path is not it. A submodule there reads back with a null `object` exactly
330
- // as a missing path does, so only the entry's `type` tells them apart.
331
- for (const [what, entry] of [
332
- ["a file", { type: "blob", object: { __typename: "Blob", text: "x", isTruncated: false } }],
333
- ["a submodule", { type: "commit", object: null }],
334
- ["a null entry GitHub sent no NOT_FOUND for", null],
335
- ]) {
336
- test(`\`.github/workflows\` at the base that is ${what}: exit 2, never no-ci — --declare-no-ci cannot let it through`, () => {
337
- for (const args of [[], ["--declare-no-ci"]]) {
338
- const r = run(args, { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW }, baseEntryRaw: entry });
339
- assert.equal(r.status, 2, r.stdout + r.stderr);
340
- assert.match(r.stderr, /\.github\/workflows at the base commit is not a readable directory/);
341
- assert.equal(r.payload, null);
342
- }
343
- });
344
- }
345
-
346
- // gh exits 1 on a reply carrying a NOT_FOUND for a missing path, so the
347
- // absence a no-ci verdict rests on arrives as a failed read — on either base
348
- // read, the tip's or the oid-bound second one.
349
- for (const [route, opts] of [
350
- ["the base tip's", {}],
351
- ["the oid-bound second", { baseTip: "ccc111ccc", tipFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } }],
352
- ]) {
353
- test(`no workflows directory at the base, as ${route} read reports it (NOT_FOUND, gh exit 1): no-ci`, () => {
354
- const r = run([], { ...opts, baseFiles: {}, headFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } });
355
- assert.equal(r.status, 1, r.stdout + r.stderr);
356
- assert.equal(r.payload.verdict, "no-ci");
357
- });
358
- }
359
-
360
- for (const [what, err] of [
361
- ["a NOT_FOUND somewhere other than a workflow directory", { type: "NOT_FOUND", path: ["repository", "pullRequest"] }],
362
- ["another error on the head's workflow directory", { type: "FORBIDDEN", path: ["repository", "head", "file"] }],
363
- ["an error with no path", { type: "NOT_FOUND" }],
364
- ]) {
365
- test(`a GraphQL reply carrying ${what} fails the read (exit 2), whatever data came with it`, () => {
366
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW }, prErrors: [err] });
367
- assert.equal(r.status, 2, r.stdout + r.stderr);
368
- assert.match(r.stderr, /ci-state: gh failed: exit 1/);
369
- assert.equal(r.payload, null);
370
- });
371
- }
372
-
373
- test("a workflows directory holding no YAML at the base is a genuine no-ci", () => {
374
- const r = run([], { repoFiles: { ".github/workflows/README.md": "nothing here" } });
375
- assert.equal(r.status, 1, r.stdout + r.stderr);
376
- assert.equal(r.payload.verdict, "no-ci");
377
- });
378
-
379
- test("workflow name with a trailing YAML comment (and quotes) still matches — a configured repo never reads as no-ci", () => {
380
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW_COMMENTED } });
381
- assert.equal(r.status, 0, r.stdout + r.stderr);
382
- assert.equal(r.payload.verdict, "green");
383
- });
384
-
385
- test("workflow files present but none named CI: exit 2 naming them, never a declarable no-ci", () => {
386
- for (const args of [[], ["--declare-no-ci"]]) {
387
- const r = run(args, {
388
- repoFiles: {
389
- ".github/workflows/release-label.yml": OTHER_WORKFLOW,
390
- ".github/workflows/release.yml": OTHER_WORKFLOW.replace("Release Label", "Release"),
391
- },
392
- });
393
- assert.equal(r.status, 2, r.stdout + r.stderr);
394
- assert.match(r.stderr, /none named 'CI'/);
395
- assert.match(r.stderr, /release-label\.yml/);
396
- // The false statement this replaced: "no workflows configured under
397
- // .github/workflows/" said of a directory full of workflows.
398
- assert.doesNotMatch(r.stderr, /no workflows configured/);
399
- }
400
- });
401
-
402
- // Discovery cannot skip a YAML blob it could not read: until its text is
403
- // read, nothing says it is not a second file carrying the workflow's name.
404
- test("an unreadable sibling YAML blob refuses rather than being skipped — its name cannot be settled", () => {
405
- const r = run([], {
406
- repoFiles: {
407
- ".github/workflows/ci.yml": CI_WORKFLOW,
408
- ".github/workflows/zz-other.yml": { truncated: true },
409
- },
410
- });
411
- assert.equal(r.status, 2, r.stdout + r.stderr);
412
- assert.match(r.stderr, /cannot read \.github\/workflows\/zz-other\.yml/);
413
- });
414
-
415
- // A non-YAML entry and a subdirectory are neither workflows nor unreadable
416
- // workflows: they must not refuse a repo whose CI workflow reads fine.
417
- test("a non-YAML file or a subdirectory in the workflows directory does not disturb discovery", () => {
418
- const r = run([], {
419
- repoFiles: {
420
- ".github/workflows/ci.yml": CI_WORKFLOW,
421
- ".github/workflows/README.md": { text: null },
422
- ".github/workflows/shared.yml": { dir: true },
423
- },
424
- });
425
- assert.equal(r.status, 0, r.stdout + r.stderr);
426
- assert.equal(r.payload.verdict, "green");
427
- });
428
-
429
- // The verdict is a property of the PR and its run, not of whoever asks. The
430
- // caller's working tree used to supply the expected set, so a `main` checkout
431
- // and the PR's own worktree read the same run differently. Here the working
432
- // tree carries a CI workflow with a job the run never had, and the answer from
433
- // it, from a subdirectory, and from an empty tree must be identical.
434
- test("the same PR and run give the same verdict whatever the caller's working tree holds", () => {
435
- const repoFiles = { ".github/workflows/ci.yml": CI_WORKFLOW };
436
- const stale = { ".github/workflows/ci.yml": `${CI_WORKFLOW} stale-job:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n` };
437
- const answers = [
438
- run([], { repoFiles }),
439
- run([], { repoFiles, localFiles: stale }),
440
- run([], { repoFiles, localFiles: stale, cwd: "scripts" }),
441
- ];
442
- for (const r of answers) assert.equal(r.status, 0, r.stdout + r.stderr);
443
- assert.deepEqual(answers[1].payload, answers[0].payload);
444
- assert.deepEqual(answers[2].payload, answers[0].payload);
445
- });
446
-
447
- test("a cwd gh resolves no repository from refuses (exit 2) before any other read", () => {
448
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW }, repoView: null });
449
- assert.equal(r.status, 2, r.stdout + r.stderr);
450
- assert.match(r.stderr, /no GitHub repository resolves from this cwd's git remotes/);
451
- assert.equal(r.log, "repo view --json nameWithOwner,url\n", "nothing may be read for a repository that was never resolved");
452
- });
453
-
454
- for (const [what, view, said] of [
455
- ["a url with no host", { nameWithOwner: "acme/repo", url: "not a url" }, /url carries no host \(got "not a url"\)/],
456
- ["no nameWithOwner", { url: "https://github.com/acme/repo" }, /nameWithOwner is not owner\/name \(the key is absent\)/],
457
- ]) {
458
- test(`gh's repository resolution answering with ${what} refuses (exit 2) before any other read`, () => {
459
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW }, repoView: JSON.stringify(view) });
460
- assert.equal(r.status, 2, r.stdout + r.stderr);
461
- assert.match(r.stderr, said);
462
- assert.equal(r.log, "repo view --json nameWithOwner,url\n");
463
- });
464
- }
465
-
466
- // The host is gh's resolution of the repository, never a parse of a remote
467
- // URL: credentials in the URL, an ssh host alias and a remote not named
468
- // `origin` each made that parse name a host gh could not reach, or none.
469
- // Every `gh api` read names it — the rules and protection reads included,
470
- // which only a dropped-and-absent job reaches.
471
- const GHE_VIEW = JSON.stringify({ nameWithOwner: "acme/repo", url: "https://ghe-real.example/acme/repo" });
472
- for (const [what, remotes] of [
473
- ["an origin URL carrying credentials", { origin: "https://x-access-token:tok@ghe-real.example/acme/repo.git" }],
474
- ["an origin through an ssh host alias", { origin: "git@ghe-work:acme/repo.git" }],
475
- ["no remote named origin", { upstream: "ssh://git@ghe-real.example/acme/repo.git" }],
476
- ]) {
477
- test(`${what}: every gh api read names the host gh resolved`, () => {
478
- const r = run([], {
479
- remotes,
480
- repoView: GHE_VIEW,
481
- baseFiles: { ".github/workflows/ci.yml": TWO_JOB_WORKFLOW },
482
- headFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
483
- classic: ["integration"],
484
- });
485
- assert.equal(r.status, 1, r.stdout + r.stderr);
486
- const reads = r.log.split("\n").filter((l) => l.startsWith("api "));
487
- for (const read of [/^api graphql /, /^api repos\/\{owner\}\/\{repo\}\/rules\/branches\/main /, /^api repos\/\{owner\}\/\{repo\}\/branches\/main /, /^api --hostname \S+ repos\/acme\/repo\/compare\//]) {
488
- assert.ok(reads.some((l) => read.test(l)), `expected a read matching ${read}, the log reads: ${r.log}`);
489
- }
490
- for (const l of reads) assert.match(l, /--hostname ghe-real\.example( |$)/, `a gh api read without the resolved host: ${l}`);
491
- });
492
- }
493
-
494
- // gh resolves the repository by running git, and an ambient GIT_DIR or
495
- // GIT_WORK_TREE (a git hook, `rebase --exec`, `bisect run`) outranks its cwd —
496
- // measured, `gh repo view` and `gh api repos/{owner}/{repo}` then answer for
497
- // the repository GIT_DIR names. So neither may reach any gh call; the stub
498
- // logs either one it receives.
499
- test("an inherited GIT_DIR or GIT_WORK_TREE never reaches gh", () => {
500
- const other = mkdtempSync(join(tmpdir(), "ci-state-other-"));
501
- try {
502
- const r = run([], {
503
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
504
- spawnEnv: { GIT_DIR: join(other, ".git"), GIT_WORK_TREE: other },
505
- });
506
- assert.equal(r.status, 0, r.stdout + r.stderr);
507
- assert.match(r.log, /^repo view /m);
508
- assert.doesNotMatch(r.log, /ambient GIT_DIR/, `an ambient git variable reached gh: ${r.log}`);
509
- } finally {
510
- rmSync(other, { recursive: true, force: true });
511
- }
512
- });
513
-
514
- // expectedJobs() refuses on the assumption its derivation rests on, and that
515
- // refusal has to land before the run query — the answer it would otherwise
516
- // spend a REST read on is one it has already decided it cannot give. Nothing
517
- // else in this file reaches the derivation's die() at all, so the gh log is
518
- // what pins the order rather than the refusal alone.
519
- const CI_WORKFLOW_NAMED_JOB = CI_WORKFLOW.replace(" check:\n", " check:\n name: Check\n");
520
-
521
- test("an invalid job derivation refuses before the run list is ever requested", () => {
522
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW_NAMED_JOB } });
523
- assert.equal(r.status, 2, r.stdout + r.stderr);
524
- assert.match(r.stderr, /derivation invalid/);
525
- assert.doesNotMatch(r.log, /run list/, `the derivation must refuse before the query, and gh was asked: ${r.log}`);
526
- });
527
-
528
- // --- The not-green detectors, one negative case each ------------------------
529
- // No fixture above enters the `reasons.push` branches in the `else` arm, so
530
- // none of them can catch one being deleted — and each such deletion is a silent
531
- // false green reaching board.mjs's mapCi() and the merge bot's gate.
532
-
533
- const TWO_JOB_WORKFLOW = `name: CI
534
- on: [pull_request]
535
- jobs:
536
- check:
537
- runs-on: ubuntu-latest
538
- steps:
539
- - run: echo hi
540
- integration:
541
- runs-on: ubuntu-latest
542
- steps:
543
- - run: echo hi
544
- `;
545
-
546
- const notGreen = (overrides, repoFiles = { ".github/workflows/ci.yml": CI_WORKFLOW }) =>
547
- run([], { repoFiles, runView: JSON.stringify({ ...JSON.parse(RUN_VIEW), ...overrides }) });
548
-
549
- test("run bound to another commit: not-green, exit 1 — the cancelled-run-on-a-superseded-SHA case", () => {
550
- const r = notGreen({ headSha: "0000000" });
551
- assert.equal(r.status, 1);
552
- assert.equal(r.payload.verdict, "not-green");
553
- assert.match(r.payload.reasons.join("; "), /run headSha 0000000 != PR head abc123def/);
554
- });
555
-
556
- test("run still in progress: not-green, exit 1 — an incomplete run is not a pass", () => {
557
- const r = notGreen({ status: "in_progress" });
558
- assert.equal(r.status, 1);
559
- assert.equal(r.payload.verdict, "not-green");
560
- assert.match(r.payload.reasons.join("; "), /run status is in_progress, not completed/);
561
- });
562
-
563
- test("expected job absent from the run: not-green, exit 1 — an absent job reads as pending, never as green", () => {
564
- const r = notGreen({}, { ".github/workflows/ci.yml": TWO_JOB_WORKFLOW });
565
- assert.equal(r.status, 1);
566
- assert.equal(r.payload.verdict, "not-green");
567
- assert.match(r.payload.reasons.join("; "), /expected jobs absent from the run: integration/);
568
- });
569
-
570
- test("`skipped` is not `passed`: a skipped job is not-green, exit 1", () => {
571
- const r = notGreen({ jobs: [{ name: "check", status: "completed", conclusion: "skipped" }] });
572
- assert.equal(r.status, 1);
573
- assert.equal(r.payload.verdict, "not-green");
574
- assert.match(r.payload.reasons.join("; "), /job check is skipped, not success/);
575
- });
576
-
577
- // gh's REAL shape for an in-progress job is conclusion:"" (empty string),
578
- // never null — the same shape #1566 fixed in rank()'s tie-break. `??`
579
- // only falls through on null/undefined, so `j.conclusion ?? j.status`
580
- // would print the unreadable "job check is , not success" instead of
581
- // naming the job's actual status.
582
- test("in-progress job (conclusion \"\") not success: reason names the status, not an empty string", () => {
583
- const r = notGreen({ jobs: [{ name: "check", status: "in_progress", conclusion: "" }] });
584
- assert.equal(r.status, 1);
585
- assert.equal(r.payload.verdict, "not-green");
586
- assert.match(r.payload.reasons.join("; "), /job check is in_progress, not success/);
587
- });
588
-
589
- // The fifth reasons.push site in this arm — the one the "one negative case
590
- // each" comment above missed (#930). It fires before notGreen's override even
591
- // applies: matching.length === 0 short-circuits past the run-view read
592
- // entirely, so this needs the run LIST overridden, not the run VIEW —
593
- // notGreen only overrides the latter and cannot reach this branch at all.
594
- test("no run in the list matches the PR head at all: not-green, exit 1 — the unbound-PR case", () => {
595
- const [current] = JSON.parse(RUN_LIST);
596
- const r = run([], {
597
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
598
- runList: JSON.stringify([{ ...current, headSha: "0000000" }]),
599
- });
600
- assert.equal(r.status, 1);
601
- assert.equal(r.payload.verdict, "not-green");
602
- assert.match(r.payload.reasons.join("; "), /no CI run whose headSha equals the PR head abc123def/);
603
- });
604
-
605
- // --- Expected = H ∪ (D ∩ required): a PR may drop a job no rule requires ----
606
- // H is the head's CI job set, B the base's, D = B − H the jobs the PR drops.
607
- // The base here runs `check` and `integration`, the head only `check`, and the
608
- // run (the default fixture) carries `check` alone, succeeded — so whether
609
- // `integration` may be absent is decided by the base branch's rules alone.
610
- const DROPS_INTEGRATION = {
611
- baseFiles: { ".github/workflows/ci.yml": TWO_JOB_WORKFLOW },
612
- headFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
613
- };
614
- const RULES_READ = /^api repos\/\{owner\}\/\{repo\}\/rules\/branches\/main /m;
615
- const PROTECTION_READ = /^api repos\/\{owner\}\/\{repo\}\/branches\/main /m;
616
-
617
- test("a job the head drops and no rule requires: green, named in `dropped`, never in `missing`", () => {
618
- const r = run([], DROPS_INTEGRATION);
619
- assert.equal(r.status, 0, r.stdout + r.stderr);
620
- assert.equal(r.payload.verdict, "green");
621
- assert.deepEqual(r.payload.dropped, ["integration"]);
622
- assert.deepEqual(r.payload.missing, []);
623
- assert.match(r.log, RULES_READ, "an allowed drop has to be established against the rules, never assumed");
624
- assert.match(r.log, PROTECTION_READ);
625
- });
626
-
627
- for (const [authority, opts] of [
628
- ["a ruleset", { rules: ["check", "integration"] }],
629
- ["classic branch protection alone", { classic: ["integration"] }],
630
- ]) {
631
- test(`a job the head drops that ${authority} still requires: not-green, in \`missing\`, annotated`, () => {
632
- const r = run([], { ...DROPS_INTEGRATION, ...opts });
633
- assert.equal(r.status, 1, r.stdout + r.stderr);
634
- assert.equal(r.payload.verdict, "not-green");
635
- assert.deepEqual(r.payload.missing, ["integration"]);
636
- assert.deepEqual(r.payload.dropped, []);
637
- assert.match(r.payload.reasons.join("; "), /expected jobs absent from the run: integration \(dropped by the head's workflow, still required by the base ruleset\)/);
638
- });
639
- }
640
-
641
- // What the rule must ACCEPT: a required context is matched to a job id by
642
- // exact string, so a context that only resembles the dropped job — another
643
- // workflow's job, a display name — does not keep it expected.
644
- test("a required context that merely resembles the dropped job does not keep it expected", () => {
645
- const r = run([], { ...DROPS_INTEGRATION, rules: ["CI / integration", "Integration"], classic: ["integration-docker"] });
646
- assert.equal(r.status, 0, r.stdout + r.stderr);
647
- assert.deepEqual(r.payload.dropped, ["integration"]);
648
- });
649
-
650
- test("no dropped job absent from the run: the rules are never read", () => {
651
- for (const opts of [
652
- { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } },
653
- // The head drops `integration`, but the run reports it anyway — its own
654
- // conclusion is judged like any job's, so the rules cannot matter.
655
- { ...DROPS_INTEGRATION, runView: JSON.stringify({ ...JSON.parse(RUN_VIEW), jobs: [{ name: "check", status: "completed", conclusion: "success" }, { name: "integration", status: "completed", conclusion: "success" }] }) },
656
- ]) {
657
- const r = run([], { ...opts, rulesRaw: null, protectionRaw: null });
658
- assert.equal(r.status, 0, r.stdout + r.stderr);
659
- assert.deepEqual(r.payload.dropped, []);
660
- assert.doesNotMatch(r.log, RULES_READ);
661
- assert.doesNotMatch(r.log, PROTECTION_READ);
662
- }
663
- });
664
-
665
- test("a job the head adds and the run lacks is missing like any other, and reads no rules", () => {
666
- const r = run([], {
667
- baseFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
668
- headFiles: { ".github/workflows/ci.yml": TWO_JOB_WORKFLOW },
669
- rulesRaw: null,
670
- protectionRaw: null,
671
- });
672
- assert.equal(r.status, 1, r.stdout + r.stderr);
673
- assert.deepEqual(r.payload.missing, ["integration"]);
674
- assert.match(r.payload.reasons.join("; "), /expected jobs absent from the run: integration$|expected jobs absent from the run: integration;/);
675
- assert.doesNotMatch(r.log, RULES_READ);
676
- });
677
-
678
- // A head with no CI workflow contributes no jobs (H = ∅): every base job is a
679
- // drop, and the still-required ones stay expected. Removed outright and
680
- // renamed away (YAML present, none named CI) are both that case at the head,
681
- // where at the base the second one is a refusal.
682
- for (const [shape, headFiles] of [
683
- ["no CI workflow at all", {}],
684
- ["only workflows under other names", { ".github/workflows/release-label.yml": OTHER_WORKFLOW }],
685
- ]) {
686
- test(`a head with ${shape}: its still-required base jobs stay expected`, () => {
687
- const r = run([], { baseFiles: { ".github/workflows/ci.yml": TWO_JOB_WORKFLOW }, headFiles, rules: ["integration"] });
688
- assert.equal(r.status, 1, r.stdout + r.stderr);
689
- assert.deepEqual(r.payload.missing, ["integration"]);
690
- });
691
- }
692
-
693
- test("the base tree is the one at baseRefOid, never the base branch's newer tip", () => {
694
- // The tip has since gained `integration`, which the rules require; the
695
- // commit the PR is based on never had it. Judged against the tip, the PR
696
- // would "drop" a job it never had and read not-green.
697
- const r = run([], {
698
- baseTip: "ccc111ccc",
699
- tipFiles: { ".github/workflows/ci.yml": TWO_JOB_WORKFLOW },
700
- baseFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
701
- headFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
702
- rules: ["integration"],
703
- });
704
- assert.equal(r.status, 0, r.stdout + r.stderr);
705
- assert.equal(r.payload.verdict, "green");
706
- assert.match(r.log, /baseExpr=bbb000bbb/, "the base has to be read at baseRefOid itself");
707
- });
708
-
709
- test("a base branch that no longer exists still reads the base at baseRefOid", () => {
710
- const r = run([], {
711
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
712
- prView: JSON.stringify({ ...JSON.parse(PR_VIEW), baseRef: null }),
713
- });
714
- assert.equal(r.status, 0, r.stdout + r.stderr);
715
- assert.match(r.log, /baseExpr=bbb000bbb/);
716
- });
717
-
718
- // Every way the expected set's sources can fail to answer is exit 2 (or the
719
- // rate-limited payload) — never the base set alone, never green.
720
- for (const [what, opts, said] of [
721
- ["the head ref answering for another commit", { headOid: "fff999fff" }, /refs\/pull\/42\/head resolves to fff999fff, not the PR head abc123def/],
722
- ["the base read answering for another commit", { baseTip: "ccc111ccc", baseReadOid: "ddd222ddd" }, /base commit bbb000bbb reads back as ddd222ddd/],
723
- ["two head files sharing the CI name", { headFiles: { ".github/workflows/a.yml": CI_WORKFLOW, ".github/workflows/b.yml": CI_WORKFLOW } }, /2 workflow files under \.github\/workflows\/ at the head commit are named 'CI'/],
724
- ["a head CI blob truncated", { headFiles: { ".github/workflows/ci.yml": { truncated: true } } }, /cannot read \.github\/workflows\/ci\.yml at the head commit/],
725
- ["the PR read missing baseRefOid", { prView: JSON.stringify({ headRefName: BRANCH, headRefOid: PR_HEAD, baseRefName: "main" }) }, /baseRefOid \(the base sha\) is not a non-empty string \(the key is absent\)/],
726
- ["the ruleset read failing", { ...DROPS_INTEGRATION, rulesRaw: null }, /gh failed/],
727
- ["the classic protection read failing", { ...DROPS_INTEGRATION, protectionRaw: null }, /gh failed/],
728
- ["the ruleset read the wrong shape", { ...DROPS_INTEGRATION, rulesRaw: JSON.stringify([[{ type: "required_status_checks", parameters: {} }]]) }, /required_status_checks rule without a list of contexts/],
729
- ["the protection read without a protection object", { ...DROPS_INTEGRATION, protectionRaw: JSON.stringify({ name: "main" }) }, /protection object \(the key is absent\)/],
730
- ]) {
731
- test(`${what}: exit 2, never a verdict on the base set or green`, () => {
732
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW }, ...opts });
733
- assert.equal(r.status, 2, r.stdout + r.stderr);
734
- assert.match(r.stderr, said);
735
- assert.equal(r.payload, null);
736
- });
737
- }
738
-
739
- test("a quota refusal on the rules read is the rate-limited payload, naming that read", () => {
740
- const r = run([], { ...DROPS_INTEGRATION, rulesRaw: null, ghFailMsg: "API rate limit exceeded for user ID 1." });
741
- assert.equal(r.status, 2, r.stdout + r.stderr);
742
- assert.equal(r.payload.verdict, "rate-limited");
743
- assert.match(r.payload.reasons.join("; "), /gh api repos\/\{owner\}\/\{repo\}\/rules\/branches\/main/);
744
- });
745
-
746
- // --workflow-file names a repo-relative path read at both commits. Missing at
747
- // the base it refuses — an explicit target is never no-ci; missing at the head
748
- // it contributes no jobs, like any head without its CI workflow.
749
- test("--workflow-file absent at the base: exit 2 even under --declare-no-ci", () => {
750
- const r = run(["--workflow-file", ".github/workflows/ci.yml", "--declare-no-ci"], {
751
- baseFiles: { ".github/workflows/other.yml": CI_WORKFLOW },
752
- headFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
753
- });
754
- assert.equal(r.status, 2, r.stdout + r.stderr);
755
- assert.match(r.stderr, /\.github\/workflows\/ci\.yml does not exist at the base commit bbb000bbb/);
756
- });
757
-
758
- test("--workflow-file absent at the head: the head contributes no jobs and the drop rule decides", () => {
759
- const r = run(["--workflow-file", "./.github/workflows/ci.yml"], {
760
- baseFiles: { ".github/workflows/ci.yml": TWO_JOB_WORKFLOW },
761
- headFiles: { ".github/workflows/other.yml": CI_WORKFLOW },
762
- });
763
- assert.equal(r.status, 0, r.stdout + r.stderr);
764
- assert.deepEqual(r.payload.dropped, ["integration"]);
765
- });
766
-
767
- for (const bad of ["/abs/.github/workflows/ci.yml", ".github/../ci.yml", ".github/./ci.yml", "ci.yml", ".github/workflows/"]) {
768
- test(`--workflow-file ${bad}: refused before any read — not a repo-relative file path`, () => {
769
- const r = run(["--workflow-file", bad], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } });
770
- assert.equal(r.status, 2, r.stdout + r.stderr);
771
- assert.match(r.stderr, /--workflow-file takes a repo-relative path/);
772
- assert.equal(r.log, "");
773
- });
774
- }
775
-
776
- // --- #1410: two runs tied on head SHA AND createdAt to the second ----------
777
- // A stable sort with no tie-break keeps gh's own (unspecified) API order on
778
- // an exact createdAt tie. Measured live on PR #1402: two runs on the same
779
- // head, started the same second, one cancelled and one completed, both 6
780
- // jobs green — the tool bound to the cancelled duplicate. Recency (createdAt,
781
- // truncated to the second) stays the PRIMARY key; conclusion only breaks a
782
- // tie, so a newer in-progress run on an unrelated pair still beats an older
783
- // completed one (see the untied-path test below) — promoting conclusion to
784
- // primary would be a fresh regression, not a fix.
785
- //
786
- // Fixtures use gh's REAL run shape: a cancelled run reports
787
- // status:"completed", conclusion:"cancelled" — its LIFECYCLE (status) is
788
- // "completed", same as a successful run; only its OUTCOME (conclusion)
789
- // differs. A comparator ranking on status alone (an earlier draft of this
790
- // fix did exactly that) can never tell them apart, since both share
791
- // status:"completed" — the original #1402 bug would stay unfixed for real
792
- // GitHub data.
793
-
794
- test("two runs share head SHA and createdAt to the second, one cancelled one completed: the completed run wins and a tie-break note reaches stderr — PR #1402, cancelled listed first", () => {
795
- const createdAt = "2026-03-01T10:00:00Z";
796
- const cancelled = { databaseId: 2, headSha: PR_HEAD, status: "completed", conclusion: "cancelled", event: "pull_request", createdAt };
797
- const completed = { databaseId: 1, headSha: PR_HEAD, status: "completed", conclusion: "success", event: "pull_request", createdAt };
798
- const r = run([], {
799
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
800
- // Cancelled listed FIRST: with no tie-break, a stable sort on an exact
801
- // createdAt tie keeps this API order and picks it — the exact shape
802
- // measured on PR #1402.
803
- runList: JSON.stringify([cancelled, completed]),
804
- });
805
- assert.equal(r.status, 0, r.stdout + r.stderr);
806
- assert.equal(r.payload.verdict, "green");
807
- assert.equal(r.payload.runId, completed.databaseId, "must bind to the completed run, not the cancelled sibling sharing its head and createdAt");
808
- assert.match(r.log, new RegExp(`run view ${completed.databaseId}\\b`));
809
- assert.match(r.stderr, new RegExp(`run selection tie-break.*chose #${completed.databaseId} \\(completed/success\\) over #${cancelled.databaseId} \\(completed/cancelled\\)`));
810
- });
811
-
812
- test("two runs share head SHA and createdAt to the second, one cancelled one completed: the completed run wins regardless of array order — mirrored order", () => {
813
- const createdAt = "2026-03-01T10:00:00Z";
814
- const cancelled = { databaseId: 2, headSha: PR_HEAD, status: "completed", conclusion: "cancelled", event: "pull_request", createdAt };
815
- const completed = { databaseId: 1, headSha: PR_HEAD, status: "completed", conclusion: "success", event: "pull_request", createdAt };
816
- const r = run([], {
817
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
818
- // Completed listed FIRST this time. A stable sort would already pick it
819
- // by accident in this order alone, so this test never proves the
820
- // comparator does anything by itself — it only proves the reversed-order
821
- // test above isn't vacuously passing because of array order.
822
- runList: JSON.stringify([completed, cancelled]),
823
- });
824
- assert.equal(r.status, 0, r.stdout + r.stderr);
825
- assert.equal(r.payload.verdict, "green");
826
- assert.equal(r.payload.runId, completed.databaseId, "must bind to the completed run regardless of gh's response order");
827
- });
828
-
829
- test("two runs share head SHA, createdAt to the second, and conclusion rank: the numerically higher databaseId wins, not the lexicographically greater one", () => {
830
- const createdAt = "2026-03-01T10:00:00Z";
831
- // databaseId 9 and 10: "9" sorts ahead of "10" under a STRING compare
832
- // (localeCompare), backwards from the numerically higher/newer id. Listed
833
- // with the lexicographically-winning id first so a lingering string
834
- // compare would pick it by accident too.
835
- const lowerId = { databaseId: 9, headSha: PR_HEAD, status: "completed", conclusion: "success", event: "pull_request", createdAt };
836
- const higherId = { databaseId: 10, headSha: PR_HEAD, status: "completed", conclusion: "success", event: "pull_request", createdAt };
837
- const r = run([], {
838
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
839
- runList: JSON.stringify([lowerId, higherId]),
840
- });
841
- assert.equal(r.status, 0, r.stdout + r.stderr);
842
- assert.equal(r.payload.verdict, "green");
843
- assert.equal(r.payload.runId, higherId.databaseId, "the numerically higher databaseId must win the final tie-break, not the lexicographically greater one");
844
- assert.match(r.stderr, new RegExp(`run selection tie-break.*chose #${higherId.databaseId} \\(completed/success\\) over #${lowerId.databaseId} \\(completed/success\\)`));
845
- });
846
-
847
- test("two runs' createdAt differs only in the fractional-second component: still treated as a tie, not two distinct instants", () => {
848
- // GitHub's createdAt is documented as whole-second precision, but the
849
- // comparator truncates via bySecond() defensively. If the comparator
850
- // instead compared full-precision strings, these two would never be
851
- // grouped as tied — the cancelled run's fractionally-LATER createdAt would
852
- // win on recency alone, and conclusion would never even be consulted.
853
- const cancelled = { databaseId: 2, headSha: PR_HEAD, status: "completed", conclusion: "cancelled", event: "pull_request", createdAt: "2026-03-01T10:00:00.900Z" };
854
- const completed = { databaseId: 1, headSha: PR_HEAD, status: "completed", conclusion: "success", event: "pull_request", createdAt: "2026-03-01T10:00:00.100Z" };
855
- const r = run([], {
856
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
857
- runList: JSON.stringify([cancelled, completed]),
858
- });
859
- assert.equal(r.status, 0, r.stdout + r.stderr);
860
- assert.equal(r.payload.verdict, "green");
861
- assert.equal(r.payload.runId, completed.databaseId, "sub-second createdAt drift must not hide a genuine tie; conclusion still decides");
862
- assert.match(r.stderr, /run selection tie-break/);
863
- });
864
-
865
- test("untied path: a newer non-completed run still beats an older completed one on the same head — conclusion never outranks recency", () => {
866
- const older = { databaseId: 5, headSha: PR_HEAD, status: "completed", conclusion: "success", event: "pull_request", createdAt: "2026-01-01T00:00:00Z" };
867
- const newer = { databaseId: 6, headSha: PR_HEAD, status: "in_progress", conclusion: null, event: "pull_request", createdAt: "2026-01-02T00:00:00Z" };
868
- const r = run([], {
869
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
870
- runList: JSON.stringify([older, newer]),
871
- runView: JSON.stringify({ jobs: [{ name: "check", status: "in_progress", conclusion: null }], attempt: 1, status: "in_progress", conclusion: null, headSha: PR_HEAD }),
872
- });
873
- assert.equal(r.status, 1);
874
- assert.equal(r.payload.verdict, "not-green");
875
- assert.equal(r.payload.runId, newer.databaseId, "recency stays primary: a newer in-progress run must still beat an older completed one when createdAt is NOT tied");
876
- assert.doesNotMatch(r.stderr, /run selection tie-break/, "createdAt differs here, so no tie-break note should fire");
877
- });
878
-
879
- // --- #1566: rank()'s middle tier must match live gh data --------------------
880
- // `gh run list --json conclusion` reports an empty string `""` for a
881
- // non-completed run, never `null`. An earlier version of rank()'s middle
882
- // tier required `r.conclusion === null`, so it silently never matched real
883
- // data and a still-running run fell into the SAME bottom tier as a
884
- // failed/cancelled one, losing an exact-createdAt tie it should win.
885
- test("two runs share head SHA and createdAt to the second, one in-progress (conclusion \"\") one cancelled: the in-progress run wins the tie-break, not the cancelled one", () => {
886
- const createdAt = "2026-03-01T10:00:00Z";
887
- // In-progress listed with the LOWER databaseId: under the pre-fix bug both
888
- // runs fall to the bottom tier (conclusion:"" never matches `=== null`),
889
- // so the final databaseId tie-break picks the cancelled run (higher id) —
890
- // the wrong winner. Only the fixed middle tier makes the in-progress run
891
- // win despite its lower id.
892
- const inProgress = { databaseId: 1, headSha: PR_HEAD, status: "in_progress", conclusion: "", event: "pull_request", createdAt };
893
- const cancelled = { databaseId: 2, headSha: PR_HEAD, status: "completed", conclusion: "cancelled", event: "pull_request", createdAt };
894
- const r = run([], {
895
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
896
- runList: JSON.stringify([cancelled, inProgress]),
897
- runView: JSON.stringify({ jobs: [{ name: "check", status: "in_progress", conclusion: "" }], attempt: 1, status: "in_progress", conclusion: "", headSha: PR_HEAD }),
898
- });
899
- assert.equal(r.status, 1);
900
- assert.equal(r.payload.verdict, "not-green");
901
- assert.equal(r.payload.runId, inProgress.databaseId, "still-running (conclusion \"\") must outrank a settled cancelled run in the tie-break, not lose to it on databaseId");
902
- assert.match(r.stderr, new RegExp(`run selection tie-break.*chose #${inProgress.databaseId} \\(in_progress/\\) over #${cancelled.databaseId} \\(completed/cancelled\\)`));
903
- });
904
-
905
- // --- #169: a flag given with no value must die, never read as absent -------
906
- // `base`/`workflow`/`workflow-file` all read via `arg(name) || default`, so a
907
- // trailing flag previously fell straight through to the DEFAULT — the caller
908
- // asked to gate on a specific base/workflow and silently got a real verdict
909
- // against the wrong one instead of a refusal. Pinned as the priority site
910
- // (feigi's PR #167 review comment): `ci-state.mjs --pr 5 --base` used to
911
- // compare against `main` with no signal anything was wrong.
912
-
913
- test("trailing --base (no value) dies (exit 2) rather than silently comparing against the default base", () => {
914
- const r = run(["--base"]);
915
- assert.equal(r.status, 2);
916
- assert.match(r.stderr, /--base needs a value/);
917
- assert.equal(r.log, "", "must die before ever asking gh anything");
918
- });
919
-
920
- test("--workflow=CI form dies by name, not silently read as absent (indexOf cannot see it)", () => {
921
- const r = run(["--workflow=CI"]);
922
- assert.equal(r.status, 2);
923
- assert.match(r.stderr, /--workflow needs a space-separated value/);
924
- });
925
-
926
- // #364: has() used exact argv.includes, so a boolean flag written --name=value
927
- // (in ANY form the value takes) silently read as absent — dropping the
928
- // caller's declared no-CI opt-out with no signal. The wording has to say
929
- // "boolean flag", distinct from arg()'s "needs a space-separated value" above:
930
- // a boolean has no value to give in the first place.
931
- for (const flag of ["declare-no-ci", "quiet"]) {
932
- for (const v of ["=true", "=false", "="]) {
933
- test(`--${flag}${v} dies as a boolean flag, never silently read as absent`, () => {
934
- const r = run([`--${flag}${v}`]);
935
- assert.equal(r.status, 2);
936
- assert.match(r.stderr, new RegExp(`--${flag} is a boolean flag, not --${flag}=`));
937
- assert.equal(r.log, "", "must die before ever asking gh anything");
938
- });
939
- }
940
- }
941
-
942
- // Position, not just spelling — and run()'s fixed `--pr 42` prepend does NOT
943
- // supply it: a fixed prepend gives a FIXED offset, so all six cases in the
944
- // loop above land their flag at process.argv[4] and a guard narrowed to that
945
- // one index passes every one of them. Robustness needs the flag at DIFFERENT offsets across
946
- // cases (#462 review); this is the only case that supplies one. --declare-no-ci
947
- // is the flag worth spending it on: read as absent, it drops the caller's
948
- // opt-out and the gate answers on a suite nobody ran.
949
- test("--declare-no-ci=true dies behind another flag too, not only at the front of argv", () => {
950
- const r = run(["--quiet", "--declare-no-ci=true"]);
951
- assert.equal(r.status, 2);
952
- assert.match(r.stderr, /--declare-no-ci is a boolean flag, not --declare-no-ci=/);
953
- assert.equal(r.log, "", "must die before ever asking gh anything");
954
- });
955
-
956
- // The control: the new `=` guard must not touch the bare spelling. --quiet's
957
- // STDERR effect is what pins it here (--declare-no-ci's bare form is already
958
- // pinned above, by its effect on verdict/exit code): vlog's command echoes
959
- // vanish from stderr, though the same gh calls still ran (r.log is written by
960
- // the stub itself, unconditionally). Its PAYLOAD effect is the next test's.
961
- test("--quiet still reads as present in its bare spelling — the = refusal is not a blanket one", () => {
962
- const loud = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } });
963
- assert.equal(loud.status, 0, loud.stdout + loud.stderr);
964
- assert.match(loud.stderr, /\$ gh api graphql/);
965
-
966
- const quiet = run(["--quiet"], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } });
967
- assert.equal(quiet.status, 0, quiet.stdout + quiet.stderr);
968
- assert.doesNotMatch(quiet.stderr, /\$ gh api graphql/);
969
- assert.match(quiet.log, /api graphql/, "gh still ran despite the quieter stderr");
970
- });
971
-
972
- // #677. The other half of what `--quiet` does, and the half the flag exists for:
973
- // `jobs`, `missing` and `dropped` leave the JSON payload with it and are present without
974
- // it. Same fixture both ways, so the flag is the only difference. The field
975
- // names are spelled out rather than derived from ci-state.mjs — deriving them
976
- // from the assignment under test would make this pass vacuously if that
977
- // assignment changed, which is the one thing it must not do. The deriving is
978
- // `quiet-payload-prose.test.mjs`'s job, over the prose that has to agree.
979
- test("--quiet drops `jobs`, `missing` and `dropped` from the payload; without it they are there", () => {
980
- const opts = { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } };
981
- const loud = run([], opts);
982
- const quiet = run(["--quiet"], opts);
983
- assert.equal(loud.status, 0, loud.stdout + loud.stderr);
984
- assert.equal(quiet.status, 0, quiet.stdout + quiet.stderr);
985
- for (const field of ["jobs", "missing", "dropped"]) {
986
- assert.ok(field in loud.payload, `without --quiet the payload must carry \`${field}\`, and it reads ${JSON.stringify(loud.payload)}`);
987
- assert.ok(!(field in quiet.payload), `--quiet must drop \`${field}\` from the payload, and it reads ${JSON.stringify(quiet.payload)}`);
988
- }
989
- });
990
-
991
- test("trailing --pr (no value, the entry flag itself) still dies naming the flag", () => {
992
- const r = spawnSync(process.execPath, [SCRIPT, "--pr"], { encoding: "utf8" });
993
- assert.equal(r.status, 2);
994
- assert.match(r.stderr, /--pr needs a value/);
995
- });
996
-
997
- // The other two branches of the same guard: a flag eating the NEXT FLAG as its
998
- // value, and an explicit whitespace-only value. Deleting either clause from
999
- // arg() left this suite 18/18 green before these two existed.
1000
- test("--base followed by another flag is rejected, not read as the string \"--workflow\"", () => {
1001
- const r = run(["--base", "--workflow", "CI"]);
1002
- assert.equal(r.status, 2);
1003
- assert.match(r.stderr, /--base needs a value/);
1004
- assert.equal(r.log, "", "must die before ever asking gh anything");
1005
- });
1006
-
1007
- // #463 fallout: `--workflow-file` is the one flag this file used to read below
1008
- // its guards, in discoverWorkflowFile()'s caller. With the read there, this
1009
- // invocation refused with `unexpected argument 'main'` — --base's innocent
1010
- // value — instead of naming the flag given wrong (measured). The read is a
1011
- // statement above sweep() for that reason; putting it back reds this.
1012
- test("trailing --workflow-file names --workflow-file, not the innocent value of the flag behind it", () => {
1013
- const r = run(["--workflow-file", "--base", "main"]);
1014
- assert.equal(r.status, 2);
1015
- assert.match(r.stderr, /--workflow-file needs a value/);
1016
- assert.equal(r.log, "", "must die before ever asking gh anything");
1017
- });
1018
-
1019
- test("--base given a whitespace-only value dies rather than comparing against the default base", () => {
1020
- const r = run(["--base", " "]);
1021
- assert.equal(r.status, 2);
1022
- assert.match(r.stderr, /--base needs a value/);
1023
- });
1024
-
1025
- // --- #269: parsing a gh reply is not the same as it being the right shape --
1026
- // A reply that parses cleanly but is the wrong shape (an error object where
1027
- // an array is expected, a run view missing its jobs) previously flowed on
1028
- // unchecked until the first dereference threw — and an uncaught throw exits
1029
- // 1, this script's code for "not bound-green". Each case below pins the
1030
- // class: exit 2, naming the query and the field, before the crash site is
1031
- // ever reached. #232's caution is why the row-level cases exist too — a
1032
- // guard that checks the array but not its elements is itself a partial
1033
- // guard, and jobs/runs rows are read (`j.name`, `r.headSha`) unguarded.
1034
-
1035
- // Every assertion in this section is about the REFUSAL LINE, not about stderr
1036
- // as a whole: the diagnostic stream echoes each gh command before running it,
1037
- // and that echo carries `api graphql`, `run view` and every field name the
1038
- // query asks for — `$ gh api graphql … headRefName headRefOid baseRefName …`
1039
- // (measured). `assert.match(r.stderr, /headRefName/)` is therefore satisfied
1040
- // by a refusal that names nothing at all, which leaves the exit status as the
1041
- // only load-bearing half of such a case. Asserting on the line itself is what
1042
- // makes the field name — and, for #926, what the line says gh actually SENT —
1043
- // load-bearing.
1044
- const refusal = (r) => r.stderr.split("\n").find((l) => l.includes("not the expected shape")) ?? "";
1045
-
1046
- // #926. Each of these guards covers three distinct faults — the key absent,
1047
- // the value an empty string, the value not a string — and "missing <field>"
1048
- // asserted absence for all of them: measured, `{"headRefName":""}`,
1049
- // `{"headRefName":42}` and the key omitted printed one identical line, so a
1050
- // reader hunted for a key gh had in fact returned as `""`, `42` or `null`.
1051
- // Each row pins its own fault's rendering AND that the line does not tell
1052
- // another fault's story: a present value is never reported as an absent key,
1053
- // and an absent key never quotes a value nothing sent.
1054
- //
1055
- // The clause-level reachability these rows also carry: an empty string
1056
- // satisfies the type check and a number satisfies the emptiness check, so
1057
- // those rows are what keep each clause from being deletable. The absent rows
1058
- // are refused by both clauses at once and so pin neither — they are here for
1059
- // what the line SAYS, which is this ticket. What a lost clause costs is the
1060
- // field flowing on: `branch` becomes the empty string or a number and
1061
- // `gh run list --branch` asks for the wrong branch, while `prHead` becomes a
1062
- // value no run's headSha can equal, which reads as the superseded-SHA case
1063
- // rather than as a reply that could not be trusted.
1064
- for (const [what, field, prFields, saw, notSaw] of [
1065
- ["an absent branch name", "headRefName", { headRefOid: PR_HEAD }, /the key is absent/, /got /],
1066
- ["an empty branch name", "headRefName", { headRefName: "", headRefOid: PR_HEAD }, /got ""/, /absent/],
1067
- ["a non-string branch name", "headRefName", { headRefName: 42, headRefOid: PR_HEAD }, /got 42/, /absent/],
1068
- ["a null branch name", "headRefName", { headRefName: null, headRefOid: PR_HEAD }, /got null/, /absent/],
1069
- ["an absent head sha", "headRefOid", { headRefName: BRANCH }, /the key is absent/, /got /],
1070
- ["an empty head sha", "headRefOid", { headRefName: BRANCH, headRefOid: "" }, /got ""/, /absent/],
1071
- ["a non-string head sha", "headRefOid", { headRefName: BRANCH, headRefOid: 42 }, /got 42/, /absent/],
1072
- ["a null head sha", "headRefOid", { headRefName: BRANCH, headRefOid: null }, /got null/, /absent/],
1073
- ]) {
1074
- test(`PR info carrying ${what}: exit 2 naming the field and what gh sent, never a verdict built on it`, () => {
1075
- const r = run([], {
1076
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1077
- prView: JSON.stringify({ state: "OPEN", mergeStateStatus: "CLEAN", ...prFields }),
1078
- });
1079
- assert.equal(r.status, 2, r.stdout + r.stderr);
1080
- assert.match(r.stderr, /api graphql/);
1081
- assert.match(refusal(r), new RegExp(field));
1082
- assert.match(refusal(r), saw);
1083
- assert.doesNotMatch(refusal(r), notSaw);
1084
- assert.doesNotMatch(r.log, /run list/, "must die before ever asking gh for runs");
1085
- });
1086
- }
1087
-
1088
- test("run list returns an error object, not an array: exit 2, never the crash from runs.filter", () => {
1089
- // The ticket's own reproduction: gh exits 0 printing an error body where
1090
- // --json databaseId,headSha,... normally produces an array.
1091
- const r = run([], {
1092
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1093
- runList: JSON.stringify({ error: "rate limited" }),
1094
- });
1095
- assert.equal(r.status, 2, r.stdout + r.stderr);
1096
- assert.match(r.stderr, /run list/);
1097
- assert.match(r.stderr, /expected an array of runs/);
1098
- });
1099
-
1100
- test("run list row is null: exit 2, never the crash reading r.headSha off null", () => {
1101
- const r = run([], {
1102
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1103
- runList: JSON.stringify([null]),
1104
- });
1105
- assert.equal(r.status, 2, r.stdout + r.stderr);
1106
- assert.match(r.stderr, /run list row 0 is not an object/);
1107
- });
1108
-
1109
- // The same #926 split at the run-view guard, whose faults are two rather than
1110
- // three: the `jobs` key absent, and a `jobs` present but not an array.
1111
- // "missing jobs array" asserted the first for both of them (measured), and the
1112
- // second is the shape an error body or a partial run view takes — the value is
1113
- // right there to be quoted. `absent` stays a row of its own because it is the
1114
- // shape this guard was added for: it is the only thing between a missing key
1115
- // and `view.jobs.map(...)`, and an uncaught throw there exits 1 — "could not
1116
- // be read" rendered as a CI verdict, the whole #269 class.
1117
- for (const [what, runFields, saw, notSaw] of [
1118
- ["absent", {}, /the key is absent/, /got /],
1119
- ["an error object", { jobs: { error: "rate limited" } }, /got \{"error":"rate limited"\}/, /absent/],
1120
- ["a string", { jobs: "none" }, /got "none"/, /absent/],
1121
- ["null", { jobs: null }, /got null/, /absent/],
1122
- ]) {
1123
- test(`run view whose jobs is ${what}: exit 2 naming the field and what gh sent, never read as zero jobs`, () => {
1124
- const r = run([], {
1125
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1126
- runView: JSON.stringify({ attempt: 1, status: "completed", conclusion: "success", headSha: PR_HEAD, ...runFields }),
1127
- });
1128
- assert.equal(r.status, 2, r.stdout + r.stderr);
1129
- assert.match(refusal(r), /run view/);
1130
- assert.match(refusal(r), /jobs/);
1131
- assert.match(refusal(r), saw);
1132
- assert.doesNotMatch(refusal(r), notSaw);
1133
- });
1134
- }
1135
-
1136
- // #926's own new hazard: the value a refusal quotes is gh's, so its length is
1137
- // gh's too — a `jobs` that came back as an error body carries however much
1138
- // text that body had, onto a stderr the fleet's CI monitor polls. So it is
1139
- // cut short, and says that it was: a tail dropped with no marker reads as the
1140
- // whole value, the same class of lie "missing" was. Asserted against whether
1141
- // the value's own unbroken run survives the cut, not against the cap's
1142
- // number, so tuning the cap does not red this — a smaller cap only cuts the
1143
- // run shorter, it does not make it survive.
1144
- test("a refusal quoting an unbounded value is cut short and says that it was", () => {
1145
- const huge = "x".repeat(400);
1146
- const r = run([], {
1147
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1148
- runView: JSON.stringify({ jobs: { error: huge }, attempt: 1, status: "completed", conclusion: "success", headSha: PR_HEAD }),
1149
- });
1150
- assert.equal(r.status, 2, r.stdout + r.stderr);
1151
- assert.match(refusal(r), /jobs/);
1152
- assert.match(refusal(r), /\(truncated\)/);
1153
- assert.doesNotMatch(
1154
- refusal(r),
1155
- /x{400}/,
1156
- `the refusal must not carry the whole value, and it reads ${refusal(r)}`,
1157
- );
1158
- });
1159
-
1160
- // The direction this guard gets wrong on its own: what it wrongly REFUSES.
1161
- // Every jobs fixture above is malformed by construction, so none of them can
1162
- // show that the legitimate empty reply still reaches a verdict — and an empty
1163
- // `jobs` is legitimate: the guard's whole question is array-ness, a run with
1164
- // no job rows answers it, and the job-presence check below is what has an
1165
- // opinion about how many. A guard tightened from "is an array" onto
1166
- // truthiness or length would refuse it, and refusing a working invocation
1167
- // costs more than any diagnostic above gains. The verdict it must reach is
1168
- // not-green, by that job-presence check rather than by the shape check —
1169
- // which is also where the word "absent" belongs: about a job expected and
1170
- // missing from the run, never about a key gh did send.
1171
- test("run view whose jobs is an empty array is accepted — a verdict, never a shape refusal", () => {
1172
- const r = run([], {
1173
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1174
- runView: JSON.stringify({ jobs: [], attempt: 1, status: "completed", conclusion: "success", headSha: PR_HEAD }),
1175
- });
1176
- assert.equal(r.status, 1, r.stdout + r.stderr);
1177
- assert.equal(r.payload.verdict, "not-green");
1178
- assert.doesNotMatch(r.stderr, /not the expected shape/);
1179
- assert.match(r.stderr, /expected jobs absent from the run: check/);
1180
- });
1181
-
1182
- test("a job entry in the run view is null: exit 2, never the crash reading j.name off null", () => {
1183
- const r = run([], {
1184
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1185
- runView: JSON.stringify({ jobs: [null], attempt: 1, status: "completed", conclusion: "success", headSha: PR_HEAD }),
1186
- });
1187
- assert.equal(r.status, 2, r.stdout + r.stderr);
1188
- assert.match(r.stderr, /job entry 0 is not an object/);
1189
- });
1190
-
1191
- // The refusal names a POSITION, and a fixture whose malformed element sits
1192
- // first is satisfied by a guard that only answers "is one of them bad". Each
1193
- // site carries a well-formed element ahead of the bad one so the reported
1194
- // index has to be derived rather than guessed. Nothing reads the index today;
1195
- // it is the diagnostic a human gets for a reply gh really sent, so being wrong
1196
- // about which element was malformed sends them to the wrong one.
1197
- test("a run list row after a well-formed one is malformed: the refusal names that row's position", () => {
1198
- const [current] = JSON.parse(RUN_LIST);
1199
- const r = run([], {
1200
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1201
- runList: JSON.stringify([current, null]),
1202
- });
1203
- assert.equal(r.status, 2, r.stdout + r.stderr);
1204
- assert.match(r.stderr, /run list row 1 is not an object/);
1205
- });
1206
-
1207
- test("a job entry after a well-formed one is malformed: the refusal names that entry's position", () => {
1208
- const view = JSON.parse(RUN_VIEW);
1209
- const r = run([], {
1210
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1211
- runView: JSON.stringify({ ...view, jobs: [...view.jobs, null] }),
1212
- });
1213
- assert.equal(r.status, 2, r.stdout + r.stderr);
1214
- assert.match(r.stderr, /job entry 1 is not an object/);
1215
- });
1216
-
1217
- // The direction these guards get wrong on their own: what they wrongly REFUSE.
1218
- // Every fixture above is malformed by construction, so none of them can show
1219
- // that a well-formed reply carrying more than one row still reaches a verdict
1220
- // — and more than one row is the shape gh returns for any branch with a run
1221
- // history, the normal case rather than an edge one. A guard tightened past it
1222
- // refuses a working invocation, which costs more than the diagnostic above.
1223
- test("a run list whose rows are all well-formed still reaches a verdict, superseded rows included", () => {
1224
- const [current] = JSON.parse(RUN_LIST);
1225
- const r = run([], {
1226
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1227
- runList: JSON.stringify([
1228
- { ...current, databaseId: 2, headSha: "0000000", createdAt: "2025-12-31T00:00:00Z" },
1229
- current,
1230
- ]),
1231
- });
1232
- assert.equal(r.status, 0, r.stdout + r.stderr);
1233
- assert.equal(r.payload.verdict, "green");
1234
- });
1235
-
1236
- // isObject is the whole refusal at the row and job level, so each of its
1237
- // clauses is load-bearing alone — at both sites, which take the same two shapes
1238
- // here. Every other malformed row and job fixture in this file is `null`, which
1239
- // the null clause already refuses on its own; an array and a scalar are what
1240
- // separate the other two clauses from decoration. Both degrade quietly rather
1241
- // than crashing, which is why they need pinning: either one yields `undefined`
1242
- // for every field read off it, so the run reports runs and jobs it never saw
1243
- // instead of refusing the reply.
1244
- for (const [what, malformed] of [
1245
- ["an array", []],
1246
- ["a scalar", "check"],
1247
- ]) {
1248
- test(`a job entry that is ${what}: exit 2, never read as a job with no fields`, () => {
1249
- const r = run([], {
1250
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1251
- runView: JSON.stringify({ jobs: [malformed], attempt: 1, status: "completed", conclusion: "success", headSha: PR_HEAD }),
1252
- });
1253
- assert.equal(r.status, 2, r.stdout + r.stderr);
1254
- assert.match(r.stderr, /job entry 0 is not an object/);
1255
- });
1256
-
1257
- test(`a run list row that is ${what}: exit 2, never read as a run with no fields`, () => {
1258
- const r = run([], {
1259
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1260
- runList: JSON.stringify([malformed]),
1261
- });
1262
- assert.equal(r.status, 2, r.stdout + r.stderr);
1263
- assert.match(r.stderr, /run list row 0 is not an object/);
1264
- });
1265
- }
1266
-
1267
- // The false-positive class the guard must NOT create: an in-progress job's
1268
- // `conclusion` is legitimately `null`, not a missing/wrong-shaped field. If
1269
- // the shape check validated field types instead of just object-ness, this
1270
- // well-formed reply would itself start being refused.
1271
- test("in-progress job with conclusion:null is accepted — not refused as malformed shape", () => {
1272
- const r = run([], {
1273
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1274
- runView: JSON.stringify({
1275
- jobs: [{ name: "check", status: "in_progress", conclusion: null }],
1276
- attempt: 1,
1277
- status: "in_progress",
1278
- conclusion: null,
1279
- headSha: PR_HEAD,
1280
- }),
1281
- });
1282
- assert.equal(r.status, 1, r.stdout + r.stderr); // not-green (still running) — never exit 2
1283
- assert.equal(r.payload.verdict, "not-green");
1284
- assert.doesNotMatch(r.stderr, /not the expected shape/);
1285
- });
1286
-
1287
- // #365's other half. The sweep refuses any `--` token not in this script's
1288
- // known set, so a name missing from that set refuses an invocation this script
1289
- // accepts — "worse than the bug" by the ticket's own words. Measured, dropping
1290
- // `base` or `workflow` reddens THIS test and nothing else; the other four names
1291
- // also redden tests above, which happen to pass them.
1292
- //
1293
- // So: every flag ci-state.mjs accepts, in ONE green run. --workflow-file is the
1294
- // one that would not otherwise be here, because its value is first needed far
1295
- // below the sweep, where the workflow trees are read — the sweep needs the
1296
- // NAME, and a set built by reading down to the first gh call would miss it.
1297
- //
1298
- // A repo-relative path: the script reads it at the PR's head and base
1299
- // commits, which run() serves from the same files.
1300
- test("every flag ci-state.mjs accepts survives the unknown-flag sweep in one invocation", () => {
1301
- const r = run(["--base", "main", "--workflow", "CI", "--workflow-file", ".github/workflows/ci.yml", "--declare-no-ci", "--quiet"], {
1302
- repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW },
1303
- });
1304
- assert.equal(r.status, 0, `a working invocation was refused: ${r.stderr}`);
1305
- // Live, not subsumed by the status assertion above: the behind-count block
1306
- // TOLERATES its child — tryRun() swallows the failure and returns null
1307
- // while execFileSync has already forwarded the child's stderr — so a child
1308
- // refusing a flag lands here at exit 0 with `behind` silently null.
1309
- assert.doesNotMatch(r.stderr, /unknown (flag|option)/);
1310
- assert.equal(r.payload.verdict, "green");
1311
- });
1312
-
1313
- // --- #262: a quota refusal is a distinguishable cause, not a generic failure -
1314
- // Every `gh` read failure landed on one arm that reported the exit code and
1315
- // nothing a caller could act on — an exhausted REST quota, a repo that cannot
1316
- // be resolved and a revoked token were one undifferentiated cause. The correct
1317
- // responses differ: a quota refusal recovers on its own and is worth re-probing
1318
- // shortly, the others need someone to look, so the cause is named in the
1319
- // PAYLOAD. That is where the fleet's gates read this script — `merge-gate.mjs`
1320
- // gates every merge on the payload's own fields, and an empty payload, which is
1321
- // all this arm produced, is `ci-unreadable` there: a probe that could not look,
1322
- // never a reading about the PR.
1323
- //
1324
- // No test reached this arm before: every other exit-2 case here dies in
1325
- // workflow discovery or in a shape check, never in the subprocess failure path.
1326
- // `$GH_FAIL_MSG` is what makes the two causes drivable, and the pair below is
1327
- // the point — either test alone passes a script that ignores the cause entirely.
1328
-
1329
- // The quota refusal as `gh` actually words it, wrapping the REST body.
1330
- const RATE_LIMIT_STDERR =
1331
- "couldn't fetch workflows for feigi/claude-config: HTTP 403: API rate limit exceeded for user ID 1234.";
1332
- // A failure that is NOT a quota refusal and never recovers by waiting.
1333
- const MISSING_REPO_STDERR = "could not resolve to a Repository with the name 'feigi/nope'";
1334
-
1335
- const ghFailure = (ghFailMsg) =>
1336
- run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW }, runList: null, ghFailMsg });
1337
-
1338
- test("a rate-limited gh read names the quota as its cause in the payload, at the unchanged exit 2", () => {
1339
- const r = ghFailure(RATE_LIMIT_STDERR);
1340
- assert.equal(r.status, 2, r.stdout + r.stderr);
1341
- assert.ok(r.payload, "a quota refusal must emit a payload — the cause is unreadable to a gate that only sees stderr");
1342
- assert.equal(r.payload.verdict, "rate-limited");
1343
- assert.match(r.payload.reasons.join("; "), /rate limit/i);
1344
- // `pr` is the payload's only identifying field, and the fleet polls this
1345
- // script for several PRs at once — an outage attributed to the wrong one, or
1346
- // carrying a string where every other payload here carries a number, is
1347
- // indistinguishable from a correct report at the point a caller reads it.
1348
- // assert/strict, so this pins the type as well as the value.
1349
- assert.equal(r.payload.pr, 42);
1350
- // The refused query, not merely that a quota was mentioned: the PR read is
1351
- // GraphQL and `run list`/`run view` are REST, so which one was refused is
1352
- // what separates an exhausted REST quota from a token or repo problem. The
1353
- // fixture refuses `run list` — keep this literal in step with it.
1354
- assert.match(r.payload.reasons.join("; "), /gh run list/);
1355
- });
1356
-
1357
- // GitHub's older spelling of the same self-clearing secondary limit, still
1358
- // emitted by a GHE Server predating the rename. Without this the alternation in
1359
- // RATE_LIMITED is unpinned: dropping it leaves every test above green, because
1360
- // they all drive the current wording.
1361
- const LEGACY_ABUSE_STDERR =
1362
- "HTTP 403: You have triggered an abuse detection mechanism. Please wait a few minutes before you try again.";
1363
-
1364
- test("the pre-rename secondary-limit wording is read as a quota refusal too", () => {
1365
- const r = ghFailure(LEGACY_ABUSE_STDERR);
1366
- assert.equal(r.status, 2, r.stdout + r.stderr);
1367
- assert.ok(r.payload, "the abuse-detection spelling is the same self-clearing limit under its old name");
1368
- assert.equal(r.payload.verdict, "rate-limited");
1369
- });
1370
-
1371
- // The bound on that alternation: `abuse` alone appears in refusals no wait
1372
- // clears, so matching the short form would tell a caller to re-probe a
1373
- // repository that has been disabled outright.
1374
- const DISABLED_REPO_STDERR =
1375
- "HTTP 403: Repository access blocked. This repository has been disabled for abuse of GitHub's terms of service.";
1376
-
1377
- test("a repository disabled for abuse is NOT a quota refusal", () => {
1378
- const r = ghFailure(DISABLED_REPO_STDERR);
1379
- assert.equal(r.status, 2, r.stdout + r.stderr);
1380
- assert.equal(r.payload, null, "a permanent block must not be reported as an outage that clears on its own");
1381
- });
1382
-
1383
- test("a gh read failing for any other reason reports exactly as it did before: exit 2, no payload", () => {
1384
- const r = ghFailure(MISSING_REPO_STDERR);
1385
- assert.equal(r.status, 2, r.stdout + r.stderr);
1386
- assert.equal(r.payload, null, "only a quota refusal earns a payload; every other cause is unchanged");
1387
- assert.match(r.stderr, /gh failed/);
1388
- });
1389
-
1390
- // The outage payload must not be mistaken for a reading. A quota refusal is a
1391
- // probe that could not look, so it reports no CI state at all. Emitting these
1392
- // as nulls or empty arrays would let unobserved state read as observed: an
1393
- // empty `missing` says "nothing is missing", which is a reading, where an
1394
- // absent one is what `merge-gate.mjs`, which gates every merge on this
1395
- // payload's own fields, reads as a probe that could not look rather than as
1396
- // observed state.
1397
- test("the outage payload reports no CI state it could not observe", () => {
1398
- const r = ghFailure(RATE_LIMIT_STDERR);
1399
- for (const field of ["status", "conclusion", "jobs", "missing", "dropped", "runId"]) {
1400
- assert.ok(
1401
- !(field in r.payload),
1402
- `a probe that never read CI must not report \`${field}\`, and the payload reads ${JSON.stringify(r.payload)}`,
1403
- );
1404
- }
1405
- });
1406
-
1407
- // #927: `jobs`/`missing` used to ship as `[]` on the no-ci arm too — module
1408
- // scope initialises `let jobs = []`/`let missing = []` and the no-ci branch
1409
- // never reaches the run-binding code that reassigns them, so every no-ci
1410
- // payload carried them empty. An empty `missing` is a READING — "nothing is
1411
- // missing" — and no-ci never took a reading: there was no workflow file to
1412
- // derive an expected-job set from, let alone a run to check it against.
1413
- // `emitRateLimited()` above already answers the identical "nothing was read"
1414
- // question by omitting `jobs`/`missing` rather than shipping them empty —
1415
- // covered by "the outage payload reports no CI state it could not observe"
1416
- // above, which this test does not duplicate — and this pins that the no-ci
1417
- // arm now answers it the same way.
1418
- test("a payload for a question never asked — no-ci — omits `jobs`/`missing` rather than shipping them empty", () => {
1419
- const noCi = run([]);
1420
- assert.equal(noCi.status, 1, noCi.stdout + noCi.stderr);
1421
- assert.equal(noCi.payload.verdict, "no-ci");
1422
-
1423
- for (const field of ["jobs", "missing", "dropped"]) {
1424
- assert.ok(
1425
- !(field in noCi.payload),
1426
- `no-ci never binds a run, so \`${field}\` must be absent, not an empty array — and the payload reads ${JSON.stringify(noCi.payload)}`,
1427
- );
1428
- }
1429
- });
1430
-
1431
- // The declared-away flip only moves the exit code (#111) — it must not start
1432
- // shipping `jobs`/`missing` back in, since `--declare-no-ci` still never binds
1433
- // a run for this script to read either field from.
1434
- test("no CI + --declare-no-ci: `jobs`/`missing` stay absent — the flag changes the gate, not what was read", () => {
1435
- const r = run(["--declare-no-ci"]);
1436
- assert.equal(r.status, 0, r.stdout + r.stderr);
1437
- for (const field of ["jobs", "missing", "dropped"]) {
1438
- assert.ok(!(field in r.payload), `\`${field}\` must stay absent under --declare-no-ci too — got ${JSON.stringify(r.payload)}`);
1439
- }
1440
- });
1441
-
1442
- // #890: the same one-line/one-terminator contract the verdict payload is held to
1443
- // below, at the other call site that writes a payload to stdout. writeAll() appends
1444
- // no newline of its own, so each site supplies its own: supplying none runs this
1445
- // payload together with whatever the caller polling a rate-limited PR prints
1446
- // next, and supplying two ends the output early for a reader that treats a blank
1447
- // line as the end of it. Both were green here before this assertion — the
1448
- // quota-refusal tests above all read `payload`, and the harness parses that from
1449
- // a TRIMMED stdout, so every one of them is blind to the terminator by
1450
- // construction.
1451
- //
1452
- // Compared against a re-serialisation of the payload this very run emitted
1453
- // rather than against a literal copy of it, which is what keeps the assertion
1454
- // about the terminator alone: rewording a reason, or adding a field, changes
1455
- // both sides together and stays green, while any change to the trailing bytes
1456
- // reds. A literal would instead have to be re-typed every time the refusal text
1457
- // moved, and would red for the wrong reason when it was.
1458
- test("the rate-limited payload is emitted byte for byte too: one line, one trailing newline", () => {
1459
- const r = ghFailure(RATE_LIMIT_STDERR);
1460
- assert.equal(r.status, 2, r.stdout + r.stderr);
1461
- assert.equal(r.stdout, `${JSON.stringify(r.payload)}\n`);
1462
- });
1463
-
1464
- // --- #840: a non-numeric --pr must refuse, never ship an unnamed payload -----
1465
- // `--pr` was validated for truthiness alone, so `--pr abc` reached both payload
1466
- // sites. Each builds `pr: Number(pr)`, and `JSON.stringify(NaN)` is `null` — the
1467
- // normal path shipped a payload with no identifying field at exit 0 under
1468
- // `verdict: "green"`, the verdict the fleet gates on.
1469
- //
1470
- // The gh receipt below is the load-bearing assertion, not decoration. Exit 2, an
1471
- // empty stdout and a matching stderr line are each reproducible by a LATER
1472
- // guard: downgrade this one to a warning and the script runs on, gh fails, and
1473
- // die() reproduces all three while the warning still sits in stderr. Only a
1474
- // refusal reached BEFORE the first query can show gh was never asked, so the
1475
- // receipt is what pins fatality and the other three merely describe the refusal.
1476
- //
1477
- // `prView: null` is what keeps that argument true, and is not tidiness. Under
1478
- // the green fixture the downgraded guard reaches a gh that ANSWERS, so the run
1479
- // gets further than the refusal it is being compared against and diverges on
1480
- // its exit code first — the assertion that reds is the status one, and the
1481
- // receipt is never what caught it. A gh that fails when reached is what makes
1482
- // exit 2, an empty stdout and a matching stderr line reproducible by the later
1483
- // guard too, leaving the receipt as the only assertion that separates them.
1484
- //
1485
- // The stub also keeps a regressed guard off this repo's live GitHub data —
1486
- // arg.test.mjs's own stubGhBin() gives the same two jobs, for the same shape of
1487
- // guard.
1488
- test("a non-numeric --pr refuses before any query, rather than reporting `pr: null`", () => {
1489
- const r = run([], { pr: "abc", prView: null });
1490
- assert.equal(r.status, 2, r.stdout + r.stderr);
1491
- assert.match(r.stderr, /--pr needs a number/);
1492
- assert.equal(r.stdout.trim(), "", `a refusal ships no payload, and stdout reads ${r.stdout}`);
1493
- assert.equal(r.log, "", `the refusal must land before the first gh read, and gh was asked: ${r.log}`);
1494
- });
1495
-
1496
- // Both anchors, separately. A guard that loses `$` still matches "42x" on its
1497
- // digit prefix, and one that loses `^` still matches "x42" on its digit suffix,
1498
- // so each value refuses only while its own anchor is present and neither mutant
1499
- // survives the pair. What a surviving mutant lets through is this block's whole
1500
- // defect back: Number("42x") is NaN, the payload's only identifying field
1501
- // serializes to null, and the PR read would build `refs/pull/42x/head` out of it — the
1502
- // ambiguity the digits-only shape is chosen to forfeit against. Every other
1503
- // --pr this suite feeds the guard is all digits or none, and both mutants agree
1504
- // with the real guard on those.
1505
- for (const pr of ["42x", "x42"]) {
1506
- test(`a --pr mixing digits with non-digits refuses as \`abc\` does: ${pr}`, () => {
1507
- const r = run([], { pr, prView: null });
1508
- assert.equal(r.status, 2, r.stdout + r.stderr);
1509
- assert.match(r.stderr, /--pr needs a number/);
1510
- assert.equal(r.stdout.trim(), "", `a refusal ships no payload, and stdout reads ${r.stdout}`);
1511
- assert.equal(r.log, "", `the refusal must land before the first gh read, and gh was asked: ${r.log}`);
1512
- });
1513
- }
1514
-
1515
- // The direction a new guard gets wrong on its own: what it wrongly REFUSES. A
1516
- // suite that only feeds it invalid input pins nothing about the callers it must
1517
- // keep working. board.mjs's runCiState() sends `String(pr)` off a numeric board
1518
- // record, which is exactly the digits this harness defaults to — so a guard
1519
- // tightened past them refuses a working invocation, the outcome #365's own AC
1520
- // calls worse than the bug being fixed.
1521
- //
1522
- // assert/strict pins the TYPE as well as the value: `pr` reading back as the
1523
- // string "42" would satisfy a loose check while breaking every consumer that
1524
- // keys on a number, and reading back as `null` is the defect itself. Nothing
1525
- // else covers the normal-path payload's `pr` — the sibling assertion in the
1526
- // quota section covers the outage payload's.
1527
- test("the numeric shape board.mjs sends is accepted, and the payload names its PR", () => {
1528
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } });
1529
- assert.equal(r.status, 0, r.stdout + r.stderr);
1530
- assert.equal(r.payload.verdict, "green");
1531
- assert.equal(r.payload.pr, 42);
1532
- });
1533
-
1534
- // `--pr 0` is the row the `=== null` absence check exists for, and the one a
1535
- // later "simplification" back to `!pr` silently breaks: numArg() returns a
1536
- // NUMBER, so `!pr` is true for a zero the caller plainly GAVE, and this file's
1537
- // own usage die above would then answer it with "--pr is required" instead of
1538
- // letting gh answer as no such PR. Companion to arg.test.mjs's identical row
1539
- // for diff-stats.mjs and pr-overlap.mjs's own for `--a`/`--b` — #878's own
1540
- // comment names all three callers as sharing this contract, and only
1541
- // diff-stats.mjs had this row before.
1542
- //
1543
- // `strictEqual`, same reason as the "42" test above: a payload reading `pr`
1544
- // back as the string "0" would satisfy a loose check while breaking every
1545
- // consumer that keys on a number.
1546
- test("#878: `--pr 0` reaches gh rather than drawing the usage line for an absent flag", () => {
1547
- const r = run([], { pr: "0", repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } });
1548
- assert.equal(r.status, 0, r.stdout + r.stderr);
1549
- assert.doesNotMatch(r.stderr, /usage:/, `--pr 0 was answered as an absent flag: ${r.stderr}`);
1550
- assert.equal(r.payload.verdict, "green");
1551
- assert.strictEqual(r.payload.pr, 0, `a zero PR must survive to the payload as 0: ${JSON.stringify(r.payload)}`);
1552
- });
1553
-
1554
- // What the new guard's PLACEMENT could newly break. It sits below the usage die
1555
- // on purpose: RegExp.test coerces a null argument to the string "null", so a
1556
- // guard merged into that die — or hoisted above it — answers an omitted --pr
1557
- // with a complaint about a number and never prints the usage line at all. Both
1558
- // spellings exit 2, so the exit code cannot tell them apart.
1559
- test("--pr omitted still answers with the usage line, not the numeric complaint", () => {
1560
- const r = run([], { pr: null, prView: null });
1561
- assert.equal(r.status, 2, r.stdout + r.stderr);
1562
- assert.match(r.stderr, /usage: ci-state\.mjs --pr <number>/);
1563
- assert.doesNotMatch(r.stderr, /needs a number/, "an omitted --pr is a different mistake from a malformed one");
1564
- assert.equal(r.log, "", `a usage refusal must also precede any gh read, and gh was asked: ${r.log}`);
1565
- });
1566
-
1567
- // --- The verdict payload has to survive a pipe ------------------------------
1568
- // `console.log` + `process.exit()` loses whatever is still queued: on a pipe the
1569
- // stdout write is asynchronous, the kernel accepts one buffer's worth
1570
- // synchronously, and process.exit() discards the remainder rather than draining
1571
- // it. The payload is then cut mid-JSON while the exit code arrives intact, so a
1572
- // caller that reads the code sees a normal verdict and a caller that parses
1573
- // stdout gets nothing it can use. emitRateLimited() already writes its payload
1574
- // with writeSync for this reason; these tests hold the verdict payload to the
1575
- // same standard.
1576
- //
1577
- // The mode under test is a stream the parent drains as the child writes, which
1578
- // a file is not: the same payload reaches a file fd whole and is cut on
1579
- // spawnSync's default stdio (measured), which is why these can reuse run() — a
1580
- // harness that captured stdout to a file would pass whether or not the script
1581
- // was ever fixed. That default stdio is not a FIFO but a Unix-domain SOCKET, on
1582
- // darwin and Linux alike (#1730, fstat: isSocket() on fds 1 and 2). It starts
1583
- // out blocking, and Node puts it in O_NONBLOCK once it opens a stream on it
1584
- // (Linux /proc/self/fdinfo): console.log does that to fd 1, and fd 2 has been
1585
- // through it by the time the verdict line is written, quiet or verbose.
1586
- //
1587
- // How far past "one buffer" a fixture has to reach is what that socket takes
1588
- // in ONE non-blocking write, and that is not 64 KiB everywhere. Measured for
1589
- // #1730 on 2026-09-24 with #1722's harness — a spawnSync child opens the fd's
1590
- // stream, then makes one writeSync of N bytes — 200 trials per N per fd, Linux
1591
- // being node:26-slim under Docker:
1592
- //
1593
- // darwin 65,536 bytes, every time.
1594
- // Linux N up to 146,176 went through whole every time, on both fds. Past
1595
- // it the first write took exactly 146,176 at the minimum and the
1596
- // median of every N tried, up to 2 MiB — yet it also took the WHOLE
1597
- // N some of the time, at every N: fd 2 took all of 146,177 38/200,
1598
- // all of 200,000 4/200, all of 1 MiB 1/200.
1599
- //
1600
- // So Linux has a floor and no ceiling. The parent drains the socket while the
1601
- // write is still in the kernel, and a write that races a quick enough reader
1602
- // goes through whole at any size. #1722's 584,704 was the largest first write
1603
- // in its sample, not a bound.
1604
- //
1605
- // These tests used to size themselves past 65,536 alone, and on Linux that
1606
- // proved nothing. Against the regressions two of them exist to catch — the
1607
- // payload back on console.log + process.exit, the stderr line back on one bare
1608
- // writeSync — the 131,323-byte payload and 131,165-byte line they built went
1609
- // out whole 200/200 times, so on Linux both passed the very defect they are
1610
- // named for while their `> 65536` guards held. The green payload, 317,606
1611
- // bytes, caught it 198/200.
1612
- //
1613
- // What the guards compare against is that floor: a payload at or under it goes
1614
- // out in one write on Linux however the script writes it, so the test cannot
1615
- // fail there, and it covers darwin's 65,536 too. It is measured rather than
1616
- // derived from the fixture sizes below, which is what lets it catch the
1617
- // fixture itself: the pre-#1730 one fails it, on darwin as well. A guard
1618
- // against the constant a fixture is built from can never fail, and
1619
- // arg.test.mjs's was exactly that until #1722.
1620
- const LINUX_FIRST_WRITE_BYTES = 146_176;
1621
-
1622
- // The fixture size is the other half, chosen from how often each regression
1623
- // still got through at each size on Linux — not from the floor, and not on
1624
- // "bigger is safer", which the runs refuted. Interleaved, 200 runs per size
1625
- // per regression: the bare writeSync got the stderr line through whole 15
1626
- // times at 2 MiB, against 0–1 from 292,352 to 1 MiB, with short first writes
1627
- // at 2 MiB as large as 2,046,464; console.log got the payload through twice at
1628
- // 292,352 and never from 584,704 up. 1 MiB is where both were lowest. A single
1629
- // write is still unbounded — the race above — so on Linux these tests catch a
1630
- // regression with high probability, not certainty; darwin, whose first write
1631
- // is always 65,536, catches it every time.
1632
- const SHORT_WRITE_BYTES = 1024 * 1024;
1633
-
1634
- const jobId = (i) => `generated-job-${String(i).padStart(6, "0")}-padding-padding`;
1635
-
1636
- // Derived rather than written as a literal number of jobs: the property that
1637
- // matters is "past SHORT_WRITE_BYTES", and a hardcoded count silently stops
1638
- // clearing it the moment the id shape or the payload's other fields change. The
1639
- // ids are shaped the way expectedJobs() derives them, and carry no job-level
1640
- // `name:`, which that derivation refuses.
1641
- function jobsClearingShortWrite() {
1642
- const ids = [];
1643
- for (let joined = 0; joined <= SHORT_WRITE_BYTES; ) {
1644
- const id = jobId(ids.length);
1645
- ids.push(id);
1646
- joined += id.length + ", ".length; // how the absent-jobs reason joins them
1647
- }
1648
- return ids;
1649
- }
1650
-
1651
- const workflowWithJobs = (ids) =>
1652
- `name: CI\non: [pull_request]\njobs:\n${ids.map((id) => ` ${id}:\n runs-on: ubuntu-latest\n steps:\n - run: echo hi\n`).join("")}`;
1653
-
1654
- const succeededJob = (name) => ({ name, status: "completed", conclusion: "success" });
1655
-
1656
- const runViewAllSucceeded = (ids) =>
1657
- JSON.stringify({
1658
- jobs: ids.map(succeededJob),
1659
- attempt: 1,
1660
- status: "completed",
1661
- conclusion: "success",
1662
- headSha: PR_HEAD,
1663
- });
1664
-
1665
- // The green fixture cannot follow the other two to SHORT_WRITE_BYTES. Its jobs
1666
- // arrive through `gh run view`, which ci-state.mjs reads with execFileSync's
1667
- // default 1 MiB maxBuffer — one job past it and the read dies ENOBUFS, and the
1668
- // script exits 2 with no verdict at all (measured: 11,397 jobs). So it carries
1669
- // as many jobs as one run-view reply holds, and since the payload echoes the
1670
- // same jobs back, that lands it at 1 MiB as well, by a different road.
1671
- const GH_READ_BYTES = 1024 * 1024;
1672
- function jobsFillingOneGhRead() {
1673
- const ids = [];
1674
- // One comma counted per job, one more than the reply carries: errs under.
1675
- for (let bytes = runViewAllSucceeded([]).length; ; ) {
1676
- const id = jobId(ids.length);
1677
- bytes += JSON.stringify(succeededJob(id)).length + ",".length;
1678
- if (bytes > GH_READ_BYTES) return ids;
1679
- ids.push(id);
1680
- }
1681
- }
1682
-
1683
- // --quiet is the mode the controller's CI Monitor polls in, and it drops `jobs`
1684
- // and `missing` — so this also pins that the payload still outgrows one write
1685
- // on the hot path, through `reasons` alone, where the absent-job reason names
1686
- // every job it could not find.
1687
- test("a not-green verdict payload too large for one non-blocking write reaches the caller whole", () => {
1688
- const ids = jobsClearingShortWrite();
1689
- const r = run(["--quiet"], {
1690
- repoFiles: { ".github/workflows/ci.yml": workflowWithJobs(ids) },
1691
- tolerateUnparsedStdout: true,
1692
- });
1693
- let payload;
1694
- try {
1695
- payload = JSON.parse(r.stdout);
1696
- } catch (e) {
1697
- assert.fail(`verdict payload did not survive the pipe: ${r.stdout.length} bytes, ${e.message}`);
1698
- }
1699
- assert.ok(
1700
- r.stdout.length > LINUX_FIRST_WRITE_BYTES,
1701
- `fixture no longer outgrows one write on Linux (${r.stdout.length} bytes, floor ${LINUX_FIRST_WRITE_BYTES}), so on Linux this test would pass without proving anything`,
1702
- );
1703
- assert.equal(payload.verdict, "not-green");
1704
- assert.equal(r.status, 1, r.stderr);
1705
- });
1706
-
1707
- // The other direction, and the one a fix for the above can newly break. writeSync
1708
- // throws where console.log swallows — on a saturated non-blocking pipe it raises
1709
- // EAGAIN — and an uncaught throw here would skip the exit call entirely, dropping
1710
- // the process to exit 1: the code this script reserves for not-green. A green PR
1711
- // would then be reported as failing CI, which is worse than the truncation being
1712
- // fixed. Green is also the only verdict that can carry a large payload without
1713
- // `reasons`, so this is what exercises the write with `jobs` doing the growing.
1714
- //
1715
- // That throw needs fd 1 non-blocking, and on run()'s default stdio it never
1716
- // is. The script opens no stream on fd 1, so the payload write blocks until
1717
- // the reader has taken all of it and cannot raise EAGAIN (measured: 1 MiB in
1718
- // one writeSync, 0/100 EAGAIN on darwin and on Linux). A Node caller passing
1719
- // its own non-blocking stdout through changes nothing: the child still took
1720
- // the whole MiB in one write, 20/20 on both. So without nonBlockingStdout,
1721
- // deleting writeAll()'s EAGAIN catch left this test green every time, 20/20 on
1722
- // darwin and 50/50 on Linux, while the other two --quiet tests here, the
1723
- // not-green payload above and the stderr line below, went red through the
1724
- // verdict line on fd 2.
1725
- //
1726
- // nonBlockingStdout opens the stream, and then this payload write meets EAGAIN
1727
- // on its own. With the catch deleted it throws there: red 20/20 on darwin,
1728
- // where the sampled runs exited 1 with the payload cut at 65,536 bytes. On
1729
- // Linux fd 1 is non-blocking at that write too (fdinfo, 30/30), but the 1 MiB
1730
- // usually goes out whole anyway, the no-ceiling race above, so this test caught
1731
- // the same mutant only 19/150 times there. On Linux the two fd 2 tests are what
1732
- // catch it, 50/50 each.
1733
- test("a green verdict payload too large for one non-blocking write still exits 0, gate not inverted", () => {
1734
- const ids = jobsFillingOneGhRead();
1735
- const r = run([], {
1736
- repoFiles: { ".github/workflows/ci.yml": workflowWithJobs(ids) },
1737
- runView: runViewAllSucceeded(ids),
1738
- nonBlockingStdout: true,
1739
- tolerateUnparsedStdout: true,
1740
- });
1741
- let payload;
1742
- try {
1743
- payload = JSON.parse(r.stdout);
1744
- } catch (e) {
1745
- assert.fail(`verdict payload did not survive the pipe: ${r.stdout.length} bytes, ${e.message}`);
1746
- }
1747
- assert.ok(
1748
- r.stdout.length > LINUX_FIRST_WRITE_BYTES,
1749
- `fixture no longer outgrows one write on Linux (${r.stdout.length} bytes, floor ${LINUX_FIRST_WRITE_BYTES}), so on Linux this test would pass without proving anything`,
1750
- );
1751
- assert.equal(payload.verdict, "green");
1752
- assert.equal(r.status, 0, r.stderr);
1753
- });
1754
-
1755
- // What the write must NOT change on every payload that was never at risk. console.log
1756
- // appends exactly one newline and writeSync appends none of its own, so the
1757
- // replacement has to supply it — supplying none concatenates the payload with
1758
- // whatever a caller prints next, and supplying two breaks a reader that treats a
1759
- // blank line as end of output. Pinned as exact bytes rather than "parses", which
1760
- // all three spellings would satisfy.
1761
- test("a payload that never reaches the buffer is emitted byte for byte as before: one line, one trailing newline", () => {
1762
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW } });
1763
- assert.equal(r.status, 0, r.stderr);
1764
- assert.equal(r.stdout, `${JSON.stringify(r.payload)}\n`);
1765
- });
1766
-
1767
- // The guard writeAll() puts around its write is what arg.mjs calls not
1768
- // optional, and until here nothing in this repo EXECUTED it from this script:
1769
- // deleting the try/catch outright and running this file, and then the whole
1770
- // fleet suite, left both green (measured). The two tests above prove a
1771
- // SUCCESSFUL oversized write survives; neither makes the write fail, so the
1772
- // mechanism was pinned by prose alone. arg.test.mjs pins the same guard from
1773
- // die()'s side — and since #1549 it is literally the same code, which is why
1774
- // this test stays: it is the only one that executes it through THIS script's
1775
- // exit-code contract.
1776
- //
1777
- // The failure is forced deterministically rather than by racing a reader: the
1778
- // child's stdout is /dev/null opened READ-only, so the first writeSync raises
1779
- // EBADF. A different errno from the EAGAIN in the field, and the same and only
1780
- // thing writeAll() promises about either — the message may be lost, the exit code
1781
- // may not.
1782
- //
1783
- // Green is the discriminating verdict, and the only one that discriminates: with
1784
- // the guard, the payload is lost and exit 0 still lands; without it the EBADF
1785
- // propagates, skips the process.exit() the tail is about to make, and Node falls
1786
- // through to its default exit 1 — a green PR reported to the fleet's merge gate
1787
- // as failing CI. That is the #299/#328 inversion itself, reproduced without the
1788
- // race, so this discriminates on a machine where EAGAIN never fires. Measured
1789
- // both ways: guarded exit 0, guard removed exit 1.
1790
- test("the verdict write keeps the green exit code when it throws — the guard executed, not lifted", () => {
1791
- const r = run([], { repoFiles: { ".github/workflows/ci.yml": CI_WORKFLOW }, readOnlyStdout: true });
1792
- assert.equal(r.status, 0, `exit ${r.status}: the verdict write threw and took the green verdict with it`);
1793
- });
1794
-
1795
- // The verdict SUMMARY goes to fd 2, and fd 2 already has a Node stream open on
1796
- // it by then — vlog's console.error, or under --quiet the git stderr
1797
- // execFileSync forwards — which is what puts it in O_NONBLOCK. A
1798
- // non-blocking write to a full pipe SHORT-WRITES: it returns the count it
1799
- // managed and throws nothing, so the catch above never fires and nothing is
1800
- // logged. Measured against this same fixture before the write loop consumed that
1801
- // value: the line arrived cut at one buffer with its trailing newline gone, in
1802
- // this quiet mode and in the verbose one, while stdout and the exit code came
1803
- // through untouched — the one channel the tests above cannot speak for.
1804
- //
1805
- // Completeness is asserted by CONTENT, before the size guard rather than after.
1806
- // The absent-job reason ends with the last id it joined, so a cut line simply
1807
- // does not end with it; a truncated line is also one first write long — 65,535
1808
- // bytes on darwin, most often 146,175 on Linux (measured, #1730) — which would
1809
- // fail the size guard and blame the fixture for a defect in the script. Ordered
1810
- // this way each failure names its own cause.
1811
- test("the verdict line on stderr, too large for one non-blocking write, survives with its reasons whole", () => {
1812
- const ids = jobsClearingShortWrite();
1813
- const r = run(["--quiet"], {
1814
- repoFiles: { ".github/workflows/ci.yml": workflowWithJobs(ids) },
1815
- tolerateUnparsedStdout: true,
1816
- });
1817
- const line = r.stderr.split("\n").find((l) => l.includes("verdict="));
1818
- assert.ok(line, `no verdict line on stderr at all, in ${r.stderr.length} bytes`);
1819
- assert.ok(
1820
- line.endsWith(ids[ids.length - 1]),
1821
- `verdict line cut mid-reason at ${Buffer.byteLength(line)} bytes: it does not reach the last job it names`,
1822
- );
1823
- assert.ok(
1824
- Buffer.byteLength(line) > LINUX_FIRST_WRITE_BYTES,
1825
- `fixture no longer outgrows one write on Linux on stderr (${Buffer.byteLength(line)} bytes, floor ${LINUX_FIRST_WRITE_BYTES}), so on Linux this test would pass without proving anything`,
1826
- );
1827
- assert.equal(r.status, 1, "the exit code must survive the write it follows");
1828
- });
1829
-
1830
- // #901: the verdict summary is the writeAll() call site on fd 2, and the
1831
- // terminator contract already held at the payload sites on stdout was never
1832
- // pinned here. writeAll() appends no newline of its own, so each call site
1833
- // supplies its own: supplying none runs this line together with whatever the
1834
- // caller prints next, and supplying an extra ends the output early for a
1835
- // reader that treats a blank line as the end of it.
1836
- //
1837
- // The completeness assertion covering this same line cannot stand in for that.
1838
- // It locates the line by splitting stderr on "\n", and splitting on the
1839
- // terminator is what discards it — every segment that yields is the content
1840
- // BETWEEN newlines, so no wording of an assertion over that segment can see
1841
- // whether the line was terminated at all. Measured before this test existed:
1842
- // dropping the trailing newline left this file green.
1843
- //
1844
- // fd 2 also carries the vlog trace stream and gh's own forwarded stderr, so it
1845
- // has no single expected byte string and the whole-stream equality the stdout
1846
- // pins use has no equivalent here. This isolates the line instead — it locates
1847
- // the summary by the verdict and reasons THIS run reported, then reads the
1848
- // bytes on either side of it. Deriving the expected text from the emitted
1849
- // payload rather than from a literal copy is what keeps the assertions about
1850
- // the newlines alone: rewording a reason or adding a payload field moves both
1851
- // sides together and stays green, as does rewording any trace.
1852
- //
1853
- // The LEADING newline is insurance for forwarded child stderr still draining
1854
- // through the async stream without having ended its line — arg.mjs's die()
1855
- // documents the same shape for the same reason. That RACE is what does not
1856
- // reproduce here: the text before the summary has already ended its own line,
1857
- // in this fixture a vlog trace. The BYTE is another matter — against already-ended
1858
- // text the leading newline leaves a blank line and dropping it leaves none —
1859
- // so it is pinned below, doubled as well as missing. What that leaves
1860
- // untested is the mid-line landing the newline exists to prevent, not the
1861
- // newline itself.
1862
- test("the verdict summary on stderr carries exactly one newline of its own on each side", () => {
1863
- const r = run([]);
1864
- assert.ok(
1865
- r.payload.reasons.length,
1866
- "fixture no longer produces a reason, so the summary derived below would carry an em dash the script omits when reasons is empty, and this test would fail on the lookup rather than on the terminator",
1867
- );
1868
- const summary = `ci-state: verdict=${r.payload.verdict} — ${r.payload.reasons.join("; ")}`;
1869
- const at = r.stderr.indexOf(summary);
1870
- assert.ok(at >= 0, `the verdict summary is not on stderr as emitted, in ${JSON.stringify(r.stderr)}`);
1871
- const before = r.stderr.slice(0, at);
1872
- assert.equal(
1873
- before.match(/\n*$/)[0].length,
1874
- 2,
1875
- `the summary's own leading newline must leave exactly one blank line after the already-ended text before it, which runs ${JSON.stringify(before.slice(-40))}`,
1876
- );
1877
- const after = r.stderr.slice(at + summary.length);
1878
- assert.ok(
1879
- after.startsWith("\n"),
1880
- `the verdict summary is unterminated: it runs straight into ${JSON.stringify(after.slice(0, 40))}`,
1881
- );
1882
- assert.ok(
1883
- !after.startsWith("\n\n"),
1884
- "the verdict summary's terminator is doubled, ending the stream early for a reader that stops at a blank line",
1885
- );
1886
- });
1887
-
1888
- // The shape pin. The test above executes the guard, and this one pins that the
1889
- // write still goes through the SHARED loop — the two are independent: a body
1890
- // that catches faithfully and still calls writeSync once satisfies the
1891
- // behavioural test and reintroduces the short write, because a short write
1892
- // never throws.
1893
- //
1894
- // #1549: this file used to pin its own copy of that loop, with a regex
1895
- // differing from candidates.test.mjs's and staleness.test.mjs's only in head
1896
- // line, Buffer.from argument and fd. Three near-copies pinning three
1897
- // hand-mirrored loops is exactly what that ticket removed — the loop's shape,
1898
- // its EAGAIN cap and its short-write resume are now pinned AND executed once,
1899
- // in arg.test.mjs, against arg.mjs's writeAll().
1900
- //
1901
- // What is left for this file to pin is the half arg.test.mjs cannot see: that
1902
- // ci-state.mjs still ROUTES through it. emit() was this script's own copy and
1903
- // the only one of the three that never grew #889's retry cap, so the copy
1904
- // coming BACK is the specific regression here — and it is invisible to every
1905
- // behavioural test in this file, because a freshly hand-rolled loop behaves
1906
- // identically on the day it is written and drifts only afterwards.
1907
- //
1908
- // Derived through stripComments() rather than matched against raw source: a
1909
- // /m regex over raw source is satisfied by the correct shape sitting in a
1910
- // block comment, and `^(?!\s*//)` closes neither escape (both measured, and
1911
- // strip-comments.mjs's own header records them).
1912
- test("ci-state.mjs routes every outbound write through arg.mjs's writeAll(), with no re-inlined loop of its own", () => {
1913
- const source = stripComments(readFileSync(SCRIPT, "utf8"));
1914
- assert.match(
1915
- source,
1916
- /^import \{[^}]*\bwriteAll\b[^}]*\} from "\.\/arg\.mjs";/m,
1917
- "ci-state.mjs must import writeAll from ./arg.mjs rather than hand-rolling its own write loop",
1918
- );
1919
- // Measured: re-inlining an emit()-shaped loop into this file reds exactly
1920
- // this assertion and nothing else in the suite.
1921
- assert.equal(
1922
- source.match(/\bwriteSync\(/g),
1923
- null,
1924
- "ci-state.mjs calls writeSync directly again — every write here must go through writeAll(), whose loop and EAGAIN cap are pinned once in arg.test.mjs",
1925
- );
1926
- // ...and the write is actually THERE: without this, deleting the verdict
1927
- // write outright would satisfy the assertion above.
1928
- assert.match(
1929
- source,
1930
- /^writeAll\(1, `\$\{JSON\.stringify\(payload\)\}\\n`\);/m,
1931
- "the verdict payload must go out through writeAll() on fd 1 — the write every pipe-buffer test above is about",
1932
- );
1933
- });