@feigi/fleet-ctl 0.0.0 → 3.16.3

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 (153) hide show
  1. package/agents/{fleet-implementer.agent.md → fleet-implementer-slow-high.agent.md} +23 -2
  2. package/agents/fleet-implementer-slow-medium.agent.md +231 -0
  3. package/agents/fleet-implementer-smol-high.agent.md +231 -0
  4. package/agents/{fleet-implementer-alt.agent.md → fleet-implementer-task-high.agent.md} +23 -2
  5. package/agents/fleet-implementer-task-max.agent.md +231 -0
  6. package/agents/fleet-review-comments.agent.md +4 -2
  7. package/agents/fleet-review-correctness.agent.md +2 -1
  8. package/agents/fleet-review-runner.agent.md +14 -10
  9. package/agents/fleet-review-silent-failure.agent.md +4 -3
  10. package/agents/fleet-review-simplify.agent.md +2 -1
  11. package/agents/fleet-review-snapshot.agent.md +2 -1
  12. package/agents/fleet-review-test-run.agent.md +29 -0
  13. package/agents/fleet-review-tests.agent.md +10 -5
  14. package/agents/fleet-review-types.agent.md +4 -2
  15. package/agents/fleet-review-verifier.agent.md +4 -3
  16. package/commands/review-and-fix.md +7 -6
  17. package/commands/run-merge-bot.md +14 -4
  18. package/package.json +4 -2
  19. package/scripts/agent-test.test.mjs +36 -32
  20. package/scripts/ambient-git-vars-mjs-prose.test.mjs +23 -13
  21. package/scripts/apply-ruleset.test.mjs +4 -3
  22. package/scripts/arg-header-probes-prose.test.mjs +1 -0
  23. package/scripts/arg.test.mjs +18 -18
  24. package/scripts/board-cli.test.mjs +18 -21
  25. package/scripts/board-identity.test.mjs +9 -9
  26. package/scripts/board-liveness-banner.test.mjs +6 -6
  27. package/scripts/board-prev-shape.test.mjs +12 -13
  28. package/scripts/board-tryparse-null.test.mjs +7 -7
  29. package/scripts/board.mjs +4 -7
  30. package/scripts/board.test.mjs +57 -61
  31. package/scripts/candidates.test.mjs +228 -17
  32. package/scripts/ci-completes-premise-prose.test.mjs +1 -1
  33. package/scripts/ci-state-prose.test.mjs +2 -2
  34. package/scripts/ci-state.mjs +389 -187
  35. package/scripts/ci-state.test.mjs +458 -165
  36. package/scripts/citation-sweep-prose.test.mjs +59 -1
  37. package/scripts/claim-lifecycle.test.mjs +2 -1
  38. package/scripts/claim-ticket.test.mjs +35 -34
  39. package/scripts/closing-keyword-prose.test.mjs +1 -1
  40. package/scripts/cockpit-tick-nonblocking.test.mjs +8 -8
  41. package/scripts/compute-board.mjs +13 -3
  42. package/scripts/compute-board.test.mjs +64 -1
  43. package/scripts/compute-spend.mjs +46 -8
  44. package/scripts/compute-spend.test.mjs +64 -10
  45. package/scripts/cross-repo-citation-prose.test.mjs +18 -19
  46. package/scripts/delete-merged-branch.sh +218 -0
  47. package/scripts/delete-merged-branch.test.mjs +576 -0
  48. package/scripts/derive-testcmd.sh +18 -7
  49. package/scripts/derive-testcmd.test.mjs +9 -8
  50. package/scripts/diff-stats.mjs +2 -2
  51. package/scripts/diff-stats.test.mjs +7 -11
  52. package/scripts/dispatch-block-golden-prose.test.mjs +111 -6
  53. package/scripts/dispatch-block-pins-prose.test.mjs +5 -5
  54. package/scripts/dispositions-check.mjs +507 -0
  55. package/scripts/dispositions-check.test.mjs +843 -0
  56. package/scripts/dispositions-gate-prose.test.mjs +114 -0
  57. package/scripts/drop-merged-label.test.mjs +3 -4
  58. package/scripts/exec-stub.mjs +93 -0
  59. package/scripts/exec-stub.test.mjs +69 -0
  60. package/scripts/filing-bar-seat-prose.test.mjs +1 -1
  61. package/scripts/finisher-test-verdict-prose.test.mjs +102 -0
  62. package/scripts/fix-applier-correction-rules-prose.test.mjs +11 -10
  63. package/scripts/fleet-bootstrap +5 -20
  64. package/scripts/fleet-bootstrap.test.mjs +75 -0
  65. package/scripts/fleet-heartbeat.mjs +2 -2
  66. package/scripts/fleet-provenance +15 -24
  67. package/scripts/fleet-provenance.test.mjs +86 -12
  68. package/scripts/fleet-run.test.mjs +5 -5
  69. package/scripts/fleet-state.mjs +33 -11
  70. package/scripts/fleet-state.test.mjs +90 -3
  71. package/scripts/fleet-tick.mjs +346 -70
  72. package/scripts/fleet-tick.test.mjs +566 -16
  73. package/scripts/force-with-lease-reason-prose.test.mjs +1 -1
  74. package/scripts/frontmatter-check.mjs +3 -2
  75. package/scripts/frontmatter-check.test.mjs +6 -6
  76. package/scripts/immutable-body-claim-prose.test.mjs +53 -262
  77. package/scripts/implementer-model-tier.test.mjs +98 -506
  78. package/scripts/inflight.test.mjs +18 -127
  79. package/scripts/is-cli.mjs +26 -0
  80. package/scripts/is-cli.test.mjs +99 -0
  81. package/scripts/json.test.mjs +3 -3
  82. package/scripts/ledger-dispatch.test.mjs +368 -7
  83. package/scripts/ledger-grammar.mjs +85 -1
  84. package/scripts/ledger-grammar.test.mjs +86 -1
  85. package/scripts/ledger-read-require-file.test.mjs +7 -7
  86. package/scripts/ledger-rotate.test.mjs +142 -0
  87. package/scripts/ledger.mjs +181 -17
  88. package/scripts/ledger.test.mjs +12 -130
  89. package/scripts/main-checkout.mjs +312 -0
  90. package/scripts/main-checkout.test.mjs +332 -0
  91. package/scripts/member-outcomes-header.test.mjs +3 -3
  92. package/scripts/member-outcomes.mjs +4 -5
  93. package/scripts/member-outcomes.test.mjs +92 -18
  94. package/scripts/member-prompt-prose.test.mjs +17 -13
  95. package/scripts/member-record.mjs +8 -3
  96. package/scripts/member-record.test.mjs +5 -5
  97. package/scripts/member-write-guard.mjs +5 -5
  98. package/scripts/member-write-guard.test.mjs +6 -3
  99. package/scripts/no-undo-audit.sh +24 -21
  100. package/scripts/no-undo-audit.test.mjs +9 -13
  101. package/scripts/pointer-target-prose.test.mjs +1 -1
  102. package/scripts/pr-overlap.test.mjs +6 -9
  103. package/scripts/prompt-renderer.mjs +10 -9
  104. package/scripts/prose-pin.mjs +10 -11
  105. package/scripts/prove-merge.test.mjs +3 -3
  106. package/scripts/quiet-payload-prose.test.mjs +1 -1
  107. package/scripts/reap.test.mjs +3 -4
  108. package/scripts/release-label-split-prose.test.mjs +17 -2
  109. package/scripts/release-ticket.test.mjs +35 -44
  110. package/scripts/review-core-cwd-isolation.test.mjs +7 -6
  111. package/scripts/review-core-reads.test.mjs +1 -1
  112. package/scripts/review-core-scratch-refusal.test.mjs +64 -0
  113. package/scripts/review-core-shared-test-run.test.mjs +238 -0
  114. package/scripts/review-core-snapshot-path.test.mjs +59 -12
  115. package/scripts/review-core-specialist-scratch.test.mjs +12 -10
  116. package/scripts/review-core-testcmd.test.mjs +76 -45
  117. package/scripts/review-core-unrun.test.mjs +154 -168
  118. package/scripts/review-core.mjs +250 -56
  119. package/scripts/review-eval.mjs +11 -4
  120. package/scripts/review-host-fixture.mjs +12 -3
  121. package/scripts/review-in-run-retry.test.mjs +27 -3
  122. package/scripts/review-runner-spawns.test.mjs +5 -3
  123. package/scripts/review-runner.test.mjs +14 -3
  124. package/scripts/review-tier-audit.test.mjs +1 -1
  125. package/scripts/run-merge-bot-prose.test.mjs +29 -6
  126. package/scripts/scratch-partition-invariant-prose.test.mjs +1 -1
  127. package/scripts/section-between-guard-prose.test.mjs +4 -3
  128. package/scripts/select-dimensions.test.mjs +1 -1
  129. package/scripts/shell-traps-prose.test.mjs +6 -9
  130. package/scripts/shortlist.mjs +4 -1
  131. package/scripts/shortlist.test.mjs +30 -16
  132. package/scripts/snapshot-repo.test.mjs +177 -4
  133. package/scripts/stash-prohibition-prose.test.mjs +1 -1
  134. package/scripts/temp-dir.mjs +47 -0
  135. package/scripts/tier-check.mjs +95 -28
  136. package/scripts/tier-check.test.mjs +131 -29
  137. package/scripts/tier-outcomes-header.test.mjs +11 -54
  138. package/scripts/tier-outcomes.mjs +34 -12
  139. package/scripts/tier-outcomes.test.mjs +157 -4
  140. package/scripts/tier-roles.mjs +118 -29
  141. package/scripts/tier-roles.test.mjs +226 -61
  142. package/scripts/tracker-block-copy-prose.test.mjs +3 -3
  143. package/scripts/verify-sha.test.mjs +4 -5
  144. package/scripts/watcher-degraded-block.test.mjs +5 -8
  145. package/scripts/within-run-pair-prose.test.mjs +43 -75
  146. package/scripts/worktree-audit.test.mjs +2 -1
  147. package/skills/next-ticket/SKILL.md +2 -2
  148. package/skills/run-team/SKILL.md +433 -303
  149. package/skills/run-team/references/ci-and-staleness.md +7 -6
  150. package/skills/run-team/references/correction-tickets.md +3 -3
  151. package/skills/run-team/references/isolation.md +1 -1
  152. package/skills/sizing-a-ticket/SKILL.md +8 -8
  153. package/scripts/tier-guard-gate-prose.test.mjs +0 -216
