@feigi/fleet-ctl 3.24.40 → 3.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,7 @@ argument-hint: [pr-number]
13
13
  3. **Run `testCmd` before you commit**, from the worktree, copied verbatim — not a runner you picked. `testCmd` is the command your dispatcher handed you; **standalone, with no dispatcher to hand you one, it is the repo's own test command**, the Test entrypoint in the repo's Recipe cache (`derive-testcmd.sh <repo> test` prints it). Read it off the repo, never invent one: "not a runner you picked" is what this step forbids, and on the standalone path nothing else defines the referent. With no usable Recipe cache (`derive-testcmd.sh` refuses), run the Recipe derivation step first — dispatch a `task` member, agent `fleet-recipe-deriver`, its prompt naming the main checkout's absolute path as `<repo>` and a scratch directory of its own; it proves both commands in a throwaway worktree and writes the cache only on proof, and its `RECIPE NOT PROVEN` is a stop, reported with its reason. Never fall back to a runner of your own choosing. `tests 0` is a FAILED run, not a pass: a glob matching nothing still exits 0. **Zero is not the only no-work count.** A run reporting **0 passes with no failures** skipped everything it collected, and a count **materially below the whole suite** means you ran a partial tree — this suite reported `tests 937` when this line was written, so compare what you get against a full run rather than against zero. The number drifts; that is the safe direction, because a stale one produces a loud false red while its absence produces a silent false green. Red, zero-test, or either no-work count → fix it or move the finding to defer; never commit over it. Then commit and push — `git push origin HEAD:<branch>`, the explicit refspec: this step also runs from a `--detach` worktree (`run-team/SKILL.md`'s worktree-recreation form), where a bare `git push` exits 128 (`fatal: You are not currently on a branch`) and any push whose destination is `HEAD` rather than a full or branch refname (`-u` or not, forced or not) exits 1 (`error: The destination you provided is not a full refname`) — and report the test result alongside the SHA. **Then reconcile the PR body with what you actually did.** It merges into the permanent record and nothing downstream re-derives it: your commit messages are yours to fix and usually get fixed, the body is neither. Removing a change, or reversing one, leaves the body asserting work the diff no longer contains. Measured twice in one run — one body kept asserting a calibration its own fix had just deleted as false, another kept claiming a hunk the fix had removed as "this diff owns it" — both caught by a finisher's reading rather than by any rule, and both would otherwise have merged intact. `gh pr edit <pr> --body-file <path>`, and re-read the body against the final diff rather than against your memory of it. **Never `--no-verify`.** The fleet runs in repos it knows nothing about: it must not assume a pre-commit hook exists, and must never bypass one that does — a hook that fails is a finding to report, not an obstacle. Nothing re-reviews what you commit here, so this run is the only gate between your edit and a merge.
14
14
  4. **Under the fleet, do not hold this wait.** The controller owns a persistent CI Monitor and dispatches a finisher once your report has arrived and CI is green — so push, then report to the controller a **final verdict** (every specialist you dispatched + its outcome + your apply/defer adjudication + the pushed SHA) and stop. A specialist that has neither reported nor been relayed to you is not a verdict line — ask the controller for it by name before ruling; see **Specialists**. The controller keys "review complete" on that verdict, **never on you merely going idle** — a slow specialist can still be running when your turn ends, and finishing off idle-alone ships a premature label (observed: a PR labelled while its contract-test specialist was still running and about to surface a vacuous pin). A turn-based reviewer re-reading `gh pr checks` each idle cycle rebuilds its whole context for nothing the Monitor lacks. **Standalone (no controller): watch** the run until the diff-validating jobs are green (bind via `ci-state.mjs` below); fix a **genuine** failure and repeat from 3. **Staleness is not a failure:** a `rebase-check` red or heavy jobs `skipped` **solely from a non-zero behind-count** never clears by waiting and must not be rebased away here — see **`skipped` is not `passed`** and **Do NOT rebase to label** below for what it looks like and why. Stop watching and go to 6. A turn-based reviewer that "waits for green" on a behind PR stalls forever and ends its turn without labelling. **`ci-state.mjs` returns `verdict: "no-ci"`** → there is no run to watch, so don't: go straight to 6 and let that step's `--declare-no-ci` branch decide.
15
15
  5. File each deferred finding: `gh issue create --label <ready-for-agent|needs-triage>` with the finding, `file:line`, why deferred, `Deferred from PR #<pr> review`, and **the finding's `dimension` in the issue body** — the review returns it on every finding, and a backlog that does not carry it cannot be attributed to the specialist that generated it. **The label follows the finding's state, not this step** — but it is never omitted; an unlabelled issue is invisible to both `candidates.mjs --require-label` and the cockpit's pool query, reachable only by a human. **The bar here is whether the DEFECT is confirmed — never whether the remedy is settled.** Confirmed defect with the remedy still open → `ready-for-agent`, and say in the body that the remedy is open. Torn → `needs-triage`, narrowed: torn means **unsure anything is broken**, not unsure how to fix it. **A finding a refuter CHECKED and did not survive is neither** — it is not a confirmed defect, and you are not unsure whether anything is broken: you measured that nothing is. Refutations go as **one issue per review, titled `PR #<pr> review: the suggestion band, checked`, labelled `wontfix`, and CLOSED** — a run that files them open instead has to be corrected afterwards, as one was on 2026-08-27. Left open they read as queued agent work and rot into filing artifacts; a measured triage pass found a quarter of its `needs-triage` backlog was refuted records, bulk-closable by title shape. Closed is still a durable home — `check` reads the tracker at `--state all`, so a future run re-deriving the finding lands on the evidence rather than re-litigating it. Split the band only where an entry is **not** a refutation: a residual the refuter surfaced, or a finding refused as out of scope and never checked, is real deferred work — and real deferred work earns its own open issue only past a second bar. **Worth a claim: a finding whose own claim is that correct code could be shaped better — style, naming, layout, redundancy, a micro-simplification — never gets its own open issue.** Its only open question is "is this worth doing?", which answers itself under the repriced triage bar: measured 2026-08-15→31, 133 issues were triage-closed `wontfix` in sixteen days, 121 of them review deferrals, mostly this shape. Append it to the same closed record issue under a `Below the claim bar` heading — `file:line`, dimension, the claim, and a re-open trigger per entry. Closed is a durable home for these too: `check` reads `--state all`, so a run re-deriving the finding lands on the record instead of re-filing — and a later review returning the same finding as `survived`, or a maintainer hitting it, is the promotion signal: file it open then, citing the record. **An in-scope rediscovery step 2 applied is that same promotion signal, and it files nothing** — so the record carries no mark unless you write one: run `check` over each finding step 2 applied as well, and where its tracker rows put one on a `Below the claim bar` entry, comment on that record issue, opening `Promoted — applied, not filed`, and name the entry, that its refuter let it through, and the commit carrying the fix. That comment is the promotion mark this path leaves, and it is **not** a cross-reference — measured on this tracker, a comment mints `cross-referenced` on the issue its own text *names*, never on the issue it sits under (a comment citing a second issue landed on that issue's timeline and nowhere else), so the fixed opening is what carries the signal instead. **The bar reads the finding's claim, never its review band** — a finding that alleges wrong behavior, whatever band it sat in, `unverified`-with-crashed-refuters included, is above this bar and files open under the confirmed/torn split, which is why a band cannot carry this decision. Do **not** reach for phase 0's **decided?** test here. That is a *consumption* gate, priced for a seat where implementer divergence costs a claim, a worktree and a dispatch; at filing time divergence costs one PR review the maintainer already runs. Same test, two seats, opposite correct answers — and reading it in this seat took `needs-triage` from 11 to 135 before it was repriced (ruled 2026-08-18). **Dedupe through `~/.fleet/bin/fleet-run ledger.mjs check "<subject>"`, never a bare `gh issue list --search`** — the duplicate class that guard exists to catch was filed from *here*: the ledger row for the finding rediscovered five times in one measured run carries a reviewer's own source tag, `(review-pr-108)`. `check` reads this run's filed list *and* the tracker at `--state all`, so a closed duplicate still counts. Exit **1** is already filed in this run; exit **3** is a clean ledger with matching tracker rows that score against the subject — read the ones it prints and comment on the existing follow-up rather than filing a second issue. **Exit 0 is not automatically "safe to file"**: it covers `clean`, `soft-hit` and `unverified` alike, and an unreachable `gh` degrades to a ledger-only answer that says `TRACKER NOT CHECKED`, so read the stdout `verdict` to tell a tracker that was searched and clean from one nobody read — under `unverified`, search it yourself before filing — or, for the applied-promotion comment above, before treating a tracker nobody could read as a reason to skip it. **`soft-hit` is the answer that costs most to misread**: it means related rows were found and none of them was established as a duplicate — a near-miss above the floor, or tracker rows the scorer rates 0.00 — so read the rows it printed and decide, and never treat that exit 0 as permission. Exit **2** is a usage error, meaning nothing was checked at all: fix the invocation and re-run, never read it as a duplicate. Full exit-code and `verdict` semantics live in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s **Run ledger** section — read them there rather than restating them here. **The guard dedupes, it never drops:** a duplicate becomes a comment on the issue that already covers it, never a dropped finding. **Record every issue you create, at once:** immediately after each `gh issue create`, run `~/.fleet/bin/fleet-run ledger.mjs filed <N> "<subject>"` — `<N>` the number `gh issue create` printed, and **the same subject string you passed to `check`**, so the next `check` for that finding meets it in the filed list instead of scoring a rewording. Without it the guard's ledger half never holds a row, and its exit **1** can never fire. If `filed` fails, retry it once; if it fails again, leave the issue alone — it exists and is correct — and report it as `unrecorded: #N <subject>`, so the controller runs `filed` for it. Report `filed: #N <subject>` for every issue you created — under the fleet, in your report to the controller. **The one window the guard cannot see:** `check` → `gh issue create` → `filed` is three commands, and the ledger's lock covers each alone, so two filers can both read `clean` in the seconds before either records. That gap is accepted, never a reason to skip `filed`. Post the numbers as one PR comment.
