@feigi/fleet-ctl 3.143.0 → 3.143.2

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.
@@ -122,9 +122,9 @@ For each labeled PR, lowest first:
122
122
 
123
123
  This also repairs a branch carrying a merge commit — GitHub's rebase drops those too.
124
124
 
125
- **A worktree for this branch, if one exists, goes stale here** — the API rebased the remote, not your checkout. Expected, not a divergence. To prove it holds nothing unique, run `git cherry origin/<branch> HEAD` from the worktree **before the merge, never after**, and **not** `git cherry origin/main HEAD`: `main` never contained this PR's commits before the merge either, so it reads `+` for all of them regardless of staleness and proves nothing (measured). The window is the point: step 4 deletes the remote branch once the PR lands (`delete-merged-branch.sh`; a repo that auto-deletes head branches removes it at the merge itself), so `origin/<branch>` outlives the merge only until the next pruning fetch, and step 4's `prove-merge.sh` runs one seconds later (`grep -n 'git fetch --quiet origin' scripts/prove-merge.sh`, plain, which prunes under the `fetch.prune=true` this machine's global config sets — `git config --show-origin --get fetch.prune`). Past that fetch the probe fails on a missing ref, an error easy to misread as the divergence it was meant to rule out.
125
+ **A worktree for this branch, if one exists, goes stale here** — the API rebased the remote, not your checkout. Expected, not a divergence. To prove it holds nothing unique, read it against `origin/<branch>` from the worktree **before the merge, never after** — `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run unique-in-upstream.mjs --worktree <worktree> --upstream origin/<branch>` — and **not** against `origin/main`: `main` never contained this PR's commits before the merge either, so it reads unique for all of them regardless of staleness and proves nothing (measured). The window is the point: step 4 deletes the remote branch once the PR lands (`delete-merged-branch.sh`; a repo that auto-deletes head branches removes it at the merge itself), so `origin/<branch>` outlives the merge only until the next pruning fetch, and step 4's `prove-merge.sh` runs one seconds later (`grep -n 'git fetch --quiet origin' scripts/prove-merge.sh`, plain, which prunes under the `fetch.prune=true` this machine's global config sets — `git config --show-origin --get fetch.prune`). Past that fetch the probe fails on a missing ref, an error easy to misread as the divergence it was meant to rule out.
126
126
 
127
- **Neither result halts this path, and a `+` here is not the diverged-worktree STOP.** The clean answer is the absence of a `+`, not the absence of output: `git cherry` prints a line per commit in `origin/<branch>..HEAD`, `-` where the upstream already holds an equivalent patch and `+` where it does not, so it never goes silent merely because the rebase superseded everything. A worktree that has not fetched since the API rebase — the state this step leaves it in, since no local git command runs here — reads nothing; one that has fetched reads `-` for every rebased commit. Both are clean (measured 2026-08-29 in a scratch repo: a bare remote, a branch rebased onto an advanced `main` and force-pushed, and a clone left at the pre-rebase head — `git cherry origin/feat HEAD` printed nothing before that clone fetched and a `-` per rebased commit after, while an unpushed commit added on top raised a `+` in both). A `+` names a commit the worktree holds and that branch does not — say so alongside the merge, since it is the only signal that something local is unpushed, but it does not stop the merge, because nothing local reaches the remote from here: this step rebases through the API and pushes nothing, and step 4 merges the remote head, so an unpushed local commit is structurally unable to enter the merge. That STOP lives in the fallback (server-side rebase unavailable) and does not halt for the reason just ruled out here: neither path can carry a local commit to the remote, because neither pushes. What differs is what gets verified — the fallback rebases the worktree and verifies *that* head, so a commit only the worktree holds makes the verified tree something other than the reviewed head; here the worktree is only read, never rebased, so a `+` is a report, not a halt.
127
+ **Neither result halts this path, and `unique: true` here is not the diverged-worktree STOP.** The command prints one JSON line and exits 0 whichever way `unique` reads; the clean answer is `"unique": false`, not the absence of output, and the `listing` it carries, the raw `git cherry` output, is evidence and never the verdict. `unique` is true when any of three reads finds something: a `+` in that listing, a merge commit in `origin/<branch>..HEAD`, or a merge of HEAD into `origin/<branch>` that conflicts or makes a tree other than the branch's own. The `+` alone misses an unpushed commit that repeats a change the branch carries at another place in the file, or differs from it by whitespace alone, because a patch id ignores position and whitespace and reads it `-`; the tree comparison alone misses a commit that reverts a change the branch carries, which only the `+` catches. So either read finding something is `unique: true`. A worktree that has not fetched since the API rebase — the state this step leaves it in, since no local git command runs here — reads nothing in `listing`; one that has fetched reads `-` for every rebased commit. Both are `unique: false` (measured 2026-08-29 in a scratch repo: a bare remote, a branch rebased onto an advanced `main` and force-pushed, and a clone left at the pre-rebase head — `git cherry origin/feat HEAD` printed nothing before that clone fetched and a `-` per rebased commit after, while an unpushed commit added on top raised a `+` in both). The exception is a fetched worktree whose branch carried a merge commit: the rebase drops the merge, so the worktree still holds a merge the branch lacks and reads `unique: true` though it holds no work of its own — `merges` above 0, `content.paths` empty, every `listing` line `-`. `unique: true` names something the worktree holds and that branch does not — say so alongside the merge, since it is the only signal that something local is unpushed, but it does not stop the merge, because nothing local reaches the remote from here: this step rebases through the API and pushes nothing, and step 4 merges the remote head, so an unpushed local commit is structurally unable to enter the merge. Exit 2 is no verdict — the read failed and the error is named — so report the worktree as unread, never as clean; it halts nothing here either. That STOP lives in the fallback (server-side rebase unavailable) and does not halt for the reason just ruled out here: neither path can carry a local commit to the remote, because neither pushes. What differs is what gets verified — the fallback rebases the worktree and verifies *that* head, so a commit only the worktree holds makes the verified tree something other than the reviewed head; here the worktree is only read, never rebased, so `unique: true` is a report, not a halt.
128
128
 
129
129
  **Two, and only two, reasons this can't be used:** a real conflict, or `allow_update_branch` off on the repo. Both are whole-branch failures — GitHub's rebase replays every commit or none, no partial credit. Either → the fallback below, not a retry.
130
130
 
@@ -144,7 +144,7 @@ For each labeled PR, lowest first:
144
144
 
145
145
  **Unequal → `git fetch origin` and read the ref once more, then decide on that second reading. Bounded at one re-read, never a third.** Neither operand is a cached value, so a stable second reading cannot flip the verdict; what the re-read is for is the ref MOVING while you verify, which is live here because one way into this fallback is a step-1 poll whose cap ran out with the ref unmoved, and that call is async — it can land a moment after you gave up on it. The two readings differ → the head is not settled and the audit behind the label verified a tree that is already gone, so **refuse: report `head-moved-after-label-#<pr>` and stop**, label untouched, the same verdict and the same remedy — a fresh finisher against the new head — the gate above reaches for a head that moved after the audit. Do not read a third time; that is the unbounded wait step 1 had to be written out of. The two readings agree → the mismatch is real and belongs to one of the two arms below. **`Equal` is not among the outcomes a surviving mismatch can reach**: a worktree that is not on the branch ref never passes this check, whatever the PR object says.
146
146
 
147
- **Ahead or behind is `git cherry origin/<branch> HEAD` from the worktree, run after that fetch — not the sha compare.** A rebase orphans the pre-rebase head, so the ref does not carry the worktree's commits BY SHA even where it carries every patch in them; read the mismatch as "commits the ref lacks" and a worktree holding no work of its own answers yes and takes the STOP. Patch equivalence is the question, and `git cherry` is the instrument this step already uses for it: a `+` → ahead; no `+` → behind, a worktree the rebase superseded included.
147
+ **Ahead or behind is the `unique` verdict of `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run unique-in-upstream.mjs --worktree <worktree> --upstream origin/<branch>`, run after that fetch — not the sha compare.** A rebase orphans the pre-rebase head, so the ref does not carry the worktree's commits BY SHA even where it carries every patch in them; read the mismatch as "commits the ref lacks" and a worktree holding no work of its own answers yes and takes the STOP. Patch equivalence is the question, and the verdict is not a raw `git cherry` line: a patch id ignores position and whitespace, so an unpushed commit that repeats a change the branch carries elsewhere in the file, or differs from it by whitespace alone, reads `-` there and the STOP would not fire. The script reads `unique` true when `git cherry` shows a `+`, `origin/<branch>..HEAD` holds a merge commit, or merging HEAD into `origin/<branch>` conflicts or makes a tree other than the branch's own: `"unique": true` → ahead; `"unique": false` → behind, a worktree the rebase superseded included — unless its branch carried a merge commit the rebase dropped. The worktree still holds that merge, so it reads `"unique": true` with `merges` above 0, `content.paths` empty and every `listing` line `-`, and takes the STOP as ahead though it holds no work of its own; say in the report that the merge is all it holds. Exit 2 is no verdict — the read failed and the error is named — and is not behind: take the STOP, report `worktree-diverged-#<pr>` and quote the error.
148
148
 
149
149
  - **Equal** → proceed.
150
150
  - **Worktree ahead** → STOP, report `worktree-diverged-#<pr>`. A fix-agent that committed locally but never pushed, or was aborted mid-fix, leaves an unpushed, unreviewed commit that a clean-tree audit passes. Nothing on this path pushes, so that commit cannot enter the merge — what it corrupts is the verification: rebase on top of it and both the `origin/main...HEAD` diff and the suite run against a tree that is not the reviewed head, while any merge takes the remote head, so the content-equivalence this path depends on is gone and a green says nothing about what would land. It fails silently, which is why this halts rather than proceeding on the green. The reviewed head lives on the remote, not here; hand the choice back with the PR.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.143.0",
3
+ "version": "3.143.2",
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": {
@@ -89,6 +89,8 @@
89
89
  // replay, so each of those is an unpaired line.
90
90
  // - a `commit` entry, amend and merge commits included: a member kept
91
91
  // working after the dispatch, or a remote rebase superseded this worktree.
92
+ // The two tests are `uniqueIn()` of unique-in-upstream.mjs, which the merge
93
+ // bot runs as a command; what follows is what it does.
92
94
  // A range holds nothing unique only when two tests both find nothing. By
93
95
  // patch: `git cherry <upstream> HEAD` prints no `+` line and `git
94
96
  // rev-list --merges --count <upstream>..HEAD` is 0 - `git cherry` never
@@ -159,6 +161,7 @@ import { basename, dirname, join, resolve } from "node:path";
159
161
  import { fileURLToPath } from "node:url";
160
162
  import { makeDie, defineFlags, writeAll } from "./arg.mjs";
161
163
  import { gitEnv } from "./git-env.mjs";
164
+ import { UniqueReadError, uniqueIn as uniqueInWorktree } from "./unique-in-upstream.mjs";
162
165
 
163
166
  const NAME = "finisher-audit";
164
167
  const die = makeDie(NAME);
@@ -253,12 +256,11 @@ function run(cmd, args, options = {}) {
253
256
 
254
257
  // A git call inside the worktree. A call that could not run, was killed or
255
258
  // exited non-zero stops the audit at exit 2 unless the caller asked to read the
256
- // failure itself (`soft`), which then carries the exit status and the stdout
257
- // the call left.
259
+ // failure itself (`soft`), which then carries the error.
258
260
  function git(step, args, { soft = false, timeout } = {}) {
259
261
  const r = run("git", ["-C", realpath, ...args], timeout === undefined ? {} : { timeout });
260
262
  if (r.error || r.signal || r.status !== 0) {
261
- if (soft) return { ok: false, status: r.status, out: r.stdout ?? "", error: (r.error?.message ?? r.stderr ?? "").trim() || `exit ${r.status ?? r.signal}` };
263
+ if (soft) return { ok: false, error: (r.error?.message ?? r.stderr ?? "").trim() || `exit ${r.status ?? r.signal}` };
262
264
  const why = r.error?.message ?? (r.signal ? `killed by ${r.signal}` : (r.stderr ?? "").trim() || `exit ${r.status}`);
263
265
  fail(`${step}: git ${args.join(" ")} failed: ${why}`);
264
266
  }
@@ -288,47 +290,16 @@ function remoteState(branch, head) {
288
290
  return { state: r.sha === head ? "pushed" : "differs", ref: r.ref, sha: r.sha };
289
291
  }
290
292
 
291
- // The tree id `git merge-tree --write-tree` prints first.
292
- const TREE_ID = /^[0-9a-f]{40}$/;
293
-
294
- // What merging `HEAD` into `upstream` makes, read by `git merge-tree`'s exit
295
- // code and the tree id on the first line of its stdout: exit 0 is a merge that
296
- // went through, exit 1 with a tree id a conflict, which is a finding. Exit 1
297
- // with no tree id is git refusing a revision it cannot merge, so the exit code
298
- // alone cannot tell a conflict from it. That, exit 128 (unrelated histories
299
- // among its causes), a signal and a spawn error are reads that failed: exit 2.
300
- // The merge's tree and blob objects are written to the object store; no ref and
301
- // no file of the worktree moves.
302
- function mergeInto(upstream) {
303
- const args = ["merge-tree", "--write-tree", upstream, "HEAD"];
304
- const merge = git("merge-tree", args, { soft: true });
305
- const tree = merge.out.split("\n")[0];
306
- if (!TREE_ID.test(tree) || (!merge.ok && merge.status !== 1)) {
307
- fail(`merge-tree: git ${args.join(" ")} failed: ${merge.error ?? "no tree id on stdout"}`);
308
- }
309
- return { tree, conflict: !merge.ok };
310
- }
311
-
312
- // The paths where `tree` differs from `upstream`'s own tree, none for a tree
313
- // that is its own.
314
- function changedPaths(upstream, tree) {
315
- return git("paths", ["diff-tree", "-r", "--name-only", "-z", `${upstream}^{tree}`, tree]).out.split("\0").filter((p) => p !== "");
316
- }
317
-
318
- // What `HEAD` holds that `upstream` lacks, by two tests, either of which finds
319
- // it. By patch: `git cherry` prints `+` for a commit whose patch `upstream` does
320
- // not carry, `-` for one it does. It never lists a merge commit, so a merge's
321
- // own content is invisible to it and a merge in the range counts as unique. By
322
- // content: merging `HEAD` into `upstream` conflicts or makes a tree other than
323
- // `upstream`'s own. An `upstream` the object store lacks fails the read, exit
324
- // 2, and so does a merge that could not be read.
293
+ // What `HEAD` holds that `upstream` lacks, by the two tests unique-in-upstream.mjs
294
+ // owns. A read that could not be made stops the audit at exit 2, as a failed git
295
+ // call anywhere above does.
325
296
  function uniqueIn(upstream) {
326
- const listing = git("cherry", ["cherry", upstream, "HEAD"]).out;
327
- const merges = Number(git("merges", ["rev-list", "--merges", "--count", `${upstream}..HEAD`]).out.trim());
328
- const merged = mergeInto(upstream);
329
- const content = { ...merged, paths: changedPaths(upstream, merged.tree) };
330
- const unique = merges > 0 || listing.split("\n").some((l) => l.startsWith("+")) || content.conflict || content.paths.length > 0;
331
- return { listing, merges, content, unique };
297
+ try {
298
+ return uniqueInWorktree(realpath, upstream, { env: GIT_ENV });
299
+ } catch (e) {
300
+ if (e instanceof UniqueReadError) fail(e.message);
301
+ throw e;
302
+ }
332
303
  }
333
304
 
334
305
  // `git range-diff` prints one line per pairing, `<n>: <sha> <marker> <m>: <sha>
package/scripts/reap.sh CHANGED
@@ -442,8 +442,10 @@ keep() {
442
442
  # silent (measured on this exact shape).
443
443
  #
444
444
  # The capture is `probe`, over any command; `git_probe` is `probe git`.
445
- # pr_load's gh call below is the one other caller: its stdout fields are
446
- # refnames, numbers, object ids and fixed words, none of which can hold 0x02.
445
+ # pr_load's gh call below is a caller too: its stdout fields are refnames,
446
+ # numbers, object ids and fixed words, none of which can hold 0x02. So are the
447
+ # pair test's `pq_ids`, which prints `git patch-id`'s hex pairs and nothing
448
+ # else, and its `pq_marked`, which prints object ids and nothing else.
447
449
  gp_sep=$(printf '\002')
448
450
  probe() {
449
451
  gp_raw=$(
@@ -998,6 +1000,141 @@ EOF
998
1000
  return 1
999
1001
  }
1000
1002
 
1003
+ # THE PAIR TEST. `git cherry` reads a commit as merged when $base carries a
1004
+ # commit with the same patch id, and a patch id ignores where in a file the
1005
+ # change sits and any whitespace in it. So a commit making a merged change
1006
+ # again at another place in the same file — the second of two identical
1007
+ # blocks — or differing from a merged commit only in whitespace reads `-`
1008
+ # although no other ref holds it. Measured, git 2.54.0 (Apple Git-157): a
1009
+ # claim's first commit squash-merged, its second, never pushed, making the
1010
+ # same change in the file's identical second block — `git cherry` prints `-`
1011
+ # for both.
1012
+ #
1013
+ # So where no line reads `+`, the tip is merged only when every commit in
1014
+ # $base_rev..tip also pairs: some commit M on $base carries its patch id
1015
+ # (`git patch-id --stable`), and `git merge-tree --write-tree --merge-base=C^
1016
+ # M^ C` writes exactly M's tree — C replayed onto M's parent is M. Anything
1017
+ # less is a KEEP with its reason: a merge commit in the range (`git cherry`
1018
+ # skips merges, so what a merge itself changes is read by nothing), a commit
1019
+ # no M carries the patch id of (an empty commit has none: a false keep, and a
1020
+ # harmless one), a replay that differs from or conflicts with every such M,
1021
+ # and any probe that fails. A `+` is not this test's: it keeps, or goes to the
1022
+ # second proof above, unchanged.
1023
+ #
1024
+ # M is looked for among the commits on $base that `git rev-list
1025
+ # --cherry-mark` marks `=` against this tip, so the diffs this script reads
1026
+ # are those commits' and the tip's own, never all of $base since the fork.
1027
+ # That listing itself still names every commit on $base since the fork, and
1028
+ # `probe` splits its capture with `${…#*sep}`, which bash 3.2 — macOS /bin/sh
1029
+ # — runs in time that grows faster than the capture: measured, doubling a
1030
+ # 1600-line capture took `probe` from 3.9s to 18.7s, and on a fork 3200
1031
+ # commits behind a dry run took 6.2s with the whole listing through `probe`
1032
+ # and 0.4s with the `=` ids alone, same payload. So
1033
+ # `pq_marked` keeps the listing to itself and prints only the `=` lines' ids,
1034
+ # and what reaches `probe` grows with the merged commits alone.
1035
+ # Safe for `probe`'s separator: rev-list and rev-parse print object ids and
1036
+ # fixed marks; merge-tree under `--no-messages --name-only` prints a tree id
1037
+ # and, on a conflict, the conflicted paths C-quoted (`"we\002ird"`, measured,
1038
+ # under core.quotePath false too); and `pq_ids` keeps the diff text, which can
1039
+ # hold any byte, to itself and prints only `git patch-id`'s hex pairs. Both of
1040
+ # its pipes read a variable, never git, so the status each returns is git's.
1041
+ # `pq_marked`'s pipe reads a variable too, and git's own status is taken
1042
+ # before it runs.
1043
+ # `merge-tree --write-tree` writes the trees it merges into the object store,
1044
+ # on a dry run too; it moves and deletes nothing.
1045
+ pq_ids() {
1046
+ pq_d=$(printf '%s\n' "$1" | git diff-tree --stdin -p) || return
1047
+ printf '%s\n' "$pq_d" | git patch-id --stable
1048
+ }
1049
+ pq_marked() {
1050
+ pq_l=$(git rev-list --cherry-mark --left-only --no-merges "$1") || return
1051
+ printf '%s\n' "$pq_l" | sed -n 's/^=//p'
1052
+ }
1053
+
1054
+ # Returns 0 when every commit on tip $1 that $base_rev lacks pairs, and 1 with
1055
+ # the reason in $pq_why when one does not or a probe fails.
1056
+ pair_test() {
1057
+ if ! git_probe rev-list --parents "$base_rev..$1"; then
1058
+ pq_why="pair test failed — cannot list the commits $base lacks$(gp_why)"
1059
+ return 1
1060
+ fi
1061
+ pq_cs=
1062
+ while read -r pq_c pq_p pq_more; do
1063
+ [ -n "$pq_c" ] || continue
1064
+ if [ -n "$pq_more" ]; then
1065
+ pq_why="commit $pq_c is a merge, and git cherry does not read what a merge itself changes"
1066
+ return 1
1067
+ elif [ -z "$pq_p" ]; then
1068
+ pq_why="commit $pq_c has no parent to replay it from"
1069
+ return 1
1070
+ fi
1071
+ pq_cs=${pq_cs:+$pq_cs
1072
+ }$pq_c
1073
+ done <<EOF
1074
+ $gp_out
1075
+ EOF
1076
+ [ -n "$pq_cs" ] || return 0
1077
+
1078
+ if ! probe pq_marked "$base_rev...$1"; then
1079
+ pq_why="pair test failed — cannot list the commits on $base to pair with$(gp_why)"
1080
+ return 1
1081
+ fi
1082
+ pq_ms=$gp_out
1083
+ pq_mids=
1084
+ if [ -n "$pq_ms" ]; then
1085
+ if ! probe pq_ids "$pq_ms"; then
1086
+ pq_why="pair test failed — cannot compute the patch ids of the commits on $base$(gp_why)"
1087
+ return 1
1088
+ fi
1089
+ pq_mids=$gp_out
1090
+ fi
1091
+ if ! probe pq_ids "$pq_cs"; then
1092
+ pq_why="pair test failed — cannot compute the patch ids of the commits $base lacks$(gp_why)"
1093
+ return 1
1094
+ fi
1095
+ pq_cids=$gp_out
1096
+
1097
+ for pq_c in $pq_cs; do
1098
+ pq_id=
1099
+ while read -r pq_i pq_o; do
1100
+ [ "$pq_o" != "$pq_c" ] || pq_id=$pq_i
1101
+ done <<EOF
1102
+ $pq_cids
1103
+ EOF
1104
+ pq_with=
1105
+ if [ -n "$pq_id" ]; then
1106
+ while read -r pq_i pq_o; do
1107
+ [ "$pq_i" != "$pq_id" ] || pq_with="$pq_with $pq_o"
1108
+ done <<EOF
1109
+ $pq_mids
1110
+ EOF
1111
+ fi
1112
+ if [ -z "$pq_with" ]; then
1113
+ pq_why="commit $pq_c reads patch-equivalent, but no commit on $base carries its patch id"
1114
+ return 1
1115
+ fi
1116
+ for pq_m in $pq_with; do
1117
+ if ! git_probe rev-parse --verify "$pq_m^{tree}"; then
1118
+ pq_why="pair test failed — cannot read the tree of $pq_m$(gp_why)"
1119
+ return 1
1120
+ fi
1121
+ pq_mt=$gp_out
1122
+ if git_probe merge-tree --write-tree --no-messages --name-only --merge-base="$pq_c^" "$pq_m^" "$pq_c"; then
1123
+ [ "$gp_out" != "$pq_mt" ] || continue 2
1124
+ elif [ "$gp_rc" -ne 1 ]; then
1125
+ pq_why="pair test failed — cannot replay commit $pq_c onto $pq_m^$(gp_why)"
1126
+ return 1
1127
+ fi
1128
+ done
1129
+ case "$pq_with" in
1130
+ *" "*" "*) pq_why="commit $pq_c reads patch-equivalent but is not identical to any of the merged commits$pq_with" ;;
1131
+ *) pq_why="commit $pq_c reads patch-equivalent but is not identical to the merged commit$pq_with" ;;
1132
+ esac
1133
+ return 1
1134
+ done
1135
+ return 0
1136
+ }
1137
+
1001
1138
  # %(upstream:track) emits exactly [gone] as its own field — nothing to
1002
1139
  # pattern-match, and no -v/-vv trap.
1003
1140
  #
@@ -1170,21 +1307,22 @@ for b in $gone_branches $nu_branches; do
1170
1307
  # verdict a genuinely clean cherry produces, so "merged" is indistinguishable
1171
1308
  # from "the probe could not answer". An unmerged branch is never the ambiguous
1172
1309
  # one: its `+` line makes grep exit 0 and always keeps. Of the checks that
1173
- # must pass before the delete, this is the only one that asks whether `$tip`
1174
- # is merged — the worktree checks below and the `worktree remove` refusal
1175
- # can each keep the branch, but none of them looks at its commits, and the
1176
- # compare-and-swap refuses a ref that moved off `$tip`, never a `$tip` that
1177
- # is unmerged — so an unanswerable probe must KEEP, the same fail-closed
1178
- # shape the worktree `status` check below already uses.
1310
+ # must pass before the delete, this and the pair test after it are the only
1311
+ # ones that ask whether `$tip` is merged — the worktree checks below and the
1312
+ # `worktree remove` refusal can each keep the branch, but none of them looks
1313
+ # at its commits, and the compare-and-swap refuses a ref that moved off
1314
+ # `$tip`, never a `$tip` that is unmerged — so an unanswerable probe must
1315
+ # KEEP, the same fail-closed shape the worktree `status` check below already
1316
+ # uses.
1179
1317
  # `refs/heads/$b`, never a bare `$b`, where the tip is read above. Restoring
1180
1318
  # the bare name makes a branch that shares its name with a tag ambiguous AS A
1181
1319
  # REV again, and git resolves an ambiguous one by preferring refs/tags/ over
1182
1320
  # refs/heads/ (measured, git 2.50.1 Apple Git-155). This probe would then
1183
1321
  # answer about the TAG's commit while the delete below removes the BRANCH —
1184
1322
  # and a tag sitting on a merged commit reports clean for a branch whose
1185
- # commits exist nowhere else. No other check before the delete asks whether
1186
- # those commits are merged, so that reads straight through to destroying
1187
- # them: measured on a fixture, the enumeration fix alone turned a branch
1323
+ # commits exist nowhere else. No other check before the delete then asked
1324
+ # whether those commits are merged, so that read straight through to
1325
+ # destroying them: measured on a fixture, the enumeration fix alone turned a branch
1188
1326
  # this script currently KEEPS into `REAPED`, at exit 0, with an empty
1189
1327
  # kept[]. Qualifying changes nothing for an ordinary branch — both spellings
1190
1328
  # name the same commit — and it is the same key the worktree lookup below
@@ -1198,8 +1336,8 @@ for b in $gone_branches $nu_branches; do
1198
1336
  # existed nowhere else REAPED at exit 0 with an empty kept[]. The
1199
1337
  # qualification is built at the top of the file, where its own comment
1200
1338
  # records why the accept-list beside it is what makes prefixing sound. Being
1201
- # the only merge check bounds what ELSE could catch an unmerged branch, not
1202
- # whether this check itself can be wrong — which is why BOTH revs it
1339
+ # one of only two merge checks bounds what ELSE could catch an unmerged
1340
+ # branch, not whether this check itself can be wrong — which is why BOTH revs it
1203
1341
  # consumes are qualified.
1204
1342
  elif ! cherry=$(git cherry "$base_rev" "$tip" 2>&1); then
1205
1343
  keep "$b" "cherry probe failed — cannot tell if merged: $(printf '%s' "$cherry" | tr '\n' ' ')"
@@ -1215,7 +1353,7 @@ for b in $gone_branches $nu_branches; do
1215
1353
  # exists for: taking it is not the same as READING it. grep answers three
1216
1354
  # ways, and the `if` once had two arms — an rc 2 scan that never
1217
1355
  # examined `$cherry` fell into the merged arm, and no check between here and
1218
- # the delete below asks whether the branch is merged. So the deletion went
1356
+ # the delete below then asked whether the branch is merged. So the deletion went
1219
1357
  # ahead on a merge status no tool had established. `grep_probe` splits the two
1220
1358
  # questions; the answers are ruled on here, in the order that makes the
1221
1359
  # unanswerable case fail CLOSED like every other could-not-check in this
@@ -1241,6 +1379,11 @@ for b in $gone_branches $nu_branches; do
1241
1379
  keep "$b" "unmerged commits — $pr_why"
1242
1380
  continue
1243
1381
  fi
1382
+ # No `+`: merged only if every commit the tip holds and $base lacks pairs
1383
+ # with one $base carries — the pair test, its header above the loop.
1384
+ elif ! pair_test "$tip"; then
1385
+ keep "$b" "$pq_why"
1386
+ continue
1244
1387
  fi
1245
1388
 
1246
1389
  # The listing is read per branch, through worktree.sh's `wt_counts`, which
@@ -1905,6 +2048,11 @@ else
1905
2048
  elif [ "$gq_rc" -eq 0 ]; then
1906
2049
  keep "" "worktree $wt holds commits that exist nowhere else"
1907
2050
  continue
2051
+ # No `+`: the pair test, as in the branch sweep; its header is above that
2052
+ # sweep's loop.
2053
+ elif ! pair_test "$head"; then
2054
+ keep "" "worktree $wt — $pq_why"
2055
+ continue
1908
2056
  fi
1909
2057
 
1910
2058
  if [ -e "$wt" ]; then
@@ -1455,8 +1455,9 @@ else
1455
1455
  # update-ref, authorized by the `ahead` and `git cherry` guards above,
1456
1456
  # this recount, and the worktree check above — and carrying its own
1457
1457
  # compare-and-swap on $tip on top, which `-D` never had. reap.sh asks
1458
- # whether its own [gone] branches are merged with `git cherry` alone — no
1459
- # `ahead` count, no recount — so not this pairing, though it too
1458
+ # whether its own [gone] branches are merged with `git cherry` and a pair
1459
+ # test that replays each commit onto the one it matches — no `ahead`
1460
+ # count, no recount — so not this pairing, though it too
1460
1461
  # re-checks the worktree with `wt_holding` before its own compare-and-swap
1461
1462
  # delete. `-d` measures against HEAD and the branch's upstream, and a
1462
1463
  # claim has no upstream until its first push (claim-ticket.sh passes
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ // What a worktree's HEAD holds that an upstream lacks, as one verdict, so every
3
+ // reader that asks "is anything here unpushed or unreviewed?" asks it by the
4
+ // same two tests and none of them reads a raw `git cherry` line instead.
5
+ // `finisher-audit.mjs` imports `uniqueIn()`; the merge bot runs the command:
6
+ //
7
+ // unique-in-upstream.mjs --worktree <path> --upstream <ref>
8
+ //
9
+ // `--worktree` is the checkout read, `--upstream` the revision HEAD is compared
10
+ // with: a branch's remote-tracking ref, or a commit. Reached through the
11
+ // Resolver: `~/.omp/plugins/node_modules/@feigi/fleet-ctl/scripts/fleet-run unique-in-upstream.mjs ...`.
12
+ // Nothing is fetched: an `--upstream` the object store lacks fails the read.
13
+ //
14
+ // Stdout is one JSON line, the verdict:
15
+ //
16
+ // {worktree, upstream, listing, merges, content: {tree, conflict, paths}, unique}
17
+ //
18
+ // listing `git cherry <upstream> HEAD`, verbatim
19
+ // merges `git rev-list --merges --count <upstream>..HEAD`
20
+ // content the merge-tree read: `tree` is the tree id merging HEAD into
21
+ // `<upstream>` makes, `conflict` a boolean, and `paths` the files where
22
+ // `tree` differs from `<upstream>`'s own tree, none when it is clean
23
+ // unique true when HEAD holds something `<upstream>` lacks
24
+ //
25
+ // What HEAD holds that `upstream` lacks, by two tests, either of which finds
26
+ // it. By patch: `git cherry` prints `+` for a commit whose patch `upstream` does
27
+ // not carry, `-` for one it does. It never lists a merge commit, so a merge's
28
+ // own content is invisible to it, and a merge in the range counts as unique. By
29
+ // content: merging HEAD into `upstream` conflicts or makes a tree other than
30
+ // `upstream`'s own. Neither test is enough alone. A patch id ignores line
31
+ // numbers and whitespace, so by patch alone a commit that makes `upstream`'s
32
+ // change at another place in the file, the same lines around it, or that
33
+ // differs from one of its commits by whitespace alone, reads clean though
34
+ // `upstream` lacks its content. By content alone, a commit that undoes a change
35
+ // `upstream` carries reads clean: merging it in changes nothing, and only its
36
+ // `+` line catches it.
37
+ //
38
+ // `git merge-tree --write-tree` is read by its exit code and the tree id on the
39
+ // first line of its stdout. Exit 0 with a tree id is a merge that went through,
40
+ // clean or not by the comparison above. Exit 1 with a tree id is a conflict,
41
+ // which is a finding, never a failure. Anything else is a failed read: exit 1
42
+ // with no tree id (git also exits 1 on a revision it cannot merge), exit 128
43
+ // (on unrelated histories, for one), a signal or a spawn error. The merge's
44
+ // tree and blob objects are written to the object store; no ref and no file of
45
+ // the worktree moves.
46
+ //
47
+ // Exit vocabulary:
48
+ //
49
+ // 0 a verdict: read `unique`, which is true or false. Never an exit code for
50
+ // it, so a caller that only reads the exit status cannot take "something
51
+ // unique" for a failure of the read.
52
+ // 2 no verdict: a usage refusal, a read that failed, or a verdict that could
53
+ // not be written to stdout. A failed read prints `{worktree, upstream,
54
+ // error}` on stdout, `error` naming the call, and the message on stderr.
55
+ // It is never a clean answer.
56
+
57
+ import { spawnSync } from "node:child_process";
58
+ import { makeDie, defineFlags, writeAll } from "./arg.mjs";
59
+ import { gitEnv } from "./git-env.mjs";
60
+ import { isCLI } from "./is-cli.mjs";
61
+
62
+ const NAME = "unique-in-upstream";
63
+ // One git child's stdout: far past spawnSync's 1 MiB default for a merge that
64
+ // changes many paths.
65
+ const BUFFER = 256 * 1024 * 1024;
66
+ // The tree id `git merge-tree --write-tree` prints first.
67
+ const TREE_ID = /^[0-9a-f]{40}$/;
68
+
69
+ // A read that could not be made: a call that did not run, was killed, or
70
+ // exited with a status that is not an answer. The message names the step and
71
+ // the git call, and is what a caller reports.
72
+ export class UniqueReadError extends Error {}
73
+
74
+ // What HEAD of `worktree` holds that `upstream` lacks: `{listing, merges,
75
+ // content, unique}`. Throws `UniqueReadError` for any read that could not be
76
+ // made - an `upstream` the object store lacks, a merge that could not be read -
77
+ // so a failed read is never a clean verdict. `env` is the environment of every
78
+ // git child: the ambient one with GIT_DIR and GIT_WORK_TREE scrubbed when
79
+ // omitted.
80
+ export function uniqueIn(worktree, upstream, { env = gitEnv() } = {}) {
81
+ // A git call inside the worktree. A call that could not run, was killed or
82
+ // exited non-zero throws, unless the caller asked to read the failure itself
83
+ // (`soft`), which then carries the exit status and the stdout the call left.
84
+ const git = (step, args, { soft = false } = {}) => {
85
+ const r = spawnSync("git", ["-C", worktree, ...args], { encoding: "utf8", env, maxBuffer: BUFFER });
86
+ if (r.error || r.signal || r.status !== 0) {
87
+ if (soft) return { ok: false, status: r.status, out: r.stdout ?? "", error: (r.error?.message ?? r.stderr ?? "").trim() || `exit ${r.status ?? r.signal}` };
88
+ const why = r.error?.message ?? (r.signal ? `killed by ${r.signal}` : (r.stderr ?? "").trim() || `exit ${r.status}`);
89
+ throw new UniqueReadError(`${step}: git ${args.join(" ")} failed: ${why}`);
90
+ }
91
+ return { ok: true, out: r.stdout, error: null };
92
+ };
93
+
94
+ const listing = git("cherry", ["cherry", upstream, "HEAD"]).out;
95
+ const merges = Number(git("merges", ["rev-list", "--merges", "--count", `${upstream}..HEAD`]).out.trim());
96
+
97
+ // Exit 1 with no tree id is git refusing a revision it cannot merge, so the
98
+ // exit code alone cannot tell a conflict from it.
99
+ const mergeArgs = ["merge-tree", "--write-tree", upstream, "HEAD"];
100
+ const merge = git("merge-tree", mergeArgs, { soft: true });
101
+ const tree = merge.out.split("\n")[0];
102
+ if (!TREE_ID.test(tree) || (!merge.ok && merge.status !== 1)) {
103
+ throw new UniqueReadError(`merge-tree: git ${mergeArgs.join(" ")} failed: ${merge.error ?? "no tree id on stdout"}`);
104
+ }
105
+ const paths = git("paths", ["diff-tree", "-r", "--name-only", "-z", `${upstream}^{tree}`, tree]).out.split("\0").filter((p) => p !== "");
106
+ const unique = merges > 0 || listing.split("\n").some((l) => l.startsWith("+")) || !merge.ok || paths.length > 0;
107
+ return { listing, merges, content: { tree, conflict: !merge.ok, paths }, unique };
108
+ }
109
+
110
+ function main() {
111
+ const die = makeDie(NAME);
112
+ const { arg, sweep, stray } = defineFlags(die, { flags: { worktree: "value", upstream: "value" } });
113
+ // The sweep runs before the required-flag check so a misspelled flag is named
114
+ // as that, not buried under a missing-flag usage line.
115
+ sweep();
116
+ stray();
117
+ const worktree = arg("worktree");
118
+ const upstream = arg("upstream");
119
+ if (worktree === null || upstream === null) die("usage: unique-in-upstream.mjs --worktree <path> --upstream <ref>");
120
+ try {
121
+ const verdict = uniqueIn(worktree, upstream);
122
+ if (!writeAll(1, `${JSON.stringify({ worktree, upstream, ...verdict })}\n`)) die("the verdict could not be written to stdout");
123
+ process.exit(0);
124
+ } catch (e) {
125
+ if (!(e instanceof UniqueReadError)) throw e;
126
+ writeAll(1, `${JSON.stringify({ worktree, upstream, error: e.message })}\n`);
127
+ die(e.message);
128
+ }
129
+ }
130
+
131
+ if (isCLI(import.meta.url)) main();
@@ -25,7 +25,8 @@ Every precondition recomputed **inside** same command as delete:
25
25
  - **A branch with no upstream is selected only when origin has no branch of its name and its merged PR recorded its tip.** `%(upstream)` is empty for it, so `%(upstream:track)` has no `[gone]` to match. It is selected when `refs/remotes/origin/<b>` is absent after the sweep's own `fetch --prune`, and the second proof below ties its tip, read once, to a head its merged PR recorded; `git cherry` neither authorizes nor vetoes it, and there is no name filter. A tip already on `origin/main` ties only by **equality** with a recorded head, never by ancestry: a claim is cut from whatever `origin/main` the clone last fetched, so a fresh claim that reuses a merged PR's branch name on a clone that has not fetched that merge has no commits of its own and a tip that is an ancestor of that PR's heads — ancestry would tie it, and the reap would remove the live member's clean worktree and branch. Every keep reads `no upstream — <cause>`; where there is no GitHub repository to ask (`BASE_REF` is not an `origin` ref, or `origin` is not a `host/owner/repo` URL) it is never selected and the reason stays `no upstream — never selected`. Once selected, the worktree guards, the holder check and the compare-and-swap below run on it as on a `[gone]` branch. Its upstream arrives with the first `-u` push, or when the controller settles the implementer's report.
26
26
  - **Recompute per branch, in this command.** Branch list from earlier tool call already false: one observed run listed 28 gone branches, two calls later 27 reaped by concurrent session. Benign direction is no-op; dangerous one is worktree that gained work *after* check.
27
27
  - **`git cherry origin/main`, not `git diff main..`.** Against `origin/main` — local `main` you never fast-forwarded reads every merged branch as unmerged. A `+` line is a commit with no patch-equivalent upstream, which is usually a commit that exists nowhere else but not always: a claim the merge bot rebased server-side onto a `main` that had changed its context lines carries a different patch id, so its original tip reads `+` although everything on it merged. That keep is safe but leaky, and the second proof below is what closes it.
28
- - **The delete is `git update-ref -d`'s compare-and-swap on a tip read once, authorized by that cherry check and by a fresh check, re-read immediately before the delete, that no worktree holds the branch.** Tip read before the cherry, cherry runs against that SHA, delete refuses unless ref still equals it — commit landing between check and delete is kept with git's own `cannot lock ref`, never force-deleted, as it was under `git branch -D`, the delete this replaced. `--no-deref`, so symref branch deletes the symref, not its target (measured). Branch's config section removed after, as `-D` did — left behind, re-created branch of same name inherits dead upstream and reads `[gone]` at once. `git branch -d` would refuse everything here: upstream gone, so falls back to comparing against `HEAD`, a possibly-behind local `main`. Never delete branch whose cherry output you did not just read.
28
+ - **A branch whose commits all read `-` is merged only if every one of them pairs.** A patch id ignores where in a file a change sits and any whitespace in it, so a commit making a merged change again at another place in the same file — the second of two identical blocks — or differing from a merged commit only in whitespace reads `-` while no other ref holds it. So each commit `C` that `origin/main` lacks has to pair: a commit `M` on `origin/main` carries `C`'s `git patch-id --stable`, and `git merge-tree --write-tree --merge-base=C^ M^ C` writes exactly `M`'s tree — `C` replayed onto `M`'s parent is `M`. Anything less is a KEEP with its reason: a merge commit in the range (`git cherry` skips merges, so what one changes is read by nothing), a commit no `M` carries the patch id of (an empty commit has none — a harmless false keep), a replay that differs from or conflicts with every such `M`, and any probe that fails. A `+` is not the pair test's to rule on; it keeps, or goes to the second proof below.
29
+ - **The delete is `git update-ref -d`'s compare-and-swap on a tip read once, authorized by that cherry check, the pair test above, and a fresh check, re-read immediately before the delete, that no worktree holds the branch.** Tip read before the cherry, cherry runs against that SHA, delete refuses unless ref still equals it — commit landing between check and delete is kept with git's own `cannot lock ref`, never force-deleted, as it was under `git branch -D`, the delete this replaced. `--no-deref`, so symref branch deletes the symref, not its target (measured). Branch's config section removed after, as `-D` did — left behind, re-created branch of same name inherits dead upstream and reads `[gone]` at once. `git branch -d` would refuse everything here: upstream gone, so falls back to comparing against `HEAD`, a possibly-behind local `main`. Never delete branch whose cherry output you did not just read.
29
30
  - **A branch any worktree holds is a KEEP, checked right before the delete.** `update-ref` consults no worktree; `-D` did. So listing is re-read and worktree.sh's `wt_holding` asks: held by a `branch` line, or by detached worktree stopped mid `rebase -i` / mid `bisect` on it (admin dir's `head-name` / `BISECT_START`) — both routes `-D` refused on. Worktree it cannot resolve, or listing that will not re-read, is a KEEP. `--apply` only, like the delete: dry run cannot predict this refusal — not the same limitation `-D`'s dry run had, since an unrelated worktree elsewhere in the listing that this check cannot resolve keeps every `[gone]` branch, and every selected one with no upstream, in the pass (see below), a repo-wide case `-D` never produced.
30
31
  - **A worktree that checked the branch out while the delete ran is caught after it, and the branch is put back.** git has no lock that stops `git worktree add <p> <b>` between that holder check and the delete, and such an add writes only the new worktree's `HEAD` — the ref does not move, so the compare-and-swap succeeds and leaves the worktree on a branch that no longer exists (measured, git 2.50.1). So worktree.sh's `wt_recheck_delete` re-reads the listing right after the delete — and again, up to 20 times 0.1s apart, while an add in progress is listed `locked initializing` — and when a worktree holds the branch, or the wait runs out, recreates it at the tip with a create-only `git update-ref`. The branch is a KEEP naming the worktree or the entry, and its config section stays. A restore that fails is a KEEP naming the tip, git's error and the command that restores it by hand — or, when something recreated the branch since the delete, the commit it now sits at, left as it is, since the create-only restore never overwrites it. The branch's reflog does not come back.
31
32
  - **A cherry that cannot answer is a KEEP.** Capture git's output; never pipe git itself: `cmd | grep -q` takes grep's exit status, never cmd's, so a `git cherry` that dies (rc 128 — one unreadable loose object is enough) prints nothing, grep exits 1, and a dead probe reads identical to "nothing unmerged" (verified, git 2.50.1). Unanswerable probe authorizes no delete — same fail-closed shape as `worktree remove` below. Read the `+` anchored, too: the capture folds stderr in, so an unanchored match reads a `+` in a diagnostic as a commit. Pinned by a test.
@@ -45,7 +46,7 @@ Above walk finds branch's worktree by `branch refs/heads/<name>` line `git workt
45
46
  So `reap.sh` enumerates worktrees git lists with **no `branch` line at all** and decides each on own state:
46
47
 
47
48
  - **Bounded to `*/.worktrees/*` — fleet's own worktree home — and everything outside it is a `kept` entry.** Branch sweep authorizes its branch delete on evidence PR merged (`%(upstream:track)` reads exactly `[gone]`). This sweep has none to read: branchless + clean + patch-equivalent also describes human's `git worktree add --detach` scratch checkout that was never ticket. Unbounded, `--apply` deleted it (measured in review). Bound is ownership, never contents.
48
- - **`git cherry` against `origin/main`, never `merge-base --is-ancestor`.** Branch was rebased before it merged, so tip fully upstream is patch-equivalent, not ancestor — ancestry answers no for exactly work that is safe. A `+` can also be context drift rather than missing work, so its keep is safe but leaky; this sweep's code is unchanged, and it has no branch name to look a PR up by. Subject is full object id off porcelain, so no refname shadows it.
49
+ - **`git cherry` against `origin/main`, never `merge-base --is-ancestor`.** Branch was rebased before it merged, so tip fully upstream is patch-equivalent, not ancestor — ancestry answers no for exactly work that is safe. A `+` can also be context drift rather than missing work, so its keep is safe but leaky; this sweep runs no second proof, having no branch name to look a PR up by. Where no line reads `+`, the tip has to pass the branch sweep's pair test too. Subject is full object id off porcelain, so no refname shadows it.
49
50
  - **Absent `branch` line is not by itself detached HEAD.** git prints none for worktree whose HEAD it cannot resolve either, reporting null object id instead — four measured corruption routes for admin `HEAD`. Nothing about such worktree decidable, so report and leave. Null id alone is not the test: unborn branch is legitimate null id and DOES carry `branch` line.
50
51
  - **A git operation in progress is a keep, and git is no backstop for it.** Measured, git 2.50.1 (Apple Git-155): `worktree remove` *without* `--force` removes worktree holding interrupted rebase, and one holding bisect, at rc 0. Both detach, both leave `status --porcelain` empty — so every other check passes them and sequencer state, todo list and original head go with directory. Interrupted rebase is exactly how fleet worktree wanders off its branch (see `release-ticket.sh`'s own stray guard).
51
52
  - **Every decline is a `kept` entry, `branch` null.** No branch to name. Gap was invisible precisely because nothing was reported.