@@ -13,7 +13,6 @@
13
13
 
14
14
  import { execFileSync } from "node:child_process";
15
15
  import { gitEnv } from "./git-env.mjs";
16
- import { readdirSync, readFileSync } from "node:fs";
17
16
  import { makeDie, defineFlags, writeAll } from "./arg.mjs";
18
17
 
19
18
  const NAME = "ci-state";
@@ -40,7 +39,7 @@ const { arg, numArg, has, sweep, stray } = defineFlags(die, {
40
39
  });
41
40
 
42
41
  // `--quiet` suppresses the diagnostic stream (command echoes, per-job/per-field
43
- // lines) and drops `jobs` and `missing` from the payload. The controller's CI
42
+ // lines) and drops `jobs`, `missing` and `dropped` from the payload. The controller's CI
44
43
  // Monitor (and, standalone, the reviewer's own watch loop) polls this hot, and
45
44
  // none of that stream is acted on — `reasons` already names every failing job,
46
45
  // and the exit code already encodes green/not-green. die() and the one-line
@@ -124,16 +123,41 @@ function emitRateLimited(query) {
124
123
  writeAll(1, `${JSON.stringify(payload)}\n`);
125
124
  }
126
125
 
127
- function run(cmd, args) {
126
+ // The one spawn both primitives below go through. Its child's env drops
127
+ // GIT_DIR and GIT_WORK_TREE (gitEnv()), and every child here is `gh`, which
128
+ // runs git itself to resolve the repository — `{owner}`/`{repo}` and, through
129
+ // `gh repo view`, the host — from the cwd's remotes. Either variable outranks
130
+ // that cwd: measured, `gh repo view` and `gh api repos/{owner}/{repo}` under
131
+ // an ambient GIT_DIR both answer for the repository it names, silently, at
132
+ // exit 0.
133
+ //
134
+ // `maxBuffer` defaults to execFileSync's own 1 MiB; only the workflow-tree
135
+ // reads pass a larger one (see graphql() below). `capture` keeps the child's
136
+ // stderr instead of forwarding it, for the one read whose failure can still
137
+ // turn out to be an answer (see graphql()).
138
+ function spawn(cmd, args, { maxBuffer, capture = false } = {}) {
128
139
  vlog(`$ ${cmd} ${args.join(" ")}`);
140
+ return execFileSync(cmd, args, { encoding: "utf8", env: gitEnv(), ...(maxBuffer ? { maxBuffer } : {}), ...(capture ? { stdio: "pipe" } : {}) });
141
+ }
142
+
143
+ // Three disjoint shapes — Node-aborted (ENOENT/ENOBUFS), signal, exit (#176).
144
+ const failureOf = (e) => e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`);
145
+
146
+ // `recover(e)`, given, is handed a failed child and returns the stdout to use
147
+ // instead, or null when the failure stands. `why`, given, says what the
148
+ // failure leaves unanswerable.
149
+ function run(cmd, args, { maxBuffer, recover, why } = {}) {
129
150
  try {
130
- return execFileSync(cmd, args, { encoding: "utf8" });
151
+ return spawn(cmd, args, { maxBuffer, capture: !!recover });
131
152
  } catch (e) {
153
+ const recovered = recover?.(e);
154
+ if (recovered != null) return recovered;
132
155
  // Names the cause, never the child's stderr — execFileSync forwarded it
133
- // already (no `stdio` above), so interpolating it emits every byte twice.
134
- // `e.message` is the same string, not a fallback: Node builds it as
135
- // `Command failed: <cmd>\n<stderr>`. Three disjoint shapes — Node-aborted
136
- // (ENOENT/ENOBUFS), signal, exit (#176).
156
+ // already, so interpolating it emits every byte twice. A recoverable read
157
+ // captured it instead, so that one is forwarded here, once, now that the
158
+ // failure stands. `e.message` is the same string, not a fallback: Node
159
+ // builds it as `Command failed: <cmd>\n<stderr>`.
160
+ if (recover && e.stderr) writeAll(2, e.stderr);
137
161
  // A quota refusal names itself first (#262); every other cause reports
138
162
  // exactly as it always has, on this same line and this same exit code.
139
163
  // `?? ""` stays — RegExp.test would coerce an absent stderr to the string
@@ -141,7 +165,7 @@ function run(cmd, args) {
141
165
  // it does nothing: encoding: "utf8" above makes e.stderr a string whenever
142
166
  // a child ran, and test() ToString-coerces anything else regardless.
143
167
  if (RATE_LIMITED.test(e.stderr ?? "")) emitRateLimited(`${cmd} ${args[0]} ${args[1]}`);
144
- die(`${cmd} failed: ${e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`)}`);
168
+ die(`${cmd} failed: ${failureOf(e)}${why ? ` — ${why}` : ""}`);
145
169
  }