16
+ **Name where each deferral went, in the disposition record.** Every entry you defer carries `issue`: the number of the issue you filed it to, commented it onto, or appended it to — the closed `PR #<pr> review: the suggestion band, checked` record included. An in-scope `suggestion`'s entry — an `unverified` finding with `refutersDispatched` of zero — also carries `verdictPath`, applied or deferred: the absolute path of a file holding its refuter's verdict as JSON, `{"refuted": <boolean>, "reason": "<string>"}`, under your own `<scratch>/pr<N>/fix-XXXXXXXX/<finding>/` run root. `dispositions-check.mjs` reads each named issue back through `gh issue view --json labels,state,title` and each verdict file off disk; a mismatch names the row of its filing table the entry broke, so move or relabel that filing to the home the row names and run the check again. With `gh` unreachable, or an issue it cannot read, that filing goes unchecked: with nothing else broken the verdict is `unchecked` — never `ok`, and it exits 1 — so run the check again once `gh` answers.
16
17
  6. Diff-check green (run-bound per `ci-state.mjs`; under staleness see **`skipped` is not `passed`** for what the label then rests on) **and** deferrals filed **and** the PR carrying exactly one release label (`patch`/`minor`/`major`, counting only those three; **required on every PR** — `release-label.yml` auto-adds `patch` when none is present and hard-fails on more than one, so this never needs to check whether the repo defines the gate at all, and `gh label list` settles nothing here any more) **and** `dispositions-check.mjs --member fix-pr-<pr> --scratch <scratch>` run over your own record exiting 0 (standalone that is yours to run, from the worktree, after step 2 writes `<scratch>/dispositions-<pr>.json`; it reads the review file beside it, which you write yourself from the findings step 1 collected, in the shape **The review result file** describes — `pr`, `head`, `snapshot`, `counts` and the `survived`, `refuted` and `unverified` buckets; standalone you pass `--no-ledger`, so it writes no token and the exit status is the verdict — a `.fleet/ledger.md` the repository already holds is a previous run's, and without the flag it exits 2 for a ledger with no row for you; under the fleet `ledger.mjs dispatch` has already refused a finisher without it) → `gh pr edit <pr> --add-label ready-to-merge`. Do not merge. A non-zero dispositions exit halts you before the label, and you report the violations it printed. Zero or more than one release label halts you before the label, naming which you found — a timed-out `gh pr create` opens the PR with its `--label` unapplied and no exit status to react to, and nothing after this step re-derives the release label. **Under the fleet a finisher does this** — a fresh small agent the controller dispatches (after your final verdict, never on your bare idle). Gate it on the diff-validating **`check`** job, **not** on `ci-state --quiet` exit 0, which a behind PR — the normal case once any sibling merges — never reaches: a `rebase-check` red or heavy jobs `skipped` off the behind-count hold it short of full green, so an exit-0 gate strands every behind PR unlabelled. Label when `check` is present and green **and no heavy job (the diff-validating suites — *not* the `rebase-check` currency gate) is in `failure`** — a `skipped` heavy job is behind-count staleness and fine — **solely** off that count, which is a condition to establish rather than infer, see the five-condition note in `$(~/.fleet/bin/fleet-run --root)/skills/run-team/SKILL.md`'s fix-applier prompt block. A `failure` is the diff's own fault and blocks the label, else a genuinely broken PR gets labelled off a green `check` and burns a merge-bot rebase+CI cycle before the failure resurfaces. Read per-job state for this: run `ci-state.mjs` **without** `--quiet`, or read its `jobs` — the `--quiet` payload drops the per-job `jobs`/`missing` and the `dropped` list, keeping `reasons` (which still distinguishes `is failure` from `is skipped`). You reach step 6 yourself only when green is already in hand at push time.
17
18
 
18
19
  **`verdict: "no-ci"` — this repo has no `check` job to gate on at all**, and that is a different state from red or unknown, not a third way to skip the wait. Label off step 3's own green `testCmd` run instead of a `check` job that will never exist — and only once `ci-state.mjs` reads `no-ci` **without** the flag, since a repo whose CI is merely misconfigured exits 2 there rather than reading no-ci. `--declare-no-ci` is your caller-side declaration that step 3's run **is** this repo's gate: it flips the exit code and echoes itself into `reasons`, so finding it in the payload confirms only that you passed it, never that anyone verified anything. **No green `testCmd` run on record → do not label.** Say in your verdict that the repo has no CI configured and no declaration, and stop — inferring a pass from silence here is exactly the misconfigured-CI case the declaration exists to rule out. See `ci-state.mjs --pr <n> --declare-no-ci` below.
@@ -6,7 +6,7 @@ Set the goal, then work it until no open PR is left:
6
6
 
7
7
  `/goal Merge all of this repo's open PRs in numeric order if labeled ready-to-merge. Rebase -> Wait for checks green -> check for the ready-to-merge label -> merge if labeled. Never merge past a lower-numbered PR whose work is related — wait for its label instead.`
8
8
 
9
- Only `ready-to-merge` PRs are in scope — it is the author's sign-off. Never add the label yourself.
9
+ Only `ready-to-merge` PRs are in scope — it is the author's sign-off. Never add the label yourself. A PR-body line `main-gain-removal: <path> <key> - <why>` is a second sign-off, scoped to one file and one landing source: it lets through the removal of lines `main` gained after the PR began in that file from that source, and nothing else (step 3's `main-gain-removed`).
10
10
 
11
11
  ## Order, and the hold rule
12
12
 
@@ -189,6 +189,8 @@ For each labeled PR clearing the hold rule, lowest first:
189
189
 
190
190
  `<text>` is everything after the key, verbatim — `row` rewrites the whole line, so a token you drop is gone. `#<pr>` is this PR, never the one it conflicts with; the tick refuses a hold naming another PR. The `(conflict: …)` note is free text, comma-joined paths from the `diff --name-only` read above — placed *after* the token, never before, so it cannot fall inside `PR_MENTION`'s first-match binding or `CONFLICT_HOLD`'s own pattern. From then on the tick prints `DISPATCH fix-pr PR#<pr>` for it and counts it in `held=` until a fix-applier dispatched after the hold settles `applied:`/`no-op`. Skip the `row` write on an already-unresolved hold, per the paragraph above — nothing else about this path changes: still report `rebase-fallback-#<pr>`, still hand it back.
191
191
 
192
+ **The fallback's "verified" needs a clean main-gain check on the local rebased head.** Save the PR body to `<scratch>/pr<N>/merge-bot-<n>/body.md` (`gh pr view <pr> --json body -q .body`) and, from the main checkout, run `~/.fleet/bin/fleet-run main-gain.mjs --head "$(git -C <worktree> rev-parse HEAD)" --body-file <scratch>/pr<N>/merge-bot-<n>/body.md`. Exit 0 is the only clean result; name every `acknowledged[]` entry, with its reason, in the hand-back. Exit 1 (a line `main` gained after the PR began would be removed) or exit 2 (it could not answer) is reported inside `rebase-fallback-#<pr>` — the hits and each one's `ack` line to copy, or the `reason` it could not answer — and the fallback is never reported verified.
193
+
192
194
  2. Watch checks settle **on the rebased head**. A missing release label (`patch`/`minor`/`major`) fails `validate-release-label` — add the one matching; `release-label.yml` defines that job and exits 1 when the count of those three is zero. A stale `rebase-check` failure usually means step 1 has not landed. Where a repo chains jobs behind that check with `needs:`, they come back `skipped` rather than red and the currency check is the only thing to fix — check `ci.yml` for a `needs:` chain before assuming that: it declares none as of this reading, so no job is currently skipped behind `rebase-check`.
193
195
 
194
196
  **Hold the wait inside one blocking call — you are turn-based and cannot "keep an eye on" a run.** If you push and then end your turn, your pass stops there and nothing resumes it: whatever wakes you is external and may never come. Observed repeatedly — a bot rebases, pushes, goes idle, and the queue silently stalls with the PR one command from merging. Block instead, on the run step 3's first gate reading names — its `ci.runId` — the wait:
@@ -210,7 +212,9 @@ For each labeled PR clearing the hold rule, lowest first:
210
212
  --out <scratch>/pr<N>/merge-bot-<n>/ci.json; rc=$?
211
213
  ```
212
214
 
213
- `--pre` is the head you recorded at **The labelled head**; `--post` is the head step 1's rebase produced — omit it when no rebase ran, which is the same as passing `pre` twice. `pr<N>` is this PR and `merge-bot-<n>` is your own name, so the reading lands under a directory only you write, never in the scratch root by itself: that root is injected into every dispatched member and shared with every sibling. The gate is read-only — it runs the instrument re-check, `gh pr view <pr> --json labels,reviewDecision,headRefOid` and `ci-state.mjs --pr <pr>`, answers their conjunction, and never merges, labels, rebases or waits. Stdout is exactly one JSON line, `{pr, verdict, reason, head, pre, post, behind, instruments, ci}`; stderr is its children's diagnostics, so never fold `2>&1` into the line you read. Read `rc` straight off the call, as above — never through a pipe.
215
+ `--pre` is the head you recorded at **The labelled head**; `--post` is the head step 1's rebase produced — omit it when no rebase ran, which is the same as passing `pre` twice. `pr<N>` is this PR and `merge-bot-<n>` is your own name, so the reading lands under a directory only you write, never in the scratch root by itself: that root is injected into every dispatched member and shared with every sibling. The gate is read-only — it runs the instrument re-check, `gh pr view <pr> --json labels,reviewDecision,headRefOid,body`, the main-gain check against that head in the main checkout, and `ci-state.mjs --pr <pr>`, answers their conjunction, and never merges, labels, rebases or waits. Stdout is exactly one JSON line, `{pr, verdict, reason, head, pre, post, behind, instruments, mainGain, ci}`; stderr is its children's diagnostics, so never fold `2>&1` into the line you read. Read `rc` straight off the call, as above — never through a pipe.
216
+
217
+ **Run a plain `git fetch origin` in the main checkout before every gate run** — never `git fetch origin <src>:<dst>`, for the reason step 1's fallback gives. The main-gain check reads `origin/main` and the PR head object there as they stand and fetches nothing itself: an unfetched head is `main-gain-unanswerable`, and a stale `origin/main` is a check against the wrong `main`.
214
218
 
215
219
  1. **Run it.** Exit 0 → go to 2. Exit 1 with a `ci:…` `reason`, `ci.runId` set and `ci.status` not `completed` → the run has started but not finished: wait on `ci.runId` (step 2), then run it again. Exit 1 with `ci.runId` **null** (`reason` starts `no CI run whose headSha equals`) → GitHub has not yet registered a run for this head at all — right after `gh pr update-branch --rebase`, the id step 2's wait blocks on does not exist yet, so never route this into step 2's `gh run view <run-id>` poll with a null id. Wait 15s and run the gate again instead, capped at 20 attempts (~5 minutes); no run within that cap → skip the PR and report `<reason>-#<pr>`, the same as any other exit 1. Any other exit 1 → skip the PR, report `<reason>-#<pr>` (`head-moved-after-label-#<pr>`, `label-pulled-#<pr>`, `changes-requested-#<pr>` …), leave the label where it is, and move on. Exit 2 → stop on that PR and report `<reason>-#<pr>`: the gate could not evaluate — a finding about the tree, the tooling or the API, never about the PR. Re-run once only for `rate-limited`, a quota refusal that clears by itself.
216
220
  2. **Run it again immediately before `gh pr merge`, and merge only on that second exit 0.** Anything else takes the same arms as 1, and nothing merges.
@@ -218,6 +222,8 @@ For each labeled PR clearing the hold rule, lowest first:
218
222
  Each `reason` is a fact the gate now enforces, not a step you run:
219
223
 
220
224
  - **`head-moved-after-label`** — the PR head is neither `pre` nor `post`. **Any third SHA is a push that landed while you waited on CI, and no CI check can see it**: `ci-state.mjs` selects the run whose `headSha` equals the *current* PR head (`scripts/ci-state.mjs`, the `r.headSha === prHead` filter), so a member's push plus its own green run satisfies every CI check while the audit behind the label belongs to a tree that is gone. The remedy is a fresh finisher against the new head, label untouched.
225
+ - **`main-gain-removed:<path>`** — merging this head would remove lines `main` gained after the PR's work began: lines a later merge landed, deleted by a branch commit that every rebase since has replayed without a conflict, so no conflict preview and no `origin/main...HEAD` read is sure to show them. `mainGain.hits[]` names each file, the landing key (`#<n>` for a merged PR, else the landing commit's 12-character SHA), the removed lines, and the `ack` line to copy. Skip the PR, leave the label alone, and report `main-gain-removed:<path>-#<pr>` with the hit list and the keys. Never restore the lines yourself — the removal may be deliberate. It clears when the PR stops removing them or its body carries `main-gain-removal: <path> <key> - <why>` for every hit; the gate reads the body each run, so editing it is enough. An acknowledged removal is listed in `mainGain.acknowledged[]` and the gate passes it — name each one, with its reason, in your report.
226
+ - **`main-gain-unanswerable`** — the main-gain check could not answer: a head object the main checkout does not hold after `git fetch origin`, a merge that does not resolve cleanly, a blame that failed. `mainGain.reason` says which. Stop and report `main-gain-unanswerable-#<pr>` with it, label untouched.
221
227
  - **`behind:<n>`** — you are the only place currency is proven, and a sibling merge since your rebase expires it (the staleness below).
