@feigi/fleet-ctl 3.24.40 → 3.25.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.
@@ -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.25.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": {
@@ -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)
@@ -3589,6 +3589,8 @@ Plan it as a PR the run's own merge queue lands, never as an edit-and-continue.
3589
3589
  | Merge bot hits the hold rule | Report `held-behind-#<lower>`, PR stays queued |
3590
3590
  | 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
3591
  | 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 |
3592
+ | 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 |
3593
+ | 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
3594
  | 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
3595
  | 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
3596
  | Member silent or truncated | Send to ping or resume — same unit of work; see the state machine below |