146
170
  }
147
171
 
@@ -170,8 +194,8 @@ const cut = (s, n = 120) => (s.length > n ? `${s.slice(0, n)}… (truncated)` :
170
194
  // rather than cited by line, since both files move. Parity with them is
171
195
  // partial on purpose: those check the discriminating field of every row, the
172
196
  // row-level checks here refuse on object-ness alone — see the next comment.
173
- function runJson(cmd, args, shape) {
174
- const raw = run(cmd, args);
197
+ function runJson(cmd, args, shape, opts) {
198
+ const raw = run(cmd, args, opts);
175
199
  let parsed;
176
200
  try {
177
201
  parsed = JSON.parse(raw);
@@ -291,140 +315,309 @@ sweep();
291
315
  // positional of its own, so any leftover token is one.
292
316
  stray();
293
317
 
294
- // --- PR facts -------------------------------------------------------------
295
- const prInfo = runJson(
318
+ // The spawn primitive for the reads allowed to fail — the behind-count's own
319
+ // probes — answering null where run() would die.
320
+ function tryRun(cmd, args) {
321
+ try {
322
+ return spawn(cmd, args);
323
+ } catch (e) {
324
+ // Same discipline as run(), and it matters more here: --quiet suppresses
325
+ // vlog entirely, so under the controller's Monitor this line is discarded
326
+ // and the interpolated stderr would have been paid for and then thrown
327
+ // away. Name the cause; the child's own bytes already reached the caller.
328
+ vlog(` ${NAME}: ${cmd} failed: ${failureOf(e)}`);
329
+ return null;
330
+ }
331
+ }
332
+
333
+ const WORKFLOWS_DIR = ".github/workflows";
334
+
335
+ // `--workflow-file` names a repo-relative path, read at both commits like a
336
+ // discovered one. It is split into the directory read and the entry picked
337
+ // out of it, so it travels the same tree shape discovery does. A path that
338
+ // could leave the repository, or that names no directory, is refused before
339
+ // any read.
340
+ let wfDir = WORKFLOWS_DIR;
341
+ let wfEntry = null;
342
+ if (workflowFileArg) {
343
+ const segs = workflowFileArg.replace(/^(?:\.\/)+/, "").split("/");
344
+ if (workflowFileArg.startsWith("/") || segs.length < 2 || segs.some((s) => s === "" || s === "." || s === "..")) {
345
+ die(`--workflow-file takes a repo-relative path such as ${WORKFLOWS_DIR}/ci.yml, read at the PR's head and base commits — got '${workflowFileArg}'`);
346
+ }
347
+ wfEntry = segs.pop();
348
+ wfDir = segs.join("/");
349
+ }
350
+
351
+ // --- The repository and its host -------------------------------------------
352
+ // Every read up to the run query is `gh api`, and `gh api` does NOT infer the
353
+ // host from the local remote the way `gh pr` and `gh run` do — on a GitHub
354
+ // Enterprise repo it silently 404s against github.com. So the host is named on
355
+ // every `gh api` call, and it is taken from gh's own resolution of the cwd's
356
+ // repository — the same resolution that fills `{owner}`/`{repo}` in those
357
+ // calls — never parsed out of a remote URL. gh already handles what a URL
358
+ // parse gets wrong: credentials in the URL (`https://x-access-token:…@host/`),
359
+ // ssh host aliases, and a repository whose remote is not named `origin`.
360
+ // A cwd gh resolves no repository from is exit 2: the question cannot be asked.
361
+ const repoView = runJson(
296
362
  "gh",
297
- ["pr", "view", String(pr), "--json", "headRefName,headRefOid,state,mergeStateStatus"],
363
+ ["repo", "view", "--json", "nameWithOwner,url"],
298
364
  (v) => {
299
365
  if (!isObject(v)) return "expected an object";
300
- if (typeof v.headRefName !== "string" || !v.headRefName) return `headRefName (the branch) is not a non-empty string (${saw(v, "headRefName")})`;
301
- if (typeof v.headRefOid !== "string" || !v.headRefOid) return `headRefOid (the head sha) is not a non-empty string (${saw(v, "headRefOid")})`;
366
+ if (typeof v.nameWithOwner !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(v.nameWithOwner)) return `nameWithOwner is not owner/name (${saw(v, "nameWithOwner")})`;
367
+ if (typeof v.url !== "string" || !URL.canParse(v.url) || !new URL(v.url).hostname) return `url carries no host (${saw(v, "url")})`;
302
368
  return null;
303
369
  },
370
+ { why: "no GitHub repository resolves from this cwd's git remotes, so neither the PR nor its workflows can be read" },
304
371
  );
372
+ const host = new URL(repoView.url).hostname;
373
+
374
+ // --- PR facts and both workflow trees, read at explicit commits -------------
375
+ // The workflow the expected jobs come from is read at the PR's own commits —
376
+ // the head the run is bound to and the base it merges into — never from the
377
+ // caller's working tree. A working tree answers for whatever is checked out
378
+ // in it: a PR worktree with the head's job set, a `main` checkout with the
379
+ // base's, stale or dirty, so one PR and one run used to read differently
380
+ // depending on who asked.
381
+ //
382
+ // One GraphQL query carries the PR fields and both trees. The head is
383
+ // addressed as `refs/pull/N/head`, which outlives the head branch (the PR's
384
+ // `headRef` reads null once the branch is deleted), and must resolve to
385
+ // `headRefOid` — any other commit means the head moved between the halves of
386
+ // one read, which is exit 2 rather than one commit's workflow judged against
387
+ // another's run.
388
+ //
389
+ // The base is the commit at `baseRefOid`. `baseRef.target` is the base
390
+ // branch's TIP, which is that commit only until the base advances: an open
391
+ // PR whose base moved on since its last push carries a `baseRefOid` behind
392
+ // the tip. When the two agree, the tree already read is the right one;
393
+ // otherwise a second read addresses `baseRefOid` itself and must answer for
394
+ // exactly that commit, or exit 2 — never the tip's tree in its place.
395
+
396
+ // Every commit's workflow directory is read as `file(path:)` — the tree entry
397
+ // at that path — because the entry's `type` is what tells a directory from
398
+ // anything else standing there: a file, or a submodule (`commit`), whose
399
+ // `object` reads back null exactly as a missing path's would.
400
+ const TREE_FRAGMENT =
401
+ "fragment wf on GitObject { __typename ... on Tree { entries { name type object { __typename ... on Blob { text isTruncated } } } } }";
402
+ const DIR_ENTRY = "file(path: $dir) { type object { ...wf } }";
403
+ const PR_QUERY = `${TREE_FRAGMENT}
404
+ query($owner: String!, $name: String!, $pr: Int!, $dir: String!, $headExpr: String!) {
405
+ repository(owner: $owner, name: $name) {
406
+ pullRequest(number: $pr) {
407
+ headRefName headRefOid baseRefName baseRefOid state mergeStateStatus
408
+ baseRef { target { oid ... on Commit { ${DIR_ENTRY} } } }
409
+ }
410
+ head: object(expression: $headExpr) { oid ... on Commit { ${DIR_ENTRY} } }
411
+ }
412
+ }`;
413
+ const BASE_QUERY = `${TREE_FRAGMENT}
414
+ query($owner: String!, $name: String!, $dir: String!, $baseExpr: String!) {
415
+ repository(owner: $owner, name: $name) {
416
+ base: object(expression: $baseExpr) { oid ... on Commit { ${DIR_ENTRY} } }
417
+ }
418
+ }`;
419
+ // Where in each reply a `file` field sits, as GraphQL error paths spell it.
420
+ const HEAD_DIR = "repository.head.file";
421
+ const TIP_DIR = "repository.pullRequest.baseRef.target.file";
422
+ const BASE_DIR = "repository.base.file";
423
+
424
+ // `shape` here receives `data.repository`, the one object every query above
425
+ // answers inside; a reply without it is refused before `shape` runs. The
426
+ // query goes out on one line so its command echo stays one line too.
427
+ //
428
+ // A path that does not exist is not answered with a quiet null: `file(path:)`
429
+ // returns null AND a top-level `NOT_FOUND` error for it, and gh exits 1 on any
430
+ // reply carrying errors, printing that reply on stdout all the same
431
+ // (measured). That failure is the one that can be an answer: when every error
432
+ // in the reply is a NOT_FOUND on one of the `file` fields named in
433
+ // `absentAt`, the reply stands, and those paths come back in `notFound` — the
434
+ // only way a workflow directory is ever read as absent. Any other error, or a
435
+ // NOT_FOUND anywhere else (no such PR, no such repository), fails the read.
436
+ //
437
+ // The reply carries the text of every workflow file at up to two commits, so
438
+ // it gets a buffer sized for that rather than execFileSync's 1 MiB default:
439
+ // past the default the read dies ENOBUFS, and a repo whose workflows are
440
+ // merely large would get exit 2 where reading them off disk never did.
441
+ const TREE_READ_BYTES = 64 * 1024 * 1024;
442
+ function graphql(query, vars, absentAt, shape) {
443
+ const fields = Object.entries(vars).flatMap(([k, v]) => [typeof v === "number" ? "-F" : "-f", `${k}=${v}`]);
444
+ let notFound = [];
445
+ const recover = (e) => {
446
+ if (e.status !== 1) return null;
447
+ let reply;
448
+ try {
449
+ reply = JSON.parse(e.stdout);
450
+ } catch {
451
+ return null;
452
+ }
453
+ const errors = isObject(reply) ? reply.errors : undefined;
454
+ if (!Array.isArray(errors) || errors.length === 0) return null;
455
+ const paths = errors.map((err) => (isObject(err) && err.type === "NOT_FOUND" && Array.isArray(err.path) ? err.path.join(".") : null));
456
+ if (paths.some((p) => !absentAt.includes(p))) return null;
457
+ notFound = paths;
458
+ return e.stdout;
459
+ };
460
+ const repo = runJson(
461
+ "gh",
462
+ ["api", "graphql", "--hostname", host, "-F", "owner={owner}", "-F", "name={repo}", ...fields, "-f", `query=${query.replace(/\s+/g, " ")}`],
463
+ (v) => {
464
+ if (!isObject(v) || !isObject(v.data) || !isObject(v.data.repository)) return "expected an object carrying data.repository";
465
+ return shape?.(v.data.repository) ?? null;
466
+ },
467
+ { maxBuffer: TREE_READ_BYTES, recover },
468
+ ).data.repository;
469
+ return { repo, notFound };
470
+ }
471
+
472
+ // One commit's workflow directory, from the `file` entry `commit` carries:
473
+ // the Tree, or null ONLY where GitHub said NOT_FOUND for exactly that path. A
474
+ // null with no such error is a reply this script does not understand, and an
475
+ // entry that is there but is not a directory is not an absence either.
476
+ function dirAt(commit, side, at, notFound) {
477
+ const entry = isObject(commit) ? commit.file : undefined;
478
+ if (entry === null && notFound.includes(at)) return null;
479
+ if (!isObject(entry) || entry.type !== "tree") {
480
+ die(`${wfDir} at the ${side} commit is not a readable directory (got ${cut(JSON.stringify(entry) ?? "nothing")})`);
481
+ }
482
+ return entry.object;
483
+ }
484
+
485
+ const headExpr = `refs/pull/${pr}/head`;
486
+ const prRead = graphql(PR_QUERY, { pr, dir: wfDir, headExpr }, [HEAD_DIR, TIP_DIR], (repo) => {
487
+ const v = repo.pullRequest;
488
+ if (!isObject(v)) return `pullRequest is not an object (${saw(repo, "pullRequest")})`;
489
+ for (const [key, what] of [["headRefName", "the branch"], ["headRefOid", "the head sha"], ["baseRefName", "the base branch"], ["baseRefOid", "the base sha"]]) {
490
+ if (typeof v[key] !== "string" || !v[key]) return `${key} (${what}) is not a non-empty string (${saw(v, key)})`;
491
+ }
492
+ return null;
493
+ });
494
+ const prInfo = prRead.repo.pullRequest;
305
495
  const branch = prInfo.headRefName;
306
496
  const prHead = prInfo.headRefOid;
307
- vlog(` branch=${branch} head=${prHead} state=${prInfo.state} mergeState=${prInfo.mergeStateStatus}`);
308
-
309
- // --- Workflow file: discovered, not assumed --------------------------------
310
- // A hard-coded `.github/workflows/ci.yml` default made every fleet CI read
311
- // exit 2 the moment a repo's workflow had a different filename — no caller
312
- // anywhere passed --workflow-file to work around it (#111). Locate the file
313
- // by the SAME workflow identity `--workflow` already selects runs by (default
314
- // "CI"), read off disk rather than another `gh api` round trip (#262 budget).
315
- // --workflow-file stays as the explicit override for the one case discovery
316
- // cannot settle by itself: two workflow files sharing a name.
317
- const WORKFLOWS_DIR = ".github/workflows";
497
+ const baseOid = prInfo.baseRefOid;
498
+ vlog(` branch=${branch} head=${prHead} base=${prInfo.baseRefName}@${baseOid} state=${prInfo.state} mergeState=${prInfo.mergeStateStatus}`);
318
499
 
319
- // Anchored to the repo root, never to the cwd. Every other fact in this script
320
- // comes from `gh`, which resolves the repo from any depth, so a cwd-relative
321
- // read made the SAME repo answer `no-ci` from a subdirectory while answering
322
- // not-green from its root — and board.mjs spawns this with whatever cwd the
323
- // cockpit happens to have. `git rev-parse` is a local read, so anchoring costs
324
- // no REST call (#262). A root we cannot locate is exit 2, never `no-ci`:
325
- // absence has to be established, and failing to find the root establishes
326
- // nothing at all. Called only when discovery actually runs — an explicit
327
- // --workflow-file answers the question without a repo root and must not die
328
- // for want of one.
329
- function workflowsPath() {
330
- const root = tryRun("git", ["rev-parse", "--show-toplevel"])?.trim();
331
- if (!root) {
332
- die(`git rev-parse --show-toplevel failed — cannot locate ${WORKFLOWS_DIR}/ to answer whether this repo has CI`);
333
- }
334
- return `${root}/${WORKFLOWS_DIR}`;
500
+ const headOid = prRead.repo.head?.oid;
501
+ if (headOid !== prHead) {
502
+ die(`${headExpr} resolves to ${headOid ?? "nothing"}, not the PR head ${prHead} — the head moved mid-read; re-query rather than judge one commit's workflow against another's run`);
335
503
  }
336
504
 
337
- // Returns the workflow's path, or null ONLY where this repo genuinely has no
338
- // CI: no workflows directory, or a directory holding no YAML at all. Every
339
- // other outcome is die() (exit 2, "could not be answered") — the directory
340
- // unreadable, the target unreadable, or YAML present under other names. #111's
341
- // whole point is that absence must be DECLARED, never inferred from an error:
342
- // a repo whose CI is merely misconfigured must never read as one with no CI.
343
- function discoverWorkflowFile(dir, workflowName) {
344
- let entries;
345
- try {
346
- entries = readdirSync(dir);
347
- } catch (e) {
348
- // ENOENT is the one and only condition that means "no CI configured".
349
- // EACCES, ENOTDIR, ELOOP and friends all mean the directory is there and
350
- // we could not read it — unanswerable, exactly like the unreadable
351
- // workflow file below. The bare `catch` this replaced relabelled every one
352
- // of them `no-ci`, so a `chmod 000` on .github/workflows/ reported no-CI
353
- // for a repo whose CI run was `failure` — and exit 0 under --declare-no-ci.
354
- if (e.code === "ENOENT") return null;
355
- die(`cannot read ${dir}: ${e.message}`);
505
+ let baseTree;
506
+ const baseTip = prInfo.baseRef?.target;
507
+ if (isObject(baseTip) && baseTip.oid === baseOid && Object.hasOwn(baseTip, "file")) {
508
+ baseTree = dirAt(baseTip, "base", TIP_DIR, prRead.notFound);
509
+ } else {
510
+ const baseRead = graphql(BASE_QUERY, { dir: wfDir, baseExpr: baseOid }, [BASE_DIR]);
511
+ const got = baseRead.repo.base?.oid;
512
+ if (got !== baseOid) die(`the PR's base commit ${baseOid} reads back as ${got ?? "nothing"} — its workflow cannot be bound to it`);
513
+ baseTree = dirAt(baseRead.repo.base, "base", BASE_DIR, baseRead.notFound);
514
+ }
515
+
516
+ // One tree entry's YAML text, or null when the blob cannot be read whole:
517
+ // absent, binary, or truncated by the API. A truncated text is not a shorter
518
+ // workflow, so it is never parsed.
519
+ const blobText = (entry) => {
520
+ const o = entry.object;
521
+ return isObject(o) && o.__typename === "Blob" && typeof o.text === "string" && o.isTruncated === false ? o.text : null;
522
+ };
523
+
524
+ // The CI workflow in one commit's tree: `{ path, text }`, or null ONLY where
525
+ // that commit genuinely has none — no workflows directory (GitHub's NOT_FOUND
526
+ // for that path, see graphql()), a directory holding no YAML at all, or
527
+ // (explicit route) no entry at the named path. Every other
528
+ // outcome is die() (exit 2, "could not be answered"): the path not a
529
+ // directory, a YAML blob that cannot be read whole, two files sharing the
530
+ // workflow's name. Absence must be established, never inferred from a read
531
+ // that failed: a repo whose CI is merely misconfigured must never read as one
532
+ // with no CI.
533
+ //
534
+ // `side` settles the remaining case, YAML present but none of it carrying the
535
+ // workflow's name. At the base that is a --workflow/--workflow-file mismatch,
536
+ // not an absence — saying "no CI configured" of a directory full of workflows
537
+ // is false, and under --declare-no-ci it would exit 0 for a repo whose CI was
538
+ // never looked at. At the head it is a PR that removed or renamed its CI
539
+ // workflow, which contributes no jobs of its own.
540
+ function findWorkflow(tree, side) {
541
+ if (tree === null) return null;
542
+ if (!isObject(tree) || tree.__typename !== "Tree" || !Array.isArray(tree.entries) || tree.entries.some((e) => !isObject(e))) {
543
+ die(`${wfDir} at the ${side} commit is not a readable directory (got ${cut(JSON.stringify(tree) ?? "nothing")})`);
544
+ }
545
+ if (wfEntry !== null) {
546
+ const entry = tree.entries.find((e) => e.name === wfEntry);
547
+ if (!entry) return null;
548
+ const text = blobText(entry);
549
+ if (text === null) die(`cannot read ${wfDir}/${wfEntry} at the ${side} commit — not a file whose text came back whole`);
550
+ return { path: `${wfDir}/${wfEntry}`, text };
551
+ }
552
+ const yamls = tree.entries
553
+ .filter((e) => e.type === "blob" && /\.ya?ml$/.test(String(e.name)))
554
+ .map((e) => ({ name: e.name, path: `${wfDir}/${e.name}`, text: blobText(e) }));
555
+ const unreadable = yamls.filter((y) => y.text === null).map((y) => y.path);
556
+ if (unreadable.length) {
557
+ die(`cannot read ${unreadable.join(", ")} at the ${side} commit — the text came back absent, binary or truncated, so which workflow it is cannot be settled`);
356
558
  }
357
559
  const candidates = [];
358
- const yamls = [];
359
- const unreadable = [];
360
- for (const f of entries) {
361
- if (!/\.ya?ml$/.test(f)) continue;
362
- const path = `${dir}/${f}`;
363
- yamls.push(f);
364
- let text;
365
- try {
366
- text = readFileSync(path, "utf8");
367
- } catch (e) {
368
- // NOT fatal on the spot: this entry may be an unrelated sibling, and
369
- // dying on it blinds discovery to a target sitting readable right next
370
- // to it (one chmod-000 workflow made a green repo exit 2). Fail closed
371
- // only if nothing matched — then this file is the one that might have
372
- // been the CI workflow. The ambiguity check below sees readable files
373
- // only, so an unreadable second `CI` is invisible; a matched target wins.
374
- unreadable.push(`${path}: ${e.message}`);
375
- continue;
376
- }
560
+ for (const e of yamls) {
377
561
  // Top-level `name:` only (column 0) — a job's own `name:` step is indented
378
562
  // and expectedJobs() below already treats that as a different concern. The
379
563
  // optional ` #…` tail is a YAML comment, not part of the name: without it
380
564
  // `name: CI # main pipeline` parsed as a workflow called `CI # main
381
565
  // pipeline`, so a correctly configured repo reported no-ci. ` #` with the
382
566
  // space is what makes it a comment in YAML, so `name: CI#1` stays `CI#1`.
383
- const m = text.match(/^name:\s*(.+?)(?:\s+#.*)?\s*$/m);
567
+ const m = e.text.match(/^name:\s*(.+?)(?:\s+#.*)?\s*$/m);
384
568
  const name = m ? m[1].replace(/^['"]|['"]$/g, "") : null;
385
- if (name === workflowName) candidates.push(path);
569
+ if (name === workflow) candidates.push({ path: e.path, text: e.text });
386
570
  }
387
571
  if (candidates.length > 1) {
388
572
  die(
389
- `${candidates.length} workflow files under ${dir}/ are named '${workflowName}' (${candidates.join(", ")}) — pass --workflow-file to pick one`,
573
+ `${candidates.length} workflow files under ${wfDir}/ at the ${side} commit are named '${workflow}' (${candidates.map((c) => c.path).join(", ")}) — pass --workflow-file to pick one`,
390
574
  );
391
575
  }
392
576
  if (candidates.length === 1) return candidates[0];
393
- if (unreadable.length) {
394
- // Nothing matched, so an unreadable file could have been the match.
395
- die(`cannot read ${unreadable.join("; ")}`);
396
- }
397
- if (yamls.length) {
398
- // Workflows ARE configured here, just none under this name: a --workflow /
399
- // --workflow-file mismatch, not an absence. Saying "no CI configured" of a
400
- // directory full of workflows is a false statement, and if
401
- // --declare-no-ci let it through, it would hand the caller exit 0 for a repo
402
- // whose CI it never looked at.
577
+ if (yamls.length && side === "base") {
403
578
  die(
404
- `${yamls.length} workflow file(s) under ${dir}/ (${yamls.join(", ")}), none named '${workflowName}' — pass --workflow <name> or --workflow-file <path>`,
579
+ `${yamls.length} workflow file(s) under ${wfDir}/ at the ${side} commit (${yamls.map((e) => e.name).join(", ")}), none named '${workflow}' — pass --workflow <name> or --workflow-file <path>`,
405
580
  );
406
581
  }
407
- return null; // directory present, no workflow files in it — genuinely no CI
582
+ return null;
408
583
  }
409
584
 
410
- const workflowFile = workflowFileArg || discoverWorkflowFile(workflowsPath(), workflow);
585
+ // Whether the repo has CI at all is the base's to say: a PR adding a repo's
586
+ // first CI workflow still reads no-ci until that workflow is on the base.
587
+ const baseWf = findWorkflow(baseTree, "base");
588
+ if (baseWf === null && wfEntry !== null) {
589
+ die(`${wfDir}/${wfEntry} does not exist at the base commit ${baseOid} — an explicit --workflow-file is never read as no CI`);
590
+ }
411
591
  // No workflows at all, so this repo has no CI configured for ci-state to read.
412
592
  // That is its own verdict (`no-ci`), never the exit code reserved for "the
413
593
  // question could not be answered" — every way of failing to READ a workflow
414
- // (unreadable directory, unreadable file, malformed file) dies with exit 2
415
- // instead, above or via expectedJobs() below.
416
- const noCi = workflowFile === null;
594
+ // (a path that is not a directory, a blob not read whole, a malformed file)
595
+ // dies with exit 2 instead, above or via expectedJobs() below.
596
+ const noCi = baseWf === null;
417
597
  if (noCi) {
418
- vlog(` no workflow files under ${WORKFLOWS_DIR}/ — no-ci verdict`);
598
+ vlog(` no workflow files under ${WORKFLOWS_DIR}/ at the base commit — no-ci verdict`);
419
599
  }
420
600
 
421
- // --- Expected jobs, derived from the workflow file ------------------------
422
- // Never hardcoded: expectedJobs() parses the `jobs:` block of the workflow file
423
- // this run resolved (discoverWorkflowFile, or --workflow-file), so the expected
424
- // set tracks that file and follows it across repos. A reader asking whether an
425
- // empty `missing` is real should read that workflow for the current set. It is
426
- // deliberately not restated here: a set written into this comment is wrong the
427
- // moment a job is added.
601
+ // --- Expected jobs ----------------------------------------------------------
602
+ // Never hardcoded: the expected set is derived from the CI workflow's `jobs:`
603
+ // block as it stands at the PR's two commits, read above — H, the job ids at
604
+ // the head, and B, the job ids at the base. The run must carry every job in
605
+ //
606
+ // expected = H ∪ (D ∩ required), where D = B − H
607
+ //
608
+ // D is what the PR's own diff drops, and `required` is every status-check
609
+ // context the base branch's rules still require — its rulesets and classic
610
+ // branch protection together. So a PR may drop a CI job only once no rule a
611
+ // human owns still requires it: deleting a failing job is not a way to read
612
+ // green while the base still demands that job. A job the PR adds needs no
613
+ // clause of its own, since every job the run reports must succeed anyway.
614
+ // The rules are read only when some dropped job is also absent from the run;
615
+ // otherwise the answer cannot depend on them.
616
+ //
617
+ // A reader asking whether an empty `missing` is real should read that
618
+ // workflow at both commits for the current sets. They are deliberately not
619
+ // restated here: a set written into this comment is wrong the moment a job is
620
+ // added.
428
621
  //
429
622
  // Not built from the fleet's own prose instead: `integration-docker` — a job in
430
623
  // the agent-brain repo's CI workflow, which is on an internal GHE host and so
@@ -432,13 +625,7 @@ if (noCi) {
432
625
  // component dirs but here (`git grep -l integration-docker -- commands scripts
433
626
  // skills` matches only this file), so a
434
627
  // list built from those documents would have accepted a run missing it.
435
- function expectedJobs(file) {
436
- let text;
437
- try {
438
- text = readFileSync(file, "utf8");
439
- } catch (e) {
440
- die(`cannot read ${file}: ${e.message}`);
441
- }
628
+ function expectedJobs(text, label) {
442
629
  const ids = [];
443
630
  let inJobs = false;
444
631
  let sawNameOverride = false;
@@ -472,12 +659,52 @@ function expectedJobs(file) {
472
659
  // `sawNameOverride` stays false, and this function returns a verdict built
473
660
  // on an id the API no longer reports under.
474
661
  if (sawNameOverride) {
475
- die(`${file} sets a job-level 'name:' — job ids no longer match reported job names, derivation invalid`);
662
+ die(`${label} sets a job-level 'name:' — job ids no longer match reported job names, derivation invalid`);
476
663
  }
477
- if (ids.length === 0) die(`derived zero jobs from ${file} — refusing to answer`);
664
+ if (ids.length === 0) die(`derived zero jobs from ${label} — refusing to answer`);
478
665
  return ids;
479
666
  }
480
667
 
668
+ // The status-check contexts the base branch's rules require: every active
669
+ // ruleset's `required_status_checks` rule, plus classic branch protection's
670
+ // own list. Both are read because either alone can miss a requirement — a
671
+ // branch protected the classic way shows nothing under its rulesets. A
672
+ // dropped job counts as required when its id equals a context exactly; the
673
+ // app a context is pinned to plays no part. Either read failing is exit 2,
674
+ // never an empty set: an empty set would let every dropped job go.
675
+ function requiredContexts(branchName) {
676
+ const rulesPath = `repos/{owner}/{repo}/rules/branches/${branchName}`;
677
+ const pages = runJson("gh", ["api", rulesPath, "--hostname", host, "--paginate", "--slurp"], (v) => {
678
+ if (!Array.isArray(v) || v.some((page) => !Array.isArray(page))) return "expected pages of rules";
679
+ const rules = v.flat();
680
+ const bad = rules.findIndex(
681
+ (r) =>
682
+ !isObject(r) ||
683
+ (r.type === "required_status_checks" &&
684
+ (!Array.isArray(r.parameters?.required_status_checks) ||
685
+ r.parameters.required_status_checks.some((c) => !isObject(c) || typeof c.context !== "string"))),
686
+ );
687
+ return bad === -1 ? null : `rule ${bad} is not an object, or a required_status_checks rule without a list of contexts`;
688
+ });
689
+ const required = new Set();
690
+ for (const rule of pages.flat()) {
691
+ if (rule.type !== "required_status_checks") continue;
692
+ for (const c of rule.parameters.required_status_checks) required.add(c.context);
693
+ }
694
+ const protection = runJson("gh", ["api", `repos/{owner}/{repo}/branches/${branchName}`, "--hostname", host], (v) => {
695
+ if (!isObject(v) || !isObject(v.protection)) return `expected a branch carrying a protection object (${isObject(v) ? saw(v, "protection") : "not an object"})`;
696
+ const checks = v.protection.required_status_checks;
697
+ if (checks === undefined) return null;
698
+ if (!isObject(checks) || !Array.isArray(checks.contexts) || checks.contexts.some((c) => typeof c !== "string")) {
699
+ return `protection.required_status_checks.contexts is not a list of strings (${saw(v.protection, "required_status_checks")})`;
700
+ }
701
+ return null;
702
+ }).protection;
703
+ for (const c of protection.required_status_checks?.contexts ?? []) required.add(c);
704
+ vlog(` required by ${branchName}'s rules (${required.size}): ${[...required].join(", ")}`);
705
+ return required;
706
+ }
707
+
481
708
  // --- Find the run bound to this head --------------------------------------
482
709
  // `--limit 1` is wrong: the newest run on a branch is frequently a label or
483
710
  // policy workflow, which hides the CI result entirely. Filter by workflow, then
@@ -489,6 +716,7 @@ function expectedJobs(file) {
489
716
  const reasons = [];
490
717
  let jobs = [];
491
718
  let missing = [];
719
+ let dropped = [];
492
720
  let runId = null;
493
721
  let attempt = null;
494
722
  let runHeadSha = null;
@@ -502,12 +730,16 @@ if (noCi) {
502
730
  : `no workflows configured under ${WORKFLOWS_DIR}/ — pass --declare-no-ci once this repo is verified to gate on the reviewer's own suite run instead; absence never means pass`,
503
731
  );
504
732
  } else {
505
- // Derived here rather than above the no-ci fork: `expected` is read on this
506
- // arm alone, and the payload carries `missing`, not `expected`. Kept as this
507
- // arm's first statement — expectedJobs() refuses on an underivable workflow,
508
- // and that refusal belongs before the run query rather than after it.
509
- const expected = expectedJobs(workflowFile);
510
- vlog(` expected jobs (${expected.length}): ${expected.join(", ")}`);
733
+ // Derived here rather than above the no-ci fork: the job sets are read on
734
+ // this arm alone. Kept as this arm's first statements — expectedJobs()
735
+ // refuses on an underivable workflow at either commit, and that refusal
736
+ // belongs before the run query rather than after it.
737
+ const baseJobs = expectedJobs(baseWf.text, `${baseWf.path} at the base commit`);
738
+ const headWf = findWorkflow(dirAt(prRead.repo.head, "head", HEAD_DIR, prRead.notFound), "head");
739
+ const headJobs = headWf === null ? [] : expectedJobs(headWf.text, `${headWf.path} at the head commit`);
740
+ const droppedByHead = baseJobs.filter((j) => !headJobs.includes(j));
741
+ vlog(` head jobs (${headJobs.length}): ${headJobs.join(", ") || `none — no '${workflow}' workflow at the head`}`);
742
+ if (droppedByHead.length) vlog(` dropped by the head (${droppedByHead.length}): ${droppedByHead.join(", ")} — still expected where a base rule requires them`);
511
743
  const runs = runJson(
512
744
  "gh",
513
745
  ["run", "list", "--branch", branch, "--workflow", workflow, "--limit", "30", "--json", "databaseId,headSha,status,conclusion,event,createdAt"],
@@ -622,11 +854,19 @@ if (noCi) {
622
854
  if (status !== "completed") reasons.push(`run status is ${status}, not completed`);
623
855
 
624
856
  const present = new Set(jobs.map((j) => j.name));
625
- missing = expected.filter((e) => !present.has(e));
857
+ // A job the head dropped and the run lacks is excused only where no base
858
+ // rule still requires it, and only that case pays for reading the rules.
859
+ const absentDropped = droppedByHead.filter((j) => !present.has(j));
860
+ const required = absentDropped.length ? requiredContexts(prInfo.baseRefName) : new Set();
861
+ const stillRequired = absentDropped.filter((j) => required.has(j));
862
+ dropped = absentDropped.filter((j) => !required.has(j));
863
+ missing = [...headJobs.filter((e) => !present.has(e)), ...stillRequired];
626
864
  // An absent job reads as pending and is invisible in a checks summary. This is
627
865
  // the case a force-push creates: the run is cancelled, finished jobs keep their
628
866
  // conclusions, and the missing ones simply never appear.
629
- if (missing.length) reasons.push(`expected jobs absent from the run: ${missing.join(", ")}`);
867
+ if (missing.length) {
868
+ reasons.push(`expected jobs absent from the run: ${missing.map((j) => (stillRequired.includes(j) ? `${j} (dropped by the head's workflow, still required by the base ruleset)` : j)).join(", ")}`);
869
+ }
630
870
 
631
871
  // `skipped` is NOT `passed`. When the currency check fails, the heavy suites
632
872
  // report skipped — they did not execute.
@@ -642,67 +882,29 @@ if (noCi) {
642
882
  }
643
883
 
644
884
  // --- Behind-count ---------------------------------------------------------
645
- // `gh api` does NOT infer the host from the local remote the way `gh pr` and
646
- // `gh run` do — on a GitHub Enterprise repo it silently 404s against github.com.
885
+ // Uses the repository and host resolved above, so it reads neither again here.
647
886
  //
648
887
  // This block MUST NOT use run(): run()'s failure path calls die(), which calls
649
888
  // process.exit(2) and terminates before any surrounding catch can see it. An
650
889
  // earlier version wrapped run() in a try/catch here, which made the catch
651
890
  // unreachable — a transient failure on this purely informational side channel
652
- // hard-exited the tool and discarded a fully computed CI verdict. Use a helper
653
- // that returns null instead, so the behind-count can be unknown without costing
891
+ // hard-exited the tool and discarded a fully computed CI verdict. tryRun()
892
+ // returns null instead, so the behind-count can be unknown without costing
654
893
  // the caller the answer it actually asked for.
655
- //
656
- // GIT_DIR/GIT_WORK_TREE scrubbed (#1599, gitEnv()): this is the ONE spawn
657
- // primitive both of this file's git calls route through — `workflowsPath()`'s
658
- // `rev-parse --show-toplevel` above and `remote get-url origin` below — so
659
- // scrubbing it here protects both without a second copy. Harmless for the
660
- // `gh` calls also routed through it: neither name means anything to `gh`.
661
- // Measured: an ambient GIT_WORK_TREE alone answers `workflowsPath()`'s
662
- // `rev-parse --show-toplevel` with the AMBIENT path outright, silently, at
663
- // exit 0, regardless of the real cwd — sending workflow discovery to search
664
- // a directory that is not this repository at all. An ambient GIT_DIR alone
665
- // answers `remote get-url origin` for a DIFFERENT repository, silently, at
666
- // exit 0 — binding `gh api`'s `--hostname` to a repo the caller never named,
667
- // which behind-count's own comment above already treats as a 404 hazard for
668
- // an unrelated reason (GHE host inference) and this closes for a second.
669
- function tryRun(cmd, args) {
670
- vlog(`$ ${cmd} ${args.join(" ")}`);
671
- try {
672
- return execFileSync(cmd, args, { encoding: "utf8", env: gitEnv() });
673
- } catch (e) {
674
- // Same discipline as run(), and it matters more here: --quiet suppresses
675
- // vlog entirely, so under the controller's Monitor this line is discarded
676
- // and the interpolated stderr would have been paid for and then thrown
677
- // away. Name the cause; the child's own bytes already reached the caller.
678
- vlog(
679
- ` ${NAME}: ${cmd} failed: ${
680
- e.code ?? (e.signal ? `killed by ${e.signal}` : `exit ${e.status}`)
681
- }`,
682
- );
683
- return null;
684
- }
685
- }
686
894
 
687
895
  let behind = null;
688
896
  try {
689
- const remote = tryRun("git", ["remote", "get-url", "origin"]);
690
- const repoJson = remote === null ? null : tryRun("gh", ["repo", "view", "--json", "nameWithOwner"]);
691
- if (remote !== null && repoJson !== null) {
692
- const host = remote.trim().replace(/^(git@|https:\/\/|ssh:\/\/git@)/, "").replace(/[:/].*$/, "");
693
- const repo = JSON.parse(repoJson).nameWithOwner;
694
- const cmpJson = tryRun("gh", ["api", "--hostname", host, `repos/${repo}/compare/${base}...${prHead}`]);
695
- if (cmpJson !== null) {
696
- const cmp = JSON.parse(cmpJson);
697
- // Shaped like every other gh read here (#269), but fail-SOFT: a compare
698
- // reply without a numeric `behind_by` — a 404 body from the wrong host
699
- // or base is the live case — leaves `behind` null, this block's
700
- // documented unknown, instead of `undefined`, which JSON.stringify drops
701
- // from the payload entirely, taking the contract below and its
702
- // unknown-vlog with it. Still never dies: the probe stays advisory.
703
- behind = typeof cmp?.behind_by === "number" ? cmp.behind_by : null;
704
- vlog(` behind_by=${behind} (status=${cmp?.status})`);
705
- }
897
+ const cmpJson = tryRun("gh", ["api", "--hostname", host, `repos/${repoView.nameWithOwner}/compare/${base}...${prHead}`]);
898
+ if (cmpJson !== null) {
899
+ const cmp = JSON.parse(cmpJson);
900
+ // Shaped like every other gh read here (#269), but fail-SOFT: a compare
901
+ // reply without a numeric `behind_by` — a 404 body from the wrong host
902
+ // or base is the live case — leaves `behind` null, this block's
903
+ // documented unknown, instead of `undefined`, which JSON.stringify drops
904
+ // from the payload entirely, taking the contract below and its
905
+ // unknown-vlog with it. Still never dies: the probe stays advisory.
906
+ behind = typeof cmp?.behind_by === "number" ? cmp.behind_by : null;
907
+ vlog(` behind_by=${behind} (status=${cmp?.status})`);
706
908
  }
707
909
  } catch (e) {
708
910
  // JSON.parse of a malformed payload lands here; the subprocess failures are
@@ -732,22 +934,22 @@ const verdict = noCi ? "no-ci" : reasons.length === 0 ? "green" : "not-green";
732
934
  writeAll(2, `\n${NAME}: verdict=${verdict}${reasons.length ? ` — ${reasons.join("; ")}` : ""}\n`);
733
935
 
734
936
  // Compact, single-line: the consumer is an agent/script parsing JSON, and the
735
- // pretty view already went to stderr. On the quiet hot path drop `jobs` and
736
- // `missing` too — `reasons` already states every failing/absent job, so they
737
- // are pure duplication in the two longest-lived contexts that poll this.
937
+ // pretty view already went to stderr. On the quiet hot path drop `jobs`,
938
+ // `missing` and `dropped` too — `reasons` already states every failing/absent
939
+ // job, so they are pure duplication in the two longest-lived contexts that
940
+ // poll this.
738
941
  //
739
942
  // no-ci drops them unconditionally, quiet or not — never folded into the
740
943
  // `!quiet` check above, which is about duplication, not about what was read.
741
- // `jobs`/`missing` stay at their `let jobs = []`/`let missing = []`
742
- // initialisers on this path (the no-ci branch never reaches the run-binding
743
- // arm that assigns them), so shipping them read as "checked, nothing
744
- // missing" to a caller gating on `missing.length` when no workflow was ever
745
- // read to check against. `emitRateLimited()` above already answers the same
746
- // "nothing was read" question by omitting `jobs`/`missing` rather than
944
+ // They stay at their `let … = []` initialisers on this path (the no-ci branch
945
+ // never reaches the run-binding arm that assigns them), so shipping them read
946
+ // as "checked, nothing missing" to a caller gating on `missing.length` when no
947
+ // workflow was ever read to check against. `emitRateLimited()` above already
948
+ // answers the same "nothing was read" question by omitting them rather than
747
949
  // emitting them empty; this is the no-ci arm agreeing with it, one
748
950
  // convention for both places in this file that never bind a run.
749
951
  const payload = { pr, branch, prHead, runId, attempt, runHeadSha, status, conclusion, behind, verdict, reasons };
750
- if (!quiet && !noCi) Object.assign(payload, { jobs, missing });
952
+ if (!quiet && !noCi) Object.assign(payload, { jobs, missing, dropped });
751
953
  writeAll(1, `${JSON.stringify(payload)}\n`);
752
954
 
753
955
  // Exit vocabulary unchanged: 0 only when the gate is satisfied, 1 when it is