222
228
  - **`instrument-set-changed` / `instruments-unanswerable`** — the instrument re-check the controller runs before its own gates (`run-team/SKILL.md`, **You read your instruments out of a tree every member can write to**), taken at this seat because nothing dispatches a merge bot to read that rule. Report `<reason>-#<pr>` with what the gate printed, leave the label alone, and do **not** re-run the gate.
223
229
  - **`ci:…`** — bound to the *run*, not to check conclusions. `gh pr checks` aggregates across runs and reports a `pass` inherited from a **cancelled** run on a superseded SHA; head-SHA binding alone misses it, since the head is right and only the conclusions belong elsewhere. `ci-state.mjs` binds run head, `status`, and every expected job from one query, and reports non-green unless the run's head matches the PR head, `status` is **completed**, and every expected job is present and succeeded. That presence requirement is what catches the case above — a force-push cancels the run under you, its finished jobs go on reporting what they concluded, and whatever never ran is missing from the run entirely, which reads as `pending` in an aggregating checks summary, never here: `ci-state.mjs` names it in the reason `expected jobs absent from the run: …` and refuses green.
@@ -262,12 +268,14 @@ Measured over one three-merge pass: the next queue member went 0 → 2 → 7 →
262
268
 
263
269
  **A PR whose heavy jobs have only ever `skipped` is getting its first real verification from your rebase.** Reviewers may legitimately have labelled on the checks that did run plus local evidence, saying so explicitly. When your post-rebase run finally executes those suites, treat a red there as a **genuine first result**, not a regression you caused — read the failing job before concluding, and do not hand it back as "the rebase broke it".
264
270
 
265
- Report merged / skipped-unlabeled / held-behind-#X / worktree-diverged-#X / head-moved-after-label-#X / label-drop-failed-#X / label-read-failed-#X / branch-delete-failed-#X / branch-kept-#X (X the open PR that keeps the merged branch — a keep, not a failure) / rebase-fallback-#X / instrument-set-changed-#X / `<reason>-#X` for any other gate refusal / blocked after the pass — a dispatched bot once, at exit, after its grace (**Grace, then one report**, below).
271
+ Report merged / skipped-unlabeled / held-behind-#X / worktree-diverged-#X / head-moved-after-label-#X / main-gain-removed:<path>-#X / label-drop-failed-#X / label-read-failed-#X / branch-delete-failed-#X / branch-kept-#X (X the open PR that keeps the merged branch — a keep, not a failure) / rebase-fallback-#X / instrument-set-changed-#X / `<reason>-#X` for any other gate refusal / blocked after the pass — a dispatched bot once, at exit, after its grace (**Grace, then one report**, below). Every acknowledged main-gain removal the gate passed is named in the report, with its reason.
266
272
 
267
273
  ## No-undo audit (before every rebase)
268
274
 
269
275
  A rebase resolved the wrong way silently reverts work already in `main`. It looks like an ordinary conflict resolution and passes CI, because the branch's own tests never covered what it undid. Never resolve blind.
270
276
 
277
+ This audit is the pre-rebase half and sees only what conflicts. A deletion of lines `main` gained, already written into a branch commit, replays cleanly and never conflicts, so the audit never sees it; the **main-gain check** is the post-rebase counterpart that does — step 3's `main-gain-removed` row, and the fallback's "verified" in step 1.
278
+
271
279
  **1-3. Do not destroy unpushed work, preview conflicts, and name the work at risk** — what `main` gained in the conflicting files since the branch forked:
272
280
 
273
281
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.24.40",
3
+ "version": "3.26.0",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -14,6 +14,8 @@
14
14
  // or a rule broke and an earlier
15
15
  // fix-applier's record on the same
16
16
  // review already had
17
+ // dispositions-unchecked=fix-pr-<M>[-x]:<head> no rule broke, but where a deferral was
18
+ // filed could not be read
17
19
  //
18
20
  // `<head>` is the review file's `head` — the review the record answers — so a
19
21
  // verdict on one review never answers a later one.
@@ -61,12 +63,52 @@
61
63
  // is escalated rather than passed: the verdict is `escalate`, and the
62
64
  // output names each such finding. A `suggestion` passes as `ok`. A record
63
65
  // that also breaks a rule is a `mismatch`, its escalations printed too.
66
+ // - Refuter evidence: an in-scope suggestion — an `unverified` finding no
67
+ // refuter was dispatched against (`refutersDispatched` zero or absent),
68
+ // in scope by the presumption above or by its entry — needs
69
+ // `verdictPath`: an absolute path to a file under the fix-applier's own
70
+ // run root, `<scratch>/pr<N>/fix-XXXXXXXX/<finding>/`, holding a JSON
71
+ // object that validates against the refuter verdict schema
72
+ // `{refuted, reason}`. No `verdictPath`, a path outside that root, a file
73
+ // missing, or one failing the schema is a mismatch. `refuted: true` puts
74
+ // the finding on filing row 4, where applying it is a mismatch too;
75
+ // `refuted: false` on row 5.
76
+ // - Filing: every deferral names in `issue` the issue it was filed to, and
77
+ // that issue — read back through `gh issue view --json
78
+ // labels,state,title` — must be its finding's home in this table. A
79
+ // mismatch names the row the entry broke:
64
80
  //
65
- // Exit status: 0 ok; 1 mismatch or escalate; 2 nothing judged and nothing
66
- // written — a bad flag, an unreadable or malformed review file, a record file
67
- // that exists but cannot be read, a git or ledger failure. A missing or
68
- // unparseable RECORD is judged, not refused: the fix-applier wrote nothing a
69
- // reader can use, so every finding it had to cover is dropped.
81
+ // row finding home
82
+ // 1 survived, deferred for an allowed reason other open, ready-for-agent
83
+ // than false-rationale
84
+ // 2 survived, deferred false-rationale closed suggestion-band record
85
+ // 3 unverified, its refuters dispatched and crashed open, needs-triage
86
+ // 4 in-scope suggestion, its refuter refuted it closed suggestion-band record
87
+ // 5 in-scope suggestion, its refuter let it survive applied, or deferred as row 1
88
+ // 6 out-of-scope suggestion alleging wrong behavior open, needs-triage
89
+ // 7 claimKind shape, below the claim bar closed suggestion-band record
90
+ //
91
+ // Row 4 outranks row 7, and row 7 every other row. A row-5 deferral is
92
+ // held to row 1's reasons: one of ALLOWED_DEFER other than
93
+ // false-rationale, `remedy-outside-diff` under the rule above. An open
94
+ // home carries its row's triage label and not the other one; the closed
95
+ // suggestion-band record is the closed issue titled `PR #<pr> review: the
96
+ // suggestion band, checked`, labelled `wontfix`. `claimKind` is trusted:
97
+ // the script never judges whether a claim is about shape. A survived
98
+ // finding out of scope has no row, and its deferral's filing is not
99
+ // judged.
100
+ //
101
+ // Unchecked: `gh` unreachable, or a deferral's issue it cannot read, leaves
102
+ // that entry's filing unjudged. With no rule broken and nothing escalated the
103
+ // verdict is `unchecked`, which `ledger.mjs dispatch` refuses a finisher on —
104
+ // never ok, and never a mismatch, since the record broke nothing. Run the
105
+ // check again once `gh` answers.
106
+ //
107
+ // Exit status: 0 ok; 1 mismatch, escalate or unchecked; 2 nothing judged and
108
+ // nothing written — a bad flag, an unreadable or malformed review file, a
109
+ // record file that exists but cannot be read, a git or ledger failure. A
110
+ // missing or unparseable RECORD is judged, not refused: the fix-applier wrote
111
+ // nothing a reader can use, so every finding it had to cover is dropped.
70
112
  //
71
113
  // Without a ledger the record is judged all the same and the exit status is
72
114
  // the whole verdict: no token is written, no row is read, and `token` in the
@@ -83,15 +125,16 @@
83
125
  // written. `--no-ledger` names that state outright: no ledger is looked for,
84
126
  // whatever the repository holds, and it contradicts `--ledger`.
85
127
 
86
- import { readFileSync, existsSync, lstatSync } from "node:fs";
128
+ import { readFileSync, existsSync, lstatSync, realpathSync, statSync } from "node:fs";
87
129
  import { execFileSync } from "node:child_process";
88
- import { join, dirname, isAbsolute, relative, posix } from "node:path";
130
+ import { join, dirname, isAbsolute, relative, posix, sep } from "node:path";
89
131
  import { fileURLToPath } from "node:url";
90
132
  import { makeDie, defineFlags } from "./arg.mjs";
91
133
  import { isCLI } from "./is-cli.mjs";
92
134
  import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
93
135
  import { parseMember, memberTokens } from "./ledger-grammar.mjs";
94
136
  import { dispositionsToken, rowNums, sameHead } from "./fleet-tick.mjs";
137
+ import { VERDICT_SCHEMA } from "./review-core.mjs";
95
138
 
96
139
  const NAME = "dispositions-check";
97
140
  const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
@@ -107,6 +150,51 @@ const COVERED = ["survived", "unverified"];
107
150
  const BUCKETS = [...COVERED, "refuted"];
108
151
  const ENUMS = { scope: ["in", "out"], claimKind: ["behavior", "shape"], disposition: ["apply", "defer"] };
109
152
 
153
+ // The filing table: a deferral's home by its finding's state. `record` is the
154
+ // closed suggestion-band record; `open` the triage label an open home carries.
155
+ export const FILING_ROWS = Object.freeze({
156
+ 1: { finding: "a survived finding deferred for an allowed reason other than false-rationale", open: "ready-for-agent" },
157
+ 2: { finding: "a survived finding deferred false-rationale", record: true },
158
+ 3: { finding: "an unverified finding whose refuters crashed", open: "needs-triage" },
159
+ 4: { finding: "an in-scope suggestion its refuter refuted", record: true },
160
+ 5: { finding: "an in-scope suggestion its refuter let survive", open: "ready-for-agent" },
161
+ 6: { finding: "an out-of-scope suggestion alleging wrong behavior", open: "needs-triage" },
162
+ 7: { finding: "a finding whose claim is about shape, below the claim bar", record: true },
163
+ });
164
+ const TRIAGE_LABELS = ["ready-for-agent", "needs-triage"];
165
+ // Row 1's reasons, which a row-5 deferral is held to.
166
+ const ROW_1_DEFER = ALLOWED_DEFER.filter((r) => r !== "false-rationale");
167
+ export const recordTitle = (pr) => `PR #${pr} review: the suggestion band, checked`;
168
+
169
+ function homeText(row, pr) {
170
+ return row.record ? `the closed "${recordTitle(pr)}" issue, labelled wontfix` : `an open issue labelled ${row.open}`;
171
+ }
172
+
173
+ // Whether an issue `{state, title, labels}` is `row`'s home on PR `pr`.
174
+ function homeHolds(row, { state, title, labels }, pr) {
175
+ if (row.record) return state === "CLOSED" && title.trim() === recordTitle(pr) && labels.includes("wontfix");
176
+ return state === "OPEN" && labels.includes(row.open) && !labels.includes(TRIAGE_LABELS.find((l) => l !== row.open));
177
+ }
178
+
179
+ function describeIssue({ state, title, labels }) {
180
+ return `${state.toLowerCase()}, titled ${JSON.stringify(title)}, labelled ${labels.length === 0 ? "nothing" : labels.join(", ")}`;
181
+ }
182
+
183
+ // Why `value` is not a refuter verdict, or null when it is: the shape
184
+ // VERDICT_SCHEMA declares, checked key by key.
185
+ export function verdictProblem(value) {
186
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return "is not a JSON object";
187
+ for (const key of VERDICT_SCHEMA.required) {
188
+ if (!(key in value)) return `has no ${key}`;
189
+ }
190
+ for (const [key, v] of Object.entries(value)) {
191
+ const declared = VERDICT_SCHEMA.properties[key];
192
+ if (declared === undefined) return `carries ${key}, which a refuter verdict does not`;
193
+ if (typeof v !== declared.type) return `has a ${key} that is not a ${declared.type}`;
194
+ }
195
+ return null;
196
+ }
197
+
110
198
  // Why `review` is not a review file this check can judge a record against,
111
199
  // or null when it is: a 7-40 hex `head`, every bucket a list of finding
112
200
  // objects, and `counts` reconciling with the lists it counts. checkDispositions
@@ -248,20 +336,31 @@ function shapeErrors(e) {
248
336
  /**
249
337
  * Every rule the record breaks against the review, as `violations` of
250
338
  * `{bucket, index, rule}` — `bucket`/`index` null for a rule about the record
251
- * as a whole — and every deferral that needs a human, as `escalations` of
252
- * `{bucket, index, severity, files}`. Empty `violations` means the record
253
- * holds every rule. `record` is the parsed record, or null when there is none
254
- * to read (`recordProblem` then says why). `touched` is touchedLines() for the
255
- * review's head; `diffFiles` every file name `git diff <merge-base>...<head>`
256
- * lists, required only when an entry defers `remedy-outside-diff`; `roots` the
257
- * directories an absolute finding or remedy path is read relative to.
339
+ * as a whole — every deferral that needs a human, as `escalations` of
340
+ * `{bucket, index, severity, files}`, and every deferral whose filing could
341
+ * not be read, as `unchecked` of `{bucket, index, issue, problem}`. Empty
342
+ * `violations` means the record holds every rule. `record` is the parsed
343
+ * record, or null when there is none to read (`recordProblem` then says why).
344
+ * `touched` is touchedLines() for the review's head; `diffFiles` every file
345
+ * name `git diff <merge-base>...<head>` lists, required only when an entry
346
+ * defers `remedy-outside-diff`; `roots` the directories an absolute finding
347
+ * or remedy path is read relative to. `filing` is `{pr, issue(n), verdict(path)}`,
348
+ * required only when an entry defers or is an in-scope suggestion: `issue`
349
+ * answers `{state, title, labels}` — `state` upper-case, `labels` names — or
350
+ * `{problem}` when the tracker cannot say; `verdict` answers `{refuted}` for
351
+ * a refuter verdict path or `{problem}` when it is no usable evidence.
258
352
  * `review` must pass reviewProblem() — a bucket missing or holding a
259
353
  * non-object is a TypeError here, not a violation.
260
354
  */
261
- export function checkDispositions({ review, record, recordProblem = null, touched, diffFiles = null, roots = [] }) {
355
+ export function checkDispositions({ review, record, recordProblem = null, touched, diffFiles = null, roots = [], filing = null }) {
262
356
  const violations = [];
263
357
  const escalations = [];
358
+ const unchecked = [];
264
359
  const at = (bucket, index, rule) => violations.push({ bucket, index, rule });
360
+ const filingOf = () => {
361
+ if (filing === null) throw new TypeError("checkDispositions: an entry is judged against the tracker or a verdict file and no filing was given");
362
+ return filing;
363
+ };
265
364
 
266
365
  let entries = [];
267
366
  if (record === null) {
@@ -307,27 +406,77 @@ export function checkDispositions({ review, record, recordProblem = null, touche
307
406
  if (!e.reason?.trim()) at(bucket, index, "a reversed refutation names its evidence in reason, and this one names none");
308
407
  return;
309
408
  }
310
- if (bucket !== "survived" || e.disposition !== "defer") return;
311
- const presumed = presumedInScope(review[bucket][index], touched, roots);
312
- if (presumed === null && e.scope === "out") return;
313
- if (!ALLOWED_DEFER.includes(e.reason)) {
314
- const why = presumed === null ? "its entry declares scope in" : `${presumed}, so it is in scope whatever its entry declares`;
315
- const reason = e.reason === undefined || e.reason === "" ? "no reason" : `reason ${JSON.stringify(e.reason)}`;
316
- at(bucket, index, `an in-scope survived finding deferred with ${reason} — ${why}; it defers only for ${ALLOWED_DEFER.join(", ")}`);
409
+ if (bucket === "survived" && e.disposition !== "defer") return;
410
+ const finding = review[bucket][index];
411
+ const presumed = presumedInScope(finding, touched, roots);
412
+ const inScope = presumed !== null || e.scope === "in";
413
+ if (bucket === "survived" && !inScope) return;
414
+ const why = presumed === null ? "its entry declares scope in" : `${presumed}, so it is in scope whatever its entry declares`;
415
+ const crashed = bucket === "unverified" && finding.refutersDispatched > 0;
416
+ // An in-scope suggestion's refuter verdict is the evidence a refuter ran.
417
+ let refuted = null;
418
+ if (bucket === "unverified" && !crashed && inScope) {
419
+ if (e.verdictPath === undefined) {
420
+ at(bucket, index, `an in-scope suggestion carries no refuter evidence — its entry names no verdictPath; ${why}`);
421
+ return;
422
+ }
423
+ const v = filingOf().verdict(e.verdictPath);
424
+ if (v.problem !== undefined) {
425
+ at(bucket, index, `an in-scope suggestion carries no refuter evidence — verdictPath ${JSON.stringify(e.verdictPath)} ${v.problem}`);
426
+ return;
427
+ }
428
+ refuted = v.refuted;
429
+ if (refuted && e.disposition === "apply") {
430
+ at(bucket, index, `filing row 4 (${FILING_ROWS[4].finding}): applied, though its verdict is refuted: true — it belongs in ${homeText(FILING_ROWS[4], filing.pr)}`);
431
+ return;
432
+ }
433
+ }
434
+ if (e.disposition !== "defer") return;
435
+ const shape = e.claimKind === "shape";
436
+ // A finding that stands defers only for a reason: an in-scope survivor
437
+ // for one of ALLOWED_DEFER, a suggestion its refuter let through for one
438
+ // of row 1's — unless row 7 takes it.
439
+ if (bucket === "survived" || (refuted === false && !shape)) {
440
+ const allowed = bucket === "survived" ? ALLOWED_DEFER : ROW_1_DEFER;
441
+ if (!allowed.includes(e.reason)) {
442
+ const reason = e.reason === undefined || e.reason === "" ? "no reason" : `reason ${JSON.stringify(e.reason)}`;
443
+ at(bucket, index, bucket === "survived"
444
+ ? `an in-scope survived finding deferred with ${reason} — ${why}; it defers only for ${allowed.join(", ")}`
445
+ : `filing row 5 (${FILING_ROWS[5].finding}): deferred with ${reason} — it is applied, or deferred as row 1, for ${allowed.join(", ")}`);
446
+ return;
447
+ }
448
+ if (e.reason === REMEDY_OUTSIDE_DIFF) {
449
+ if (diffFiles === null) throw new TypeError("checkDispositions: an entry defers remedy-outside-diff and no diffFiles was given");
450
+ const inDiff = new Set(diffFiles);
451
+ const named = (e.remedyFiles ?? []).map((f) => f.trim()).filter((f) => f !== "");
452
+ const outside = named.map((f) => posix.normalize(repoPath(f, roots, inDiff))).filter((f) => !inDiff.has(f));
453
+ if (outside.length === 0) {
454
+ const what = named.length === 0 ? "remedyFiles names no file" : "every file remedyFiles names is in the PR's diff";
455
+ at(bucket, index, `reason remedy-outside-diff needs a remedy file absent from the PR's diff — ${what}`);
456
+ return;
457
+ }
458
+ const severity = finding.severity;
459
+ if (severity !== "suggestion") escalations.push({ bucket, index, severity: severity ?? null, files: outside });
460
+ }
461
+ }
462
+ // Where the deferral must be filed. `claimKind` is trusted, never judged.
463
+ const rowNo = refuted === true ? 4 : shape ? 7
464
+ : bucket === "survived" ? (e.reason === "false-rationale" ? 2 : 1)
465
+ : crashed ? 3 : inScope ? 5 : 6;
466
+ const row = FILING_ROWS[rowNo];
467
+ const { pr, issue: readIssue } = filingOf();
468
+ if (e.issue === undefined) {
469
+ at(bucket, index, `filing row ${rowNo} (${row.finding}): a deferral names the issue it was filed to, and this entry names none — it belongs in ${homeText(row, pr)}`);
317
470
  return;
318
471
  }
319
- if (e.reason !== REMEDY_OUTSIDE_DIFF) return;
320
- if (diffFiles === null) throw new TypeError("checkDispositions: an entry defers remedy-outside-diff and no diffFiles was given");
321
- const inDiff = new Set(diffFiles);
322
- const named = (e.remedyFiles ?? []).map((f) => f.trim()).filter((f) => f !== "");
323
- const outside = named.map((f) => posix.normalize(repoPath(f, roots, inDiff))).filter((f) => !inDiff.has(f));
324
- if (outside.length === 0) {
325
- const what = named.length === 0 ? "remedyFiles names no file" : "every file remedyFiles names is in the PR's diff";
326
- at(bucket, index, `reason remedy-outside-diff needs a remedy file absent from the PR's diff — ${what}`);
472
+ const issue = readIssue(e.issue);
473
+ if (issue.problem !== undefined) {
474
+ unchecked.push({ bucket, index, issue: e.issue, problem: issue.problem });
327
475
  return;
328
476
  }
329
- const severity = review[bucket][index].severity;
330
- if (severity !== "suggestion") escalations.push({ bucket, index, severity: severity ?? null, files: outside });
477
+ if (!homeHolds(row, issue, pr)) {
478
+ at(bucket, index, `filing row ${rowNo} (${row.finding}): it belongs in ${homeText(row, pr)}, and #${e.issue} is ${describeIssue(issue)}`);
479
+ }
331
480
  });
332
481
 
333
482
  for (const bucket of COVERED) {
@@ -335,7 +484,7 @@ export function checkDispositions({ review, record, recordProblem = null, touche
335
484
  if (!seen.has(`${bucket}[${index}]`)) at(bucket, index, "no entry — a finding with no entry is a dropped finding");
336
485
  });
337
486
  }
338
- return { violations, escalations };
487
+ return { violations, escalations, unchecked };
339
488
  }
340
489
 
341
490
  export function formatViolation({ bucket, index, rule }) {
@@ -352,7 +501,7 @@ export function formatEscalation({ bucket, index, severity, files }) {
352
501
  // one. Separators a removal leaves doubled are folded.
353
502
  export function withVerdict(rowText, token) {
354
503
  const mine = dispositionsToken(token);
355
- if (mine === null) throw new Error(`withVerdict: '${token}' is not a dispositions-ok=/dispositions-mismatch=/dispositions-escalate= token`);
504
+ if (mine === null) throw new Error(`withVerdict: '${token}' is not a dispositions-ok=/dispositions-mismatch=/dispositions-escalate=/dispositions-unchecked= token`);
356
505
  const words = String(rowText).trim().split(/\s+/).filter(Boolean);
357
506
  const kept = words.filter((w) => {
358
507
  const d = dispositionsToken(w);
@@ -365,13 +514,14 @@ export function withVerdict(rowText, token) {
365
514
 
366
515
  // Whether a fix-applier on PR `pr` with a lower retry suffix than `member`
367
516
  // already has a mismatch or escalate on the ledger for `head` — on any row
368
- // that resolves to the PR, since a row can be split. A verdict on another
369
- // review head counts for nothing, so a new review starts the count again.
517
+ // that resolves to the PR, since a row can be split. An unchecked verdict is
518
+ // no failure of a record, and a verdict on another review head counts for
519
+ // nothing, so a new review starts the count again.
370
520
  export function failedBefore(rows, pr, member, head) {
371
521
  const mine = member.retry ?? "";
372
522
  return rows.some((r) => rowNums(r).pr === pr && r.split(/\s+/).some((w) => {
373
523
  const d = dispositionsToken(w);
374
- return d !== null && d.verdict !== "ok" && d.member.number === pr
524
+ return d !== null && (d.verdict === "mismatch" || d.verdict === "escalate") && d.member.number === pr
375
525
  && (d.member.retry ?? "") < mine && sameHead(d.head, head);
376
526
  }));
377
527
  }
@@ -406,6 +556,75 @@ function runLedger(ledgerFile, args, what) {
406
556
  }
407
557
  }
408
558
 
559
+ // Where a deferral was filed, as checkDispositions' `filing.issue` reads it:
560
+ // `gh issue view <n> --json labels,state,title`, each number read once, run
561
+ // from `repo` so gh resolves the tracker from that repository's remotes —
562
+ // under the same scrubbed GIT_DIR and GIT_WORK_TREE as the git primitive,
563
+ // which would otherwise point gh at another repository's remotes. Anything
564
+ // short of an answer in that shape is `{problem}`: the filing goes unchecked,
565
+ // never judged.
566
+ function issueReader(repo) {
567
+ const cache = new Map();
568
+ const read = (n) => {
569
+ let out;
570
+ try {
571
+ out = execFileSync("gh", ["issue", "view", String(n), "--json", "labels,state,title"], {
572
+ cwd: repo, encoding: "utf8", env: gitEnv(), stdio: ["ignore", "pipe", "pipe"], timeout: 60_000,
573
+ });
574
+ } catch (e) {
575
+ return { problem: e.code === "ENOENT" ? "gh is not on PATH" : e.stderr?.toString().trim() || e.message };
576
+ }
577
+ let j;
578
+ try {
579
+ j = JSON.parse(out);
580
+ } catch (e) {
581
+ return { problem: `gh printed no JSON — ${e.message}` };
582
+ }
583
+ if (typeof j?.state !== "string" || typeof j.title !== "string" || !Array.isArray(j.labels)
584
+ || !j.labels.every((l) => typeof l?.name === "string")) {
585
+ return { problem: "gh printed no {labels, state, title}" };
586
+ }
587
+ return { state: j.state.toUpperCase(), title: j.title, labels: j.labels.map((l) => l.name) };
588
+ };
589
+ return (n) => {
590
+ if (!cache.has(n)) cache.set(n, read(n));
591
+ return cache.get(n);
592
+ };
593
+ }
594
+
595
+ // A refuter verdict, as checkDispositions' `filing.verdict` reads it: an
596
+ // absolute path to a file under `<scratch>/pr<pr>/fix-XXXXXXXX/<finding>/`,
597
+ // both sides resolved through symlinks, holding JSON in the refuter verdict
598
+ // schema. Anything else is `{problem}` — no evidence a refuter ran.
599
+ function verdictReader(scratch, pr) {
600
+ const runs = join(scratch, `pr${pr}`);
601
+ const notUnder = `is not under a fix-applier run root, ${runs}/fix-XXXXXXXX/<finding>/`;
602
+ return (path) => {
603
+ if (!isAbsolute(path)) return { problem: "is not an absolute path" };
604
+ let file, root;
605
+ try {
606
+ file = realpathSync(path);
607
+ } catch {
608
+ return { problem: "names no file that exists" };
609
+ }
610
+ try {
611
+ root = realpathSync(runs);
612
+ } catch {
613
+ return { problem: notUnder };
614
+ }
615
+ if (!/^fix-[^/]+\/[^/]+\/./.test(relative(root, file).split(sep).join("/"))) return { problem: notUnder };
616
+ let value;
617
+ try {
618
+ if (!statSync(file).isFile()) return { problem: "names something that is not a file" };
619
+ value = JSON.parse(readFileSync(file, "utf8"));
620
+ } catch (e) {
621
+ return { problem: `cannot be read as JSON — ${e.message}` };
622
+ }
623
+ const why = verdictProblem(value);
624
+ return why === null ? { refuted: value.refuted } : { problem: `fails the refuter verdict schema — it ${why}` };
625
+ };
626
+ }
627
+
409
628
  // The ledger file this run writes its verdict to, or null when there is none:
410
629
  // `--ledger`, else the run's `.fleet/ledger.md` under the git common dir of
411
630
  // `repo` — the workspace every worktree of one repository shares, which is
@@ -495,8 +714,9 @@ function main() {
495
714
  `list the files of ${base}..${head}`).split("\0").filter(Boolean);
496
715
  const ledgerFile = standalone ? null : ledgerInUse(arg("ledger"), repo);
497
716
 
498
- const { violations, escalations } = checkDispositions({
717
+ const { violations, escalations, unchecked } = checkDispositions({
499
718
  review, record, recordProblem, touched: touchedLines(diff), diffFiles, roots: [review.snapshot, top],
719
+ filing: { pr, issue: issueReader(repo), verdict: verdictReader(scratch, pr) },
500
720
  });
501
721
  // The verdict lands on the row carrying the member on its own PR's row —
502
722
  // where `ledger.mjs dispatch` wrote it, and where the gate reads PR M's
@@ -506,9 +726,11 @@ function main() {
506
726
  const data = ledgerFile === null ? null : JSON.parse(runLedger(ledgerFile, ["read"], "read the ledger"));
507
727
  // A mismatch an earlier fix-applier already drew on this review makes this
508
728
  // one the second: it is written as an escalate, which no fix-applier answers.
729
+ // A broken rule outranks an escalation, and an escalation a filing the
730
+ // tracker could not answer.
509
731
  const secondMismatch = violations.length > 0 && data !== null && failedBefore(data.rows, pr, member, head);
510
732
  const verdict = violations.length > 0 ? (secondMismatch ? "escalate" : "mismatch")
511
- : escalations.length > 0 ? "escalate" : "ok";
733
+ : escalations.length > 0 ? "escalate" : unchecked.length > 0 ? "unchecked" : "ok";
512
734
  const token = `dispositions-${verdict}=${member.name}:${head}`;
513
735
 
514
736
  if (data !== null) {
@@ -524,10 +746,13 @@ function main() {
524
746
 
525
747
  for (const v of violations) console.error(`${member.name}: ${formatViolation(v)}`);
526
748
  for (const x of escalations) console.error(`${member.name}: ${formatEscalation(x)}`);
749
+ for (const u of unchecked) {
750
+ console.error(`${member.name}: ${u.bucket}[${u.index}]: where it was filed is unchecked — #${u.issue} could not be read through gh: ${u.problem}`);
751
+ }
527
752
  if (secondMismatch) {
528
753
  console.error(`${member.name}: escalate — an earlier fix-applier's record on review ${head} already failed this check; no further fix-applier answers PR #${pr}, a human does`);
529
754
  }
530
- console.log(JSON.stringify({ member: member.name, pr, head, verdict, token: ledgerFile === null ? null : token, violations, escalations }));
755
+ console.log(JSON.stringify({ member: member.name, pr, head, verdict, token: ledgerFile === null ? null : token, violations, escalations, unchecked }));
531
756
  // exitCode, not exit(): stdout to a pipe is written asynchronously, and an
532
757
  // exit() here could cut the payload off.
533
758
  process.exitCode = verdict === "ok" ? 0 : 1;
@@ -372,15 +372,18 @@ const CONFLICT_HOLD = /^conflict-hold[:-]#?(\d+)$/;
372
372
  const TIER_VERDICT = /^tier-(ok|mismatch|unverifiable)=([^:\s]+):\S+$/;
373
373
  // dispositions-check.mjs's verdict on a review fix-applier's disposition
374
374
  // record: `dispositions-ok=fix-pr-<M>[-x]:<head>`,
375
- // `dispositions-mismatch=…` or `dispositions-escalate=…` (a critical or
375
+ // `dispositions-mismatch=…`, `dispositions-escalate=…` (a critical or
376
376
  // important deferral, or a second mismatch on one review, that a human rules
377
- // on), `<head>` the head of the review the record answers. `ledger.mjs
378
- // dispatch` refuses a finisher on a mismatch or an escalate. A mismatch
379
- // returns the PR to fixDue for one retry; an escalate is a hold only a human
380
- // answers, so the tick never re-offers the PR for it. A token outside this
381
- // shape is no verdict at all, which the gate reads as unchecked: fail closed.
377
+ // on) or `dispositions-unchecked=…` (no rule broke, but where a deferral was
378
+ // filed could not be read), `<head>` the head of the review the record
379
+ // answers. `ledger.mjs dispatch` refuses a finisher on anything but an ok. A
380
+ // mismatch returns the PR to fixDue for one retry; an escalate is a hold only
381
+ // a human answers, so the tick never re-offers the PR for it; an unchecked is
382
+ // answered by running the check again, so the tick never offers a
383
+ // fix-applier for it either. A token outside this shape is no verdict at all,
384
+ // which the gate reads as unchecked: fail closed.
382
385
  export function dispositionsToken(tok) {
383
- const m = /^dispositions-(ok|mismatch|escalate)=([^:\s]+):([0-9a-f]{7,40})$/i.exec(tok);
386
+ const m = /^dispositions-(ok|mismatch|escalate|unchecked)=([^:\s]+):([0-9a-f]{7,40})$/i.exec(tok);
384
387
  if (!m) return null;
385
388
  const member = parseMember(m[2]);
386
389
  if (member === null || member.family !== "fix-pr") return null;
@@ -393,14 +396,14 @@ export const sameHead = (a, b) => a.startsWith(b) || b.startsWith(a);
393
396
 
394
397
  // Which verdict outranks which when one fix-applier carries more than one for
395
398
  // a head: the stricter reading wins.
396
- const VERDICT_RANK = { ok: 0, mismatch: 1, escalate: 2 };
399
+ const VERDICT_RANK = { ok: 0, unchecked: 1, mismatch: 2, escalate: 3 };
397
400
 
398
401
  // A PR's current dispositions verdict against its latest review head: among
399
402
  // the tokens answering that head, the one from the fix-applier with the
400
403
  // highest retry suffix ("" < "b" < "c" …) — never row-text position, which a
401
404
  // `row` rewrite can reorder. One fix-applier carrying two verdicts for one
402
405
  // head reads as the stricter one. null when no token answers the head.
403
- /** @returns {{verdict: "ok"|"mismatch"|"escalate", member: string}|null} */
406
+ /** @returns {{verdict: "ok"|"unchecked"|"mismatch"|"escalate", member: string}|null} */
404
407
  export function currentDispositions(tokens, head) {
405
408
  let best = null;
406
409
  for (const t of tokens) {
@@ -1661,10 +1661,16 @@ function dispositionsRefusal(pr, review) {
1661
1661
  if (review.survived === 0 && review.unverified === 0) return null;
1662
1662
  const v = review.dispositions;
1663
1663
  if (v === null) {
1664
- return `dispositions unchecked — no dispositions-ok=/dispositions-mismatch=/dispositions-escalate= token answers PR #${pr}'s latest review, `
1664
+ return `dispositions unchecked — no dispositions-ok=/dispositions-mismatch=/dispositions-escalate=/dispositions-unchecked= token answers PR #${pr}'s latest review, `
1665
1665
  + `reviewed=${review.head}; run dispositions-check.mjs --member fix-pr-${pr}[-<x>] --scratch <scratch> for the fix-applier `
1666
1666
  + "that answered that review, then dispatch the finisher again";
1667
1667
  }
1668
+ if (v.verdict === "unchecked") {
1669
+ return `dispositions unchecked — ${v.member}'s check of review ${review.head} could not read where a deferral was filed (gh unreachable, `
1670
+ + "or an issue unreadable — an issue that does not exist is unreadable too, and no re-run answers that one: the check's stderr names "
1671
+ + `it, and the record's issue number needs correcting); run dispositions-check.mjs --member ${v.member} --scratch <scratch> again once gh answers, `
1672
+ + "then dispatch the finisher again";
1673
+ }
1668
1674
  if (v.verdict === "mismatch") {
1669
1675
  return `dispositions mismatch — ${v.member}'s disposition record fails the check against review ${review.head}; `
1670
1676
  + `dispositions-check.mjs --member ${v.member} --scratch <scratch> names each violating entry by bucket, index and rule`;
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ // Which lines would merging this head remove that `main` gained after the
3
+ // PR's work began — the main-gain check, read-only.
4
+ //
5
+ // main-gain.mjs --head <sha> [--base <ref>] [--body-file <path|->]
6
+ //
7
+ // Reads the repository at the cwd. `--head` is a full commit SHA; `--base`
8
+ // defaults to `origin/main` and is spelled the way no-undo-audit.sh takes its
9
+ // BASE_REF — `origin/<branch>` or `refs/remotes/<path>`, qualified to the
10
+ // full `refs/remotes/` path before any read so a local tag or branch literally
11
+ // named `origin/main` cannot answer for it. `--body-file` is the PR body
12
+ // (`-` reads stdin); omitted, the body is empty and nothing is acknowledged.
13
+ // It never fetches, writes or changes refs: the caller fetches first.
14
+ //
15
+ // The reference point R is the earliest author date among the PR's own
16
+ // commits (`<base>..<head>`). Rebases and amends keep author dates, so R
17
+ // survives a rewritten branch, where a merge-base taken after the rebase
18
+ // would not. A line landed on `main` when the commit `git blame
19
+ // --first-parent` attributes it to on `<base>` was committed; `main` is
20
+ // merge-only, so that is the first-parent commit that brought it in. A line
21
+ // is a main gain when it landed after R.
22
+ //
23
+ // R misses two windows. The time between the fork and the PR's first commit
24
+ // is before R. And a branch rewritten into fresh commits (`git reset --soft
25
+ // <base>` and a new commit, or a squash that resets the author) carries new
26
+ // author dates, so R moves past a landing and a deletion replayed from the
27
+ // rewrite reads clean. Only a rebase or an amend keeps R.
28
+ //
29
+ // Removed lines are read off the merge the head would actually produce:
30
+ // `git merge-tree --write-tree <base> <head>`, diffed against `<base>` with
31
+ // rename detection on. That is right for a head that is behind `<base>` too,
32
+ // where a three-dot diff is not. Every removed line is a candidate, including
33
+ // one replaced by other text, and every line of a deleted file is. A removed
34
+ // line whose exact text is added back in the same file is a move, not a
35
+ // candidate. Binary files cannot be read line by line and are listed in
36
+ // `unchecked[]` instead of blocking. A merge-tree that reports conflicts is a
37
+ // head that cannot merge as it stands, which is no answer about its content.
38
+ //
39
+ // Each hit carries a landing key: `#<n>` when the landing commit's subject is
40
+ // GitHub's merge subject for PR n, otherwise that commit's 12-character
41
+ // abbreviated SHA. A PR-body line `main-gain-removal: <path> <key> - <why>`
42
+ // acknowledges every hit in that file with that key, and nothing else; one
43
+ // with an empty reason does not count. Acknowledged hits move from `hits[]`
44
+ // to `acknowledged[]` and both are reported.
45
+ //
46
+ // Stdout: one JSON line, `{head, base, since, hits, acknowledged, unchecked,
47
+ // reason}`, `since` being R as an ISO timestamp. Each hit is `{path, key,
48
+ // landed, lines: [{line, text}], ack}`, `path` the file's name on `<base>` and
49
+ // `ack` the body line to copy, reason left for the author to write.
50
+ //
51
+ // 0 clean, or every hit acknowledged
52
+ // 1 at least one unacknowledged hit reason main-gain-removed:<first path>
53
+ // 2 could not answer: no verdict reason names what could not be read
54
+ //
55
+ // An argument this script refuses exits 2 with no JSON line at all.
56
+
57
+ import { spawnSync } from "node:child_process";
58
+ import { readFileSync } from "node:fs";
59
+ import { makeDie, defineFlags, writeAll } from "./arg.mjs";
60
+ import { gitEnv } from "./git-env.mjs";
61
+
62
+ const NAME = "main-gain";
63
+ const die = makeDie(NAME);
64
+ const { arg, sweep, stray } = defineFlags(die, {
65
+ flags: { head: "value", base: "value", "body-file": "value" },
66
+ });
67
+
68
+ const USAGE = "usage: main-gain.mjs --head <sha> [--base <ref>] [--body-file <path|->]";
69
+
70
+ const headArg = arg("head");
71
+ const base = arg("base") ?? "origin/main";
72
+ const bodyFile = arg("body-file");
73
+ if (headArg === null) die(USAGE);
74
+ sweep();
75
+ stray();
76
+
77
+ const head = headArg.toLowerCase();
78
+ if (!/^[0-9a-f]{40}$/.test(head)) die(`--head needs a full 40-character commit SHA, got ${headArg}`);
79
+ if (!/^(origin|refs\/remotes)\/./.test(base)) die(`--base must be spelled origin/<branch> or refs/remotes/<path>, got '${base}'`);
80
+ const baseRev = base.startsWith("refs/remotes/") ? base : `refs/remotes/${base}`;
81
+
82
+ let body = "";
83
+ if (bodyFile !== null) {
84
+ try {
85
+ body = readFileSync(bodyFile === "-" ? 0 : bodyFile, "utf8");
86
+ } catch (e) {
87
+ die(`cannot read --body-file ${bodyFile}: ${e.code ?? e.message}`);
88
+ }
89
+ }
90
+
91
+ // LC_ALL=C: the `Binary files … differ` line below is read by its text.
92
+ // GIT_LITERAL_PATHSPECS: a path is a name here, never a glob or magic.
93
+ const ENV = gitEnv({ LC_ALL: "C", GIT_LITERAL_PATHSPECS: "1" });
94
+
95
+ // The one git spawn. `null` for a git that could not run or exited outside
96
+ // `ok`; the caller names what it was reading.
97
+ function git(args, ok = [0]) {
98
+ const r = spawnSync("git", args, { encoding: "utf8", env: ENV, stdio: ["ignore", "pipe", "pipe"], maxBuffer: 1 << 30 });
99
+ if (r.error || r.signal || !ok.includes(r.status)) return null;
100
+ return r;
101
+ }
102
+
103
+ class Unanswerable extends Error {}
104
+ const unanswerable = (reason) => {
105
+ throw new Unanswerable(reason);
106
+ };
107
+
108
+ const MERGE_SUBJECT = /^Merge pull request #([1-9][0-9]*) from /;
109
+
110
+ function landingKey(sha, summary) {
111
+ const m = MERGE_SUBJECT.exec(summary);
112
+ return m ? `#${m[1]}` : sha.slice(0, 12);
113
+ }
114
+
115
+ // `<old> <new> <status>` per changed path, off `diff-tree --raw -z`.
116
+ function changedPaths(tree) {
117
+ const r = git(["diff-tree", "-r", "-M", "-z", "--raw", baseRev, tree]);
118
+ if (r === null) unanswerable("diff-unreadable");
119
+ const parts = r.stdout.split("\0");
120
+ const out = [];
121
+ for (let i = 0; i < parts.length - 1; ) {
122
+ const meta = parts[i++];
123
+ const m = /^:(\d{6}) (\d{6}) [0-9a-f]+ [0-9a-f]+ ([A-Z])\d*$/.exec(meta);
124
+ if (!m) unanswerable("diff-unreadable");
125
+ const status = m[3];
126
+ const oldPath = parts[i++];
127
+ const newPath = status === "R" || status === "C" ? parts[i++] : oldPath;
128
+ out.push({ oldMode: m[1], status, oldPath, newPath });
129
+ }
130
+ return out;
131
+ }
132
+
133
+ // Removed lines `[{line, text}]` and added texts, or `binary`, for one path.
134
+ function fileDiff(tree, oldPath, newPath) {
135
+ const paths = oldPath === newPath ? [oldPath] : [oldPath, newPath];
136
+ const r = git(["diff-tree", "-r", "-M", "-p", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", baseRev, tree, "--", ...paths]);
137
+ if (r === null) unanswerable(`diff-unreadable:${oldPath}`);
138
+ const removed = [];
139
+ const added = [];
140
+ let inHunk = false;
141
+ let oldLine = 0;
142
+ for (const line of r.stdout.split("\n")) {
143
+ if (line.startsWith("diff --git ")) {
144
+ inHunk = false;
145
+ continue;
146
+ }
147
+ const h = /^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@/.exec(line);
148
+ if (h) {
149
+ inHunk = true;
150
+ oldLine = Number(h[1]);
151
+ } else if (!inHunk) {
152
+ if (line.startsWith("Binary files ")) return { binary: true };
153
+ } else if (line.startsWith("-")) {
154
+ removed.push({ line: oldLine++, text: line.slice(1) });
155
+ } else if (line.startsWith("+")) {
156
+ added.push(line.slice(1));
157
+ }
158
+ }
159
+ return { binary: false, removed, added };
160
+ }
161
+
162
+ // line number on `<base>` → {sha, time, summary} for the requested lines,
163
+ // which arrive in ascending order; consecutive ones share one `-L` range.
164
+ function blame(path, lines) {
165
+ const spans = [];
166
+ for (const { line } of lines) {
167
+ const last = spans.at(-1);
168
+ if (last && line === last[1] + 1) last[1] = line;
169
+ else spans.push([line, line]);
170
+ }
171
+ const ranges = spans.flatMap(([from, to]) => ["-L", `${from},${to}`]);
172
+ const r = git(["blame", "--first-parent", "--line-porcelain", "--no-ignore-revs-file", ...ranges, baseRev, "--", path]);
173
+ if (r === null) unanswerable(`blame-failed:${path}`);
174
+ const out = new Map();
175
+ let cur = null;
176
+ for (const line of r.stdout.split("\n")) {
177
+ const h = /^([0-9a-f]{40}) \d+ (\d+)(?: \d+)?$/.exec(line);
178
+ if (h) {
179
+ cur = { sha: h[1], line: Number(h[2]), time: null, summary: "" };
180
+ } else if (cur && line.startsWith("committer-time ")) {
181
+ cur.time = Number(line.slice("committer-time ".length));
182
+ } else if (cur && line.startsWith("summary ")) {
183
+ cur.summary = line.slice("summary ".length);
184
+ } else if (cur && line.startsWith("\t")) {
185
+ out.set(cur.line, cur);
186
+ cur = null;
187
+ }
188
+ }
189
+ for (const { line } of lines) {
190
+ if (!out.has(line) || !Number.isInteger(out.get(line).time)) unanswerable(`blame-failed:${path}`);
191
+ }
192
+ return out;
193
+ }
194
+
195
+ // `main-gain-removal: <path> <key> - <why>`, one per line. The key is the
196
+ // token before ` - `, so a path may carry spaces; a blank <why> never matches.
197
+ function acknowledgements(text) {
198
+ const acks = [];
199
+ for (const raw of text.split(/\r?\n/)) {
200
+ const m = /^main-gain-removal: (.+) (#[1-9][0-9]*|[0-9a-f]{12}) - (\S.*)$/.exec(raw.trim());
201
+ if (m) acks.push({ path: m[1], key: m[2], reason: m[3] });
202
+ }
203
+ return acks;
204
+ }
205
+
206
+ function check() {
207
+ if (git(["cat-file", "-e", `${head}^{commit}`]) === null) unanswerable("head-unreadable");
208
+ if (git(["rev-parse", "--verify", "-q", `${baseRev}^{commit}`]) === null) unanswerable("base-unreadable");
209
+
210
+ const own = git(["log", "--format=%at", `${baseRev}..${head}`]);
211
+ if (own === null) unanswerable("history-unreadable");
212
+ const times = own.stdout.split("\n").filter(Boolean).map(Number);
213
+ if (times.some((t) => !Number.isInteger(t))) unanswerable("history-unreadable");
214
+ const since = times.length ? Math.min(...times) : null;
215
+
216
+ const merged = git(["merge-tree", "--write-tree", baseRev, head], [0, 1]);
217
+ if (merged === null) unanswerable("merge-unreadable");
218
+ if (merged.status === 1) unanswerable("merge-conflict");
219
+ const tree = merged.stdout.split("\n")[0];
220
+ if (!/^[0-9a-f]{40,64}$/.test(tree)) unanswerable("merge-unreadable");
221
+
222
+ const hits = [];
223
+ const unchecked = [];
224
+ // No commits of its own: the head is already on `<base>` and merges nothing.
225
+ if (since !== null) {
226
+ for (const { oldMode, status, oldPath, newPath } of changedPaths(tree)) {
227
+ if (status === "A") continue;
228
+ if (oldMode === "160000") {
229
+ unchecked.push(oldPath);
230
+ continue;
231
+ }
232
+ const d = fileDiff(tree, oldPath, newPath);
233
+ if (d.binary) {
234
+ unchecked.push(oldPath);
235
+ continue;
236
+ }
237
+ const addedBack = new Map();
238
+ for (const t of d.added) addedBack.set(t, (addedBack.get(t) ?? 0) + 1);
239
+ const candidates = d.removed.filter(({ text }) => {
240
+ const n = addedBack.get(text) ?? 0;
241
+ if (n === 0) return true;
242
+ addedBack.set(text, n - 1);
243
+ return false;
244
+ });
245
+ if (candidates.length === 0) continue;
246
+ const blamed = blame(oldPath, candidates);
247
+ const byKey = new Map();
248
+ for (const c of candidates) {
249
+ const b = blamed.get(c.line);
250
+ if (b.time <= since) continue;
251
+ const key = landingKey(b.sha, b.summary);
252
+ if (!byKey.has(key)) {
253
+ byKey.set(key, { path: oldPath, key, landed: b.sha, lines: [], ack: `main-gain-removal: ${oldPath} ${key} - <why>` });
254
+ }
255
+ byKey.get(key).lines.push(c);
256
+ }
257
+ hits.push(...byKey.values());
258
+ }
259
+ }
260
+
261
+ const acks = acknowledgements(body);
262
+ const acknowledged = [];
263
+ const open = [];
264
+ for (const hit of hits) {
265
+ const ack = acks.find((a) => a.path === hit.path && a.key === hit.key);
266
+ if (ack) acknowledged.push({ ...hit, reason: ack.reason });
267
+ else open.push(hit);
268
+ }
269
+ return {
270
+ since: since === null ? null : new Date(since * 1000).toISOString(),
271
+ hits: open,
272
+ acknowledged,
273
+ unchecked,
274
+ reason: open.length ? `main-gain-removed:${open[0].path}` : null,
275
+ };
276
+ }
277
+
278
+ // Node exits 1 on an uncaught throw, and 1 here is a verdict about the PR,
279
+ // so nothing but a hit may reach it: every other failure is exit 2.
280
+ let result;
281
+ try {
282
+ result = check();
283
+ } catch (e) {
284
+ if (!(e instanceof Unanswerable)) die(`check failed: ${e.code ?? e.message} — could not evaluate`);
285
+ result = { since: null, hits: [], acknowledged: [], unchecked: [], reason: e.message, unknown: true };
286
+ }
287
+ const { unknown, ...payload } = result;
288
+ writeAll(1, `${JSON.stringify({ head, base, ...payload })}\n`);
289
+ process.exit(unknown ? 2 : payload.hits.length ? 1 : 0);
@@ -4,12 +4,14 @@
4
4
  // merge-gate.mjs --pr <n> --pre <sha> [--post <sha>] [--out <path>]
5
5
  //
6
6
  // Runs, in order, `instruments.sh --repo <main checkout>`, `gh pr view <n>
7
- // --json labels,reviewDecision,headRefOid` and `ci-state.mjs --pr <n>
8
- // --declare-no-ci`, then answers the conjunction. All three run on every
9
- // call, whatever the earlier ones said, so the JSON line carries every field
10
- // that was read. It never merges, labels, rebases or waits: the merge bot
11
- // runs it once before any wait and once immediately before `gh pr merge`, and
12
- // merges only on that second exit 0.
7
+ // --json labels,reviewDecision,headRefOid,body`, `main-gain.mjs` against the
8
+ // PR head in the main checkout, and `ci-state.mjs --pr <n> --declare-no-ci`,
9
+ // then answers the conjunction. All four run on every call, whatever the
10
+ // earlier ones said — except main-gain.mjs, which needs the head and body gh
11
+ // read and the main checkout, and is skipped when either could not be had — so
12
+ // the JSON line carries every field that was read. It never merges, labels,
13
+ // rebases or waits: the merge bot runs it once before any wait and once
14
+ // immediately before `gh pr merge`, and merges only on that second exit 0.
13
15
  //
14
16
  // `--pre` is the labelled head, `--post` the head the bot's own
15
17
  // `gh pr update-branch --rebase` produced; omitted, it is `--pre` (the
@@ -20,8 +22,11 @@
20
22
  // guesses it.
21
23
  //
22
24
  // Stdout: exactly one JSON line, `{pr, verdict, reason, head, pre, post,
23
- // behind, instruments, ci}`. Stderr: the children's own diagnostics, passed
24
- // straight through and never folded into stdout.
25
+ // behind, instruments, mainGain, ci}`, `mainGain` echoing main-gain.mjs's own
26
+ // payload — hits, acknowledged removals and unchecked files — or null when
27
+ // it did not run or printed no JSON object; an unusable payload is still
28
+ // echoed. Stderr: the children's own diagnostics, passed straight through
29
+ // and never folded into stdout.
25
30
  //
26
31
  // Exit vocabulary — the same three-way contract as inflight.sh, prove-merge.sh
27
32
  // and staleness.mjs:
@@ -39,6 +44,7 @@
39
44
  // label `ready-to-merge` absent 1 label-pulled
40
45
  // reviewDecision CHANGES_REQUESTED 1 changes-requested
41
46
  // PR head not in {pre, post} 1 head-moved-after-label
47
+ // main-gain.mjs exit 1 1 main-gain-removed:<first path>
42
48
  // ci-state exit 1 (not-green) 1 ci:<first entry of ci.reasons>
43
49
  // ci.behind > 0 1 behind:<n>
44
50
  // ci-state payload rate-limited/unusable 2 rate-limited / ci-unreadable
@@ -46,6 +52,14 @@
46
52
  // instruments.sh exit 1 2 instrument-set-changed
47
53
  // instruments.sh any other failure 2 instruments-unanswerable
48
54
  // gh pr view fails or misparses 2 pr-unreadable
55
+ // main-gain.mjs exit 2 or unusable payload 2 main-gain-unanswerable
56
+ //
57
+ // main-gain.mjs answers which lines merging the head would remove that `main`
58
+ // gained after the PR's work began. It reads `origin/main` in the main
59
+ // checkout as it stands, so the caller fetches first. On the server-side
60
+ // rebase path the PR object can lag at the pre-rebase head for a while;
61
+ // checking that head gives the same verdict as the rebased one, because
62
+ // `git merge-tree` against `main` lands the same content either way.
49
63
  //
50
64
  // An instrument change is 2, not 1: a changed instrument says nothing about
51
65
  // the PR, and the response is stop-and-report like every other 2.
@@ -114,25 +128,26 @@ const CHILD = { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] };
114
128
  // `--repo` locates the baseline only; the baseline itself names the tree to
115
129
  // audit, so a workspace that does not track `plugin/…` still reaches a
116
130
  // verdict over the checkout its run pinned — no flag here repoints it.
131
+ // `root` is returned too: main-gain.mjs reads the same main checkout.
117
132
  function readInstruments() {
118
133
  const common = spawnSync("git", ["rev-parse", "--git-common-dir"], { ...CHILD, env: gitEnv() });
119
134
  const root = common.error || common.status !== 0 ? null : workspaceDirFromGitCommonDir(common.stdout);
120
- if (root === null) return { exit: null, digest: null };
135
+ if (root === null) return { exit: null, digest: null, root };
121
136
  const r = spawnSync("sh", [join(SCRIPT_DIR, "instruments.sh"), "--repo", root], CHILD);
122
137
  const digest = (r.stdout ?? "").trim().split("\n")[0] || null;
123
- if (r.error || r.signal) return { exit: null, digest };
138
+ if (r.error || r.signal) return { exit: null, digest, root };
124
139
  // An exit 0 that printed no digest compared nothing it can show, so it is
125
140
  // not taken as "unchanged". instruments.sh prints the digest on both of its
126
141
  // answering paths (0 and 1) before it exits.
127
- if (r.status === 0 && !/^[0-9a-f]{64}$/.test(digest ?? "")) return { exit: null, digest };
128
- return { exit: r.status, digest };
142
+ if (r.status === 0 && !/^[0-9a-f]{64}$/.test(digest ?? "")) return { exit: null, digest, root };
143
+ return { exit: r.status, digest, root };
129
144
  }
130
145
 
131
146
  // --- gh pr view -----------------------------------------------------------
132
- // null for anything that is not the three fields in their gh shapes: a parse
147
+ // null for anything that is not the four fields in their gh shapes: a parse
133
148
  // that succeeds on the wrong shape must not reach a check that reads it.
134
149
  function readPr() {
135
- const r = spawnSync("gh", ["pr", "view", String(pr), "--json", "labels,reviewDecision,headRefOid"], CHILD);
150
+ const r = spawnSync("gh", ["pr", "view", String(pr), "--json", "labels,reviewDecision,headRefOid,body"], CHILD);
136
151
  if (r.error || r.status !== 0) return null;
137
152
  let v;
138
153
  try {
@@ -146,9 +161,47 @@ function readPr() {
146
161
  // same way. Anything else is not a decision gh would give.
147
162
  if (!Object.hasOwn(v, "reviewDecision") || (v.reviewDecision !== null && typeof v.reviewDecision !== "string")) return null;
148
163
  if (typeof v.headRefOid !== "string" || !/^[0-9a-f]{40}$/.test(v.headRefOid)) return null;
164
+ // The body carries the main-gain acknowledgements. gh answers `""` for an
165
+ // empty one, so a missing field is a read that did not happen.
166
+ if (typeof v.body !== "string") return null;
149
167
  return v;
150
168
  }
151
169
 
170
+ // --- main-gain.mjs --------------------------------------------------------
171
+ // Against the head gh just read, in the main checkout, with the body on
172
+ // stdin. Not run without both, and its row then stays silent:
173
+ // instruments-unanswerable or pr-unreadable names the missing input. As with
174
+ // ci-state below, the payload decides and the exit code has to agree with
175
+ // it — exit 0 with a hit, or exit 1 without one, is not a verdict. `payload`
176
+ // is whatever object the child printed, kept for the output line's echo
177
+ // (an exit 2 names what it could not read); decide() reads it only when
178
+ // `usable`.
179
+ function readMainGain(root, prView) {
180
+ if (root === null || prView === null) return { usable: false, exit: null, payload: null };
181
+ const r = spawnSync(
182
+ process.execPath,
183
+ [join(SCRIPT_DIR, "main-gain.mjs"), "--head", prView.headRefOid, "--body-file", "-"],
184
+ // A PR that removes a large main-gained file prints every removed line:
185
+ // past spawnSync's 1 MiB default the read fails ENOBUFS and the verdict
186
+ // that PR earned reads as unanswerable. main-gain.mjs's own git reads
187
+ // carry the same 1 GiB bound.
188
+ { ...CHILD, stdio: ["pipe", "pipe", "inherit"], cwd: root, input: prView.body, maxBuffer: 1 << 30 },
189
+ );
190
+ if (r.error) writeAll(2, `merge-gate: main-gain.mjs could not be read: ${r.error.code ?? r.error.message}\n`);
191
+ let v = null;
192
+ try {
193
+ v = JSON.parse(r.stdout ?? "");
194
+ } catch {
195
+ v = null;
196
+ }
197
+ const payload = isObject(v) ? v : null;
198
+ const read = (usable) => ({ usable, exit: r.status, payload });
199
+ if (r.error || r.signal || payload === null || payload.head !== prView.headRefOid) return read(false);
200
+ if (![payload.hits, payload.acknowledged, payload.unchecked].every(Array.isArray)) return read(false);
201
+ if (!payload.hits.every((h) => isObject(h) && typeof h.path === "string" && h.path !== "")) return read(false);
202
+ return read((r.status === 0 && payload.hits.length === 0) || (r.status === 1 && payload.hits.length > 0));
203
+ }
204
+
152
205
  // --- ci-state.mjs ---------------------------------------------------------
153
206
  // `--declare-no-ci` on every call, with no option on this script's surface.
154
207
  // It moves exactly one arm of ci-state's gate — `no-ci` — and cannot relax
@@ -195,7 +248,7 @@ function readCi() {
195
248
  }
196
249
 
197
250
  // --- the conjunction ------------------------------------------------------
198
- function decide(instruments, prView, ciRead) {
251
+ function decide(instruments, prView, mainGain, ciRead) {
199
252
  const blocked = (reason) => ({ verdict: "blocked", reason });
200
253
  const unknown = (reason) => ({ verdict: "unknown", reason });
201
254
  const { validated, usable } = ciRead;
@@ -209,6 +262,7 @@ function decide(instruments, prView, ciRead) {
209
262
  // own CI judged here while the label's audit belongs to the tree before it,
210
263
  // so the same row applies to ci-state's reading too.
211
264
  if (usable && !heads.has(validated.prHead)) return blocked("head-moved-after-label");
265
+ if (mainGain.usable && mainGain.exit === 1) return blocked(`main-gain-removed:${mainGain.payload.hits[0].path}`);
212
266
  if (usable && ciRead.notGreen) return blocked(`ci:${validated.reasons[0]}`);
213
267
  if (usable && validated.behind > 0) return blocked(`behind:${validated.behind}`);
214
268
  if (!usable) return unknown(ciRead.rateLimited ? "rate-limited" : "ci-unreadable");
@@ -216,6 +270,7 @@ function decide(instruments, prView, ciRead) {
216
270
  if (instruments.exit === 1) return unknown("instrument-set-changed");
217
271
  if (instruments.exit !== 0) return unknown("instruments-unanswerable");
218
272
  if (prView === null) return unknown("pr-unreadable");
273
+ if (!mainGain.usable) return unknown("main-gain-unanswerable");
219
274
  return { verdict: "mergeable", reason: null };
220
275
  }
221
276
 
@@ -227,8 +282,9 @@ const EXIT = { mergeable: 0, blocked: 1, unknown: 2 };
227
282
  try {
228
283
  const instruments = readInstruments();
229
284
  const prView = readPr();
285
+ const mainGain = readMainGain(instruments.root, prView);
230
286
  const ciRead = readCi();
231
- const { verdict, reason } = decide(instruments, prView, ciRead);
287
+ const { verdict, reason } = decide(instruments, prView, mainGain, ciRead);
232
288
  const line = `${JSON.stringify({
233
289
  pr,
234
290
  verdict,
@@ -238,6 +294,7 @@ try {
238
294
  post,
239
295
  behind: ciRead.usable ? ciRead.ci.behind : null,
240
296
  instruments: instruments.digest,
297
+ mainGain: mainGain.payload,
241
298
  ci: ciRead.ci,
242
299
  })}\n`;
243
300
  // The file first: if it cannot be written, the gate refuses (exit 2)
@@ -1473,7 +1473,7 @@ for a token on a ticket's line — never a hand edit.
1473
1473
  |---|---|
1474
1474
  | Implementer report | `verify-sha.sh`; `ledger.mjs settle impl-<N>=PR#<M>`, or `=bailed` and relabel by cause (**Implementer bails before implementing**, below) |
1475
1475
  | Review workflow notification / `review-pr-<n>` report | write `<scratch>/review-<pr>.json`; `reviewed=<head>:<survived>/<refuted>/<unverified>` on the PR's row (**Reviewers**) |
1476
- | Fix-applier report | `ledger.mjs settle fix-pr-<M>=…`; for a fix-applier that answered a review — not one that cleared a conflict hold, which has no review file — `~/.fleet/bin/fleet-run dispositions-check.mjs --member <that member> --scratch <scratch>`, from the checkout root: it judges `<scratch>/dispositions-<M>.json` against `<scratch>/review-<M>.json`, writes `dispositions-ok=`, `dispositions-mismatch=` or `dispositions-escalate=<member>:<head>` onto the PR's row itself, and exits 1 on a mismatch or an escalation, naming each violating or escalated entry's bucket and index, a violation its rule too — **Then dispatch a fix-applier** says what a mismatch asks of you, the gate paragraph below what an escalation does; copy the refutations it reversed — the record's `refuted` entries — to `ruled`; `ledger.mjs filed <N> "<subject>"` for each `unrecorded:` line |
1476
+ | Fix-applier report | `ledger.mjs settle fix-pr-<M>=…`; for a fix-applier that answered a review — not one that cleared a conflict hold, which has no review file — `~/.fleet/bin/fleet-run dispositions-check.mjs --member <that member> --scratch <scratch>`, from the checkout root: it judges `<scratch>/dispositions-<M>.json` against `<scratch>/review-<M>.json`, writes `dispositions-ok=`, `dispositions-mismatch=`, `dispositions-escalate=` or `dispositions-unchecked=<member>:<head>` onto the PR's row itself, and exits 1 on a mismatch, an escalation or an unchecked, naming each violating or escalated entry's bucket and index, a violation its rule too, and each entry whose filed issue `gh` could not read — **Then dispatch a fix-applier** says what a mismatch asks of you, the gate paragraph below what an escalation or an unchecked does; copy the refutations it reversed — the record's `refuted` entries — to `ruled`; `ledger.mjs filed <N> "<subject>"` for each `unrecorded:` line |
1477
1477
  | Finisher report | `ledger.mjs settle finisher-pr-<M>=labelled` as reported, even when its read-back lacks `ready-to-merge` — the tick's `DISPATCH finisher PR#<M>` catches that next. A **repair** finisher's (one sent on that line) read-back lacking it also gets `gh pr comment <M>` with both finishers' read-backs: the one-shot escalation, where halts comment. `ledger.mjs filed <N> "<subject>"` for each `unrecorded:` line |
1478
1478
  | Finisher report (halted) | `ledger.mjs settle finisher-pr-<M>=halted:<cause>`; `gh pr comment <M>` with the finisher's halt report, cause and evidence; `ledger.mjs filed <N> "<subject>"` for each `unrecorded:` line; then the per-cause rule (**Resolving a finisher halt**, below) |
1479
1479
  | Finisher report (failed / killed) | `ledger.mjs settle finisher-pr-<M>=failed` for a finisher that crashed or gave up, `=killed` for one that was killed; no label, and the tick prints no dispatch for it. The cockpit flags the PR `finisher:failed` / `finisher:killed` at severity 4 and you resolve it by hand (**Resolving a finisher that died**, below) |
@@ -2533,9 +2533,15 @@ fix-applier's `no-op` and its `ok` verdict are what open the finisher. The
2533
2533
  refusal names its cause. `dispositions
2534
2534
  unchecked` — no verdict answers that head: run `dispositions-check.mjs` for
2535
2535
  the fix-applier that answered the review, as the Fix-applier report edge
2536
- states, then dispatch again. `dispositions mismatch` — no finisher: the tick
2537
- prints `DISPATCH fix-pr PR#<M>` for it, and the next-suffix fix-applier answers
2538
- it (**Then dispatch a fix-applier**). `dispositions escalate` — no finisher, no
2536
+ states, then dispatch again. It names a `dispositions-unchecked=` verdict too —
2537
+ no rule broke, but the check could not read where a deferral was filed, `gh`
2538
+ unreachable or an issue unreadable: run the check again for that fix-applier
2539
+ once `gh` answers (an issue that does not exist is unreadable too, and no re-run
2540
+ answers that one: the check's stderr names it, and the record's issue number
2541
+ needs correcting); the tick offers no fix-applier for it. `dispositions
2542
+ mismatch` — no finisher: the tick prints `DISPATCH fix-pr PR#<M>` for it, and
2543
+ the next-suffix fix-applier answers it (**Then dispatch a fix-applier**).
2544
+ `dispositions escalate` — no finisher, no
2539
2545
  retry and no further fix-applier: either a `critical` or `important` finding was
2540
2546
  deferred `remedy-outside-diff`, or a second mismatch was drawn on one review, and
2541
2547
  only a human can rule on either. Post the check's output, which names each
@@ -3589,6 +3595,8 @@ Plan it as a PR the run's own merge queue lands, never as an edit-and-continue.
3589
3595
  | Merge bot hits the hold rule | Report `held-behind-#<lower>`, PR stays queued |
3590
3596
  | Merge bot finds the worktree ahead of the PR head **on the local-rebase fallback** | `worktree-diverged-#<pr>`, PR stays queued. Read the stray commit; push-or-discard is yours, and the maintainer's if the evidence cannot settle it |
3591
3597
  | Merge bot finds the head moved after `ready-to-merge` was applied | `head-moved-after-label-#<pr>`, PR stays queued, label untouched. Dispatch a **fresh** finisher against the new head — the first audit verified a different tree |
3598
+ | Merge bot's gate finds the merge would remove lines `main` gained after the PR's work began (`main-gain-removed:<path>`, exit 1) | Relay `main-gain-removed:<path>-#<pr>` to a human with the hit list and the acknowledgement keys the bot printed. PR stays queued, label untouched, nothing written to the ledger, and no member is dispatched to restore the lines — the removal may be deliberate. It clears when the PR stops removing them or its body carries `main-gain-removal: <path> <key> - <why>` for each hit |
3599
+ | Merge bot's gate cannot answer the main-gain check (`main-gain-unanswerable`, exit 2) | Report `main-gain-unanswerable-#<pr>` with what it printed, PR stays queued, label untouched |
3592
3600
  | Merge bot cannot resolve a rebase safely | Stop that PR, report, continue. On a conflict the bot has already appended `conflict-hold:#<pr>` to the PR's row; the tick prints `DISPATCH fix-pr PR#<pr>` and holds the merge until that fix-applier settles |
3593
3601
  | Merge bot's gate refuses on its instrument re-check (`instrument-set-changed` or `instruments-unanswerable`, exit 2) | Report `<reason>-#<pr>` with what it printed, PR stays queued, label untouched. Do not re-run the gate |
3594
3602
  | Member silent or truncated | Send to ping or resume — same unit of work; see the state machine below |