@feigi/fleet-ctl 0.0.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.
Files changed (245) hide show
  1. package/.claude-plugin/plugin.json +9 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/agents/fleet-finisher.agent.md +7 -0
  5. package/agents/fleet-implementer-alt.agent.md +210 -0
  6. package/agents/fleet-implementer.agent.md +210 -0
  7. package/agents/fleet-merge-bot.agent.md +7 -0
  8. package/agents/fleet-review-comments.agent.md +40 -0
  9. package/agents/fleet-review-correctness.agent.md +43 -0
  10. package/agents/fleet-review-runner.agent.md +73 -0
  11. package/agents/fleet-review-silent-failure.agent.md +49 -0
  12. package/agents/fleet-review-simplify.agent.md +46 -0
  13. package/agents/fleet-review-snapshot.agent.md +24 -0
  14. package/agents/fleet-review-tests.agent.md +46 -0
  15. package/agents/fleet-review-types.agent.md +41 -0
  16. package/agents/fleet-review-verifier.agent.md +29 -0
  17. package/commands/review-and-fix.md +98 -0
  18. package/commands/run-merge-bot.md +357 -0
  19. package/commands/run-team-help.md +17 -0
  20. package/package.json +23 -0
  21. package/scripts/agent-test-dir-prose.test.mjs +59 -0
  22. package/scripts/agent-test.test.mjs +1636 -0
  23. package/scripts/ambient-git-vars-mjs-prose.test.mjs +354 -0
  24. package/scripts/ambient-git-vars-prose.test.mjs +192 -0
  25. package/scripts/ancestry-check-position-prose.test.mjs +175 -0
  26. package/scripts/apply-ruleset.test.mjs +420 -0
  27. package/scripts/arg-header-probes-prose.test.mjs +393 -0
  28. package/scripts/arg.mjs +600 -0
  29. package/scripts/arg.test.mjs +1354 -0
  30. package/scripts/board-cli.test.mjs +694 -0
  31. package/scripts/board-identity.test.mjs +429 -0
  32. package/scripts/board-liveness-banner.test.mjs +119 -0
  33. package/scripts/board-prev-shape.test.mjs +229 -0
  34. package/scripts/board-tryparse-null.test.mjs +119 -0
  35. package/scripts/board.html +471 -0
  36. package/scripts/board.mjs +2037 -0
  37. package/scripts/board.test.mjs +3086 -0
  38. package/scripts/brief-after-cut-prose.test.mjs +53 -0
  39. package/scripts/candidates-exit3-prose.test.mjs +302 -0
  40. package/scripts/candidates.mjs +674 -0
  41. package/scripts/candidates.test.mjs +2101 -0
  42. package/scripts/caveat-unification-prose.test.mjs +98 -0
  43. package/scripts/ci-comment-rot-prose.test.mjs +2025 -0
  44. package/scripts/ci-completes-premise-prose.test.mjs +257 -0
  45. package/scripts/ci-state-prose.test.mjs +113 -0
  46. package/scripts/ci-state.mjs +761 -0
  47. package/scripts/ci-state.test.mjs +1640 -0
  48. package/scripts/ci-vacuous-green.test.mjs +368 -0
  49. package/scripts/citation-sweep-prose.test.mjs +1572 -0
  50. package/scripts/claim-lifecycle.test.mjs +185 -0
  51. package/scripts/claim-ticket.sh +417 -0
  52. package/scripts/claim-ticket.test.mjs +1121 -0
  53. package/scripts/closing-keyword-prose.test.mjs +193 -0
  54. package/scripts/cockpit-launch-idempotent-prose.test.mjs +165 -0
  55. package/scripts/cockpit-tick-nonblocking.test.mjs +210 -0
  56. package/scripts/compute-board.mjs +579 -0
  57. package/scripts/compute-board.test.mjs +1060 -0
  58. package/scripts/compute-spend.mjs +329 -0
  59. package/scripts/compute-spend.test.mjs +451 -0
  60. package/scripts/cross-repo-citation-prose.test.mjs +156 -0
  61. package/scripts/cwd-isolation-pins.mjs +83 -0
  62. package/scripts/dedupe-guard-prose.test.mjs +243 -0
  63. package/scripts/derive-testcmd.sh +239 -0
  64. package/scripts/derive-testcmd.test.mjs +380 -0
  65. package/scripts/diff-stats.mjs +231 -0
  66. package/scripts/diff-stats.test.mjs +408 -0
  67. package/scripts/dispatch-block-golden-prose.test.mjs +1024 -0
  68. package/scripts/dispatch-block-pins-prose.test.mjs +615 -0
  69. package/scripts/drop-merged-label.sh +173 -0
  70. package/scripts/drop-merged-label.test.mjs +480 -0
  71. package/scripts/expected-jobs-prose.test.mjs +80 -0
  72. package/scripts/filing-bar-seat-prose.test.mjs +242 -0
  73. package/scripts/filing-claim-bar-prose.test.mjs +166 -0
  74. package/scripts/finisher-dispatch-premise-prose.test.mjs +312 -0
  75. package/scripts/finisher-halt-prose.test.mjs +106 -0
  76. package/scripts/finisher-name-prose.test.mjs +134 -0
  77. package/scripts/finisher-own-tree-prose.test.mjs +285 -0
  78. package/scripts/finisher-pin-race-prose.test.mjs +339 -0
  79. package/scripts/fix-applier-correction-rules-prose.test.mjs +201 -0
  80. package/scripts/fix-applier-result-file-prose.test.mjs +100 -0
  81. package/scripts/fleet-bootstrap +155 -0
  82. package/scripts/fleet-heartbeat.mjs +272 -0
  83. package/scripts/fleet-heartbeat.test.mjs +450 -0
  84. package/scripts/fleet-provenance +207 -0
  85. package/scripts/fleet-provenance.test.mjs +64 -0
  86. package/scripts/fleet-run +148 -0
  87. package/scripts/fleet-run.test.mjs +90 -0
  88. package/scripts/fleet-state.mjs +400 -0
  89. package/scripts/fleet-state.test.mjs +373 -0
  90. package/scripts/fleet-tick-prose.test.mjs +299 -0
  91. package/scripts/fleet-tick.mjs +832 -0
  92. package/scripts/fleet-tick.test.mjs +1332 -0
  93. package/scripts/force-with-lease-reason-prose.test.mjs +184 -0
  94. package/scripts/frontmatter-allowlist.json +64 -0
  95. package/scripts/frontmatter-check.mjs +256 -0
  96. package/scripts/frontmatter-check.test.mjs +436 -0
  97. package/scripts/git-env.mjs +124 -0
  98. package/scripts/git-env.test.mjs +149 -0
  99. package/scripts/git-status-untracked-mode-sweep.test.mjs +216 -0
  100. package/scripts/gone-walk.test.mjs +213 -0
  101. package/scripts/gp-sep-invariant-prose.test.mjs +188 -0
  102. package/scripts/head-moved-after-label-prose.test.mjs +233 -0
  103. package/scripts/immutable-body-claim-prose.test.mjs +413 -0
  104. package/scripts/implementer-model-tier.test.mjs +643 -0
  105. package/scripts/inflight-citation-prose.test.mjs +144 -0
  106. package/scripts/inflight-exit2-prose.test.mjs +81 -0
  107. package/scripts/inflight-probe-guard-prose.test.mjs +109 -0
  108. package/scripts/inflight-scan-scope-prose.test.mjs +57 -0
  109. package/scripts/inflight.sh +1106 -0
  110. package/scripts/inflight.test.mjs +2984 -0
  111. package/scripts/injection-control-prose.test.mjs +404 -0
  112. package/scripts/install-root-audit.test.mjs +464 -0
  113. package/scripts/instrument-check-prose.test.mjs +235 -0
  114. package/scripts/instruments.sh +394 -0
  115. package/scripts/instruments.test.mjs +787 -0
  116. package/scripts/issue-tracker-prose.test.mjs +71 -0
  117. package/scripts/json.sh +248 -0
  118. package/scripts/json.test.mjs +364 -0
  119. package/scripts/ledger-dispatch.test.mjs +516 -0
  120. package/scripts/ledger-grammar.mjs +85 -0
  121. package/scripts/ledger-grammar.test.mjs +142 -0
  122. package/scripts/ledger-read-require-file.test.mjs +197 -0
  123. package/scripts/ledger.mjs +1753 -0
  124. package/scripts/ledger.test.mjs +3554 -0
  125. package/scripts/line-distance-prose.test.mjs +245 -0
  126. package/scripts/liveness-rationale-prose.test.mjs +83 -0
  127. package/scripts/locale-pin-prose.test.mjs +189 -0
  128. package/scripts/member-outcome-prose.test.mjs +167 -0
  129. package/scripts/member-outcomes-header.test.mjs +148 -0
  130. package/scripts/member-outcomes-prose.test.mjs +63 -0
  131. package/scripts/member-outcomes.mjs +231 -0
  132. package/scripts/member-outcomes.test.mjs +507 -0
  133. package/scripts/member-prompt-prose.test.mjs +161 -0
  134. package/scripts/member-record.mjs +605 -0
  135. package/scripts/member-record.test.mjs +516 -0
  136. package/scripts/member-write-guard.mjs +279 -0
  137. package/scripts/member-write-guard.test.mjs +211 -0
  138. package/scripts/merge-commit-probe-prose.test.mjs +122 -0
  139. package/scripts/merge-gate.mjs +262 -0
  140. package/scripts/merge-gate.test.mjs +613 -0
  141. package/scripts/muted-git-guard-sweep.test.mjs +493 -0
  142. package/scripts/net-ssh-precedence-prose.test.mjs +91 -0
  143. package/scripts/net-watchdog-prose.test.mjs +79 -0
  144. package/scripts/net.sh +409 -0
  145. package/scripts/net.test.mjs +211 -0
  146. package/scripts/no-ci-gate-prose.test.mjs +108 -0
  147. package/scripts/no-undo-audit.sh +1134 -0
  148. package/scripts/no-undo-audit.test.mjs +3965 -0
  149. package/scripts/no-wave.test.mjs +138 -0
  150. package/scripts/node-floor-sweep.test.mjs +611 -0
  151. package/scripts/pointer-target-prose.test.mjs +186 -0
  152. package/scripts/pr-overlap.mjs +417 -0
  153. package/scripts/pr-overlap.test.mjs +695 -0
  154. package/scripts/printf-die-sweep.test.mjs +384 -0
  155. package/scripts/prompt-renderer.mjs +39 -0
  156. package/scripts/prompt-renderer.test.mjs +68 -0
  157. package/scripts/prose-pin.mjs +808 -0
  158. package/scripts/prose-pin.test.mjs +1034 -0
  159. package/scripts/prove-merge.sh +228 -0
  160. package/scripts/prove-merge.test.mjs +995 -0
  161. package/scripts/pull-table-relabel-prose.test.mjs +60 -0
  162. package/scripts/quiet-payload-prose.test.mjs +222 -0
  163. package/scripts/reap.sh +1768 -0
  164. package/scripts/reap.test.mjs +4395 -0
  165. package/scripts/reaping-prose.test.mjs +159 -0
  166. package/scripts/refuter-scratch-prose.test.mjs +135 -0
  167. package/scripts/release-label-required-prose.test.mjs +71 -0
  168. package/scripts/release-label-split-prose.test.mjs +169 -0
  169. package/scripts/release-ticket.sh +1716 -0
  170. package/scripts/release-ticket.test.mjs +5106 -0
  171. package/scripts/renovate-release-contract.test.mjs +379 -0
  172. package/scripts/repo-root.mjs +544 -0
  173. package/scripts/repo-root.test.mjs +873 -0
  174. package/scripts/reporter-output-rule-prose.test.mjs +208 -0
  175. package/scripts/review-agent-report-only.test.mjs +49 -0
  176. package/scripts/review-core-cwd-isolation.test.mjs +374 -0
  177. package/scripts/review-core-reads.test.mjs +478 -0
  178. package/scripts/review-core-refuter-scratch.test.mjs +148 -0
  179. package/scripts/review-core-snapshot-path.test.mjs +777 -0
  180. package/scripts/review-core-specialist-scratch.test.mjs +189 -0
  181. package/scripts/review-core-testcmd.test.mjs +288 -0
  182. package/scripts/review-core-unrun.test.mjs +530 -0
  183. package/scripts/review-core-unverified-discriminant.test.mjs +208 -0
  184. package/scripts/review-core.mjs +1028 -0
  185. package/scripts/review-eval-resolver-path.test.mjs +55 -0
  186. package/scripts/review-eval.mjs +197 -0
  187. package/scripts/review-host-fixture.mjs +73 -0
  188. package/scripts/review-in-run-retry.test.mjs +187 -0
  189. package/scripts/review-no-vendor-dispatch.test.mjs +45 -0
  190. package/scripts/review-path-default.test.mjs +796 -0
  191. package/scripts/review-runner-spawns.test.mjs +93 -0
  192. package/scripts/review-runner.test.mjs +155 -0
  193. package/scripts/review-tier-audit.test.mjs +140 -0
  194. package/scripts/run-artifact-pr-prose.test.mjs +341 -0
  195. package/scripts/run-merge-bot-prose.test.mjs +1391 -0
  196. package/scripts/scratch-partition-invariant-prose.test.mjs +74 -0
  197. package/scripts/scripts-path-citation-sweep.test.mjs +73 -0
  198. package/scripts/section-between-guard-prose.test.mjs +378 -0
  199. package/scripts/select-dimensions.test.mjs +674 -0
  200. package/scripts/shared-refusal.test.mjs +388 -0
  201. package/scripts/shell-traps-prose.test.mjs +507 -0
  202. package/scripts/shortlist.mjs +355 -0
  203. package/scripts/shortlist.test.mjs +366 -0
  204. package/scripts/slow-transport.mjs +72 -0
  205. package/scripts/snapshot-repo.test.mjs +772 -0
  206. package/scripts/snapshot-runner-audience-prose.test.mjs +129 -0
  207. package/scripts/spend-view.test.mjs +312 -0
  208. package/scripts/staleness-qualifier-prose.test.mjs +251 -0
  209. package/scripts/staleness-verdict-prose.test.mjs +142 -0
  210. package/scripts/staleness.mjs +414 -0
  211. package/scripts/staleness.test.mjs +893 -0
  212. package/scripts/stalled-member-liveness-prose.test.mjs +219 -0
  213. package/scripts/stash-prohibition-prose.test.mjs +313 -0
  214. package/scripts/strip-comments.mjs +44 -0
  215. package/scripts/tier-check.mjs +468 -0
  216. package/scripts/tier-check.test.mjs +726 -0
  217. package/scripts/tier-guard-gate-prose.test.mjs +216 -0
  218. package/scripts/tier-outcomes-header.test.mjs +586 -0
  219. package/scripts/tier-outcomes.mjs +441 -0
  220. package/scripts/tier-outcomes.test.mjs +342 -0
  221. package/scripts/tier-roles.mjs +250 -0
  222. package/scripts/tier-roles.test.mjs +316 -0
  223. package/scripts/tracker-block-copy-prose.test.mjs +288 -0
  224. package/scripts/triage-labels-gloss-prose.test.mjs +97 -0
  225. package/scripts/unattended-git-sweep.test.mjs +142 -0
  226. package/scripts/verify-sha-exit2-prose.test.mjs +269 -0
  227. package/scripts/verify-sha.sh +117 -0
  228. package/scripts/verify-sha.test.mjs +693 -0
  229. package/scripts/watcher-degraded-block.test.mjs +372 -0
  230. package/scripts/watcher-key-prose.test.mjs +106 -0
  231. package/scripts/within-run-pair-prose.test.mjs +208 -0
  232. package/scripts/worktree-audit.sh +482 -0
  233. package/scripts/worktree-audit.test.mjs +1407 -0
  234. package/scripts/worktree-head-prose.test.mjs +276 -0
  235. package/scripts/worktree-listing-sweep.test.mjs +217 -0
  236. package/scripts/worktree-model-prose.test.mjs +216 -0
  237. package/scripts/worktree.sh +470 -0
  238. package/skills/next-ticket/SKILL.md +138 -0
  239. package/skills/run-team/SKILL.md +3603 -0
  240. package/skills/run-team/references/ci-and-staleness.md +75 -0
  241. package/skills/run-team/references/correction-tickets.md +37 -0
  242. package/skills/run-team/references/isolation.md +23 -0
  243. package/skills/run-team/references/member-lifecycle.md +73 -0
  244. package/skills/run-team/references/reaping.md +73 -0
  245. package/skills/sizing-a-ticket/SKILL.md +39 -0
@@ -0,0 +1,1768 @@
1
+ #!/bin/sh
2
+ # Delete local branches whose upstream is gone, and their worktrees.
3
+ #
4
+ # Dry-run by default; --apply mutates. Every precondition is recomputed inside
5
+ # this invocation, because a branch list from an earlier call is already false:
6
+ # one observed run listed 28 gone branches and two calls later 27 had been
7
+ # reaped by a concurrent session.
8
+ #
9
+ # Deliberately NOT `/clean_gone`: its `[gone]` detection actually works —
10
+ # with an upstream configured, `git branch -v` does print `[gone]` and its
11
+ # grep matches (verified, git 2.50.1). It is disqualified because it then
12
+ # runs `git worktree remove --force` and `git branch -D` with no merged
13
+ # check at all: nothing there stops it deleting a branch whose commits exist
14
+ # nowhere else.
15
+ set -eu
16
+
17
+ # Byte semantics for the `awk`, `grep`, `tr` and `paste` below — this script
18
+ # runs no `sed`, and the four it does run do not all see the same data. `awk`
19
+ # parses branch names out of `git branch -vv`, worktree paths out of
20
+ # `git worktree list --porcelain`, and the ignored-file names
21
+ # `git status --ignored` prints; `paste -sd, -` joins those ignored names. `tr`
22
+ # sees none of that: it processes `$cherry`, `git cherry`'s output, whose commit
23
+ # subjects git constrains to no encoding at all, which makes it arguably the
24
+ # likeliest carrier of the four. `grep` reads `$cherry` at the two
25
+ # merged-commit checks AND `$wt_list` at the two registry re-reads, so it is
26
+ # the one tool here that sees both a commit subject and a raw worktree path.
27
+ # The sentence this replaces said `grep` saw only `$cherry`, and had been false
28
+ # for as long as those registry reads have existed. Under a UTF-8 locale BSD
29
+ # `tr` exits 1 on a byte that is not valid UTF-8, `paste` truncates its whole
30
+ # output at it and still exits 0, and `grep` does one of TWO things: it drops
31
+ # the offending line at rc 0/1, or it gives up on the scan and exits 2. Only
32
+ # the first half was ever written down here, which is why the second read as a
33
+ # clean no-match at all four call sites until #1419 — the reason `grep_probe`
34
+ # below takes grep's own status apart from grep's verdict.
35
+ #
36
+ # `awk` is NOT immune, and reap.test.mjs's own #614 fixture measured the
37
+ # earlier claim here false: it is byte-identical only when every rule matches
38
+ # at an ANCHOR before the bad byte, never needing to convert it. A rule that
39
+ # must SCAN PAST the byte to decide — here, the `/^branch /` match against a
40
+ # worktree's raw, unquoted registry path, one SIBLING entry away from the
41
+ # branch actually under sweep — dies instead: measured, BWK awk (macOS) aborts
42
+ # at rc 2 (`towc: multibyte conversion failure`), and this script runs under
43
+ # `set -eu`, so that death TERMINATES the whole sweep rather than merely
44
+ # mis-scoring one record. gawk and mawk (Linux CI) tolerate the same byte and
45
+ # answer rc 0, which is why this is a macOS-only ceiling, not a portable fix —
46
+ # #790. Such a byte reaches us from a fetched tree even where the local
47
+ # filesystem refuses to hold the name. #582 measured the cost of leaving this
48
+ # ambient in no-undo-audit.sh: a truncated list reported as a clean, confident
49
+ # answer.
50
+ #
51
+ # Safe as a global: nothing in this script sorts, folds case, or uses a `[a-z]`
52
+ # range or a POSIX class, so collation and case-folding — the two things
53
+ # `LC_ALL=C` otherwise changes — have nothing here to act on. "Nothing" is an
54
+ # inventory, not a hope: locale-pin-prose.test.mjs enforces it (#612), because
55
+ # this sentence shipped false in no-undo-audit.sh and a `sort` added below
56
+ # would otherwise leave every test in this suite green.
57
+ export LC_ALL=C
58
+
59
+ # Below the locale pin, not above it with `set -eu`: `unset` touches no
60
+ # byte-sensitive tool, but locale-pin-prose.test.mjs treats ANY line here that
61
+ # is not a comment, a blank, or `set -[eux]+` as work the pin must sit above,
62
+ # and refuses on principle rather than on this line's own behaviour. Same
63
+ # placement, same reason, as release-ticket.sh's copy.
64
+ #
65
+ # This is the script the class costs the most, and both halves are measured on
66
+ # it (#1020).
67
+ #
68
+ # GIT_DIR: nothing in the sweeps carries a `-C`. An ambient one therefore does
69
+ # not merely misreport — it MOVES THE DELETIONS. Measured, `--apply` run from
70
+ # clone A with `GIT_DIR` naming clone B's `.git`: B's worktree was removed and
71
+ # B's branch deleted, at rc 0, with a receipt naming them, while A's own
72
+ # [gone] branch and its dirty worktree were never looked at. A destructive
73
+ # command aimed at a repository the operator did not name.
74
+ #
75
+ # GIT_WORK_TREE: it outranks `-C`, so the dirty probe `git -C "$wt" status
76
+ # --porcelain` stops answering about `$wt`. Measured, on the fleet's own
77
+ # layout (`.worktrees/` gitignored, so the parent really is clean): a worktree
78
+ # holding uncommitted work is reported reapable — `would remove worktree`,
79
+ # `would reap` — where the unpoisoned run keeps it with reason `dirty
80
+ # worktree`. `git worktree remove` without `--force` still refuses on the real
81
+ # dirt downstream, so this stops short of data loss; what it costs is the
82
+ # `kept` reason an operator acts on, and a dry run that promises a removal the
83
+ # apply cannot perform.
84
+ unset GIT_DIR GIT_WORK_TREE
85
+
86
+ NAME=reap
87
+ die() { printf '%s: %s\n' "$NAME" "$1" >&2; exit 2; }
88
+
89
+ # The escaping helpers (#119). json.sh's header holds the sourcing contract and
90
+ # the measurements behind it. This script defines no exit 1 at all (#265), so a
91
+ # bare 1 out of it is a code its caller has no reading for. Placed here, above
92
+ # the fetch, so a missing library refuses before anything is deleted rather than
93
+ # partway through.
94
+ json_lib="$(dirname "$0")/json.sh"
95
+ [ -r "$json_lib" ] || die "cannot read $json_lib — refusing to reap without the JSON escaping helpers"
96
+ # shellcheck source-path=SCRIPTDIR
97
+ # shellcheck source=json.sh
98
+ . "$json_lib" || die "$json_lib failed to load"
99
+
100
+ # The bounded, prompt-suppressed git transport (#92, #346, #347). The fetch
101
+ # below is unattended: with no bound it can prompt for a credential or a host
102
+ # key, or stall on a transport that connects and then goes quiet, and either
103
+ # holds a fleet slot until something outside kills it. net.sh's header holds the
104
+ # reasoning and the measurements. Sourced below json.sh so a lone copy of this
105
+ # script still blames json.sh, the name its missing-library test pins.
106
+ net_lib="$(dirname "$0")/net.sh"
107
+ [ -r "$net_lib" ] || die "cannot read $net_lib — refusing to reap without the bounded git transport"
108
+ # shellcheck source-path=SCRIPTDIR
109
+ # shellcheck source=net.sh
110
+ . "$net_lib" || die "$net_lib failed to load"
111
+
112
+ # The worktree readers (#551, #725). worktree.sh's header holds the sourcing
113
+ # contract and the measurements behind it, and json.sh's holds the `[ -r ]`
114
+ # reasoning all three guards share. Sourced below json.sh so a lone copy of this
115
+ # script still blames json.sh, the name its missing-library test pins, and above
116
+ # the fetch so a missing library refuses before anything is deleted.
117
+ wt_lib="$(dirname "$0")/worktree.sh"
118
+ [ -r "$wt_lib" ] || die "cannot read $wt_lib — refusing to reap without the worktree readers"
119
+ # shellcheck source-path=SCRIPTDIR
120
+ # shellcheck source=worktree.sh
121
+ . "$wt_lib" || die "$wt_lib failed to load"
122
+
123
+ # Count first, then value. The count guard used to be the only one, and the
124
+ # `--apply` test demoted anything else to "not --apply", so a single argument
125
+ # passed whatever it said. Measured on the pre-fix script over identical
126
+ # fixtures, `reap.sh --aply` and a bare `reap.sh` both exited 0 with
127
+ # byte-identical stdout and stderr — same payload, same banner, same per-branch
128
+ # lines — so nothing in the run said the flag had not been understood (#250).
129
+ # Both refusals sit above the fetch, so a rejected invocation reads nothing and
130
+ # deletes nothing.
131
+ apply=false
132
+ [ $# -gt 1 ] && die "usage: reap.sh [--apply]"
133
+ if [ $# -eq 1 ]; then
134
+ [ "$1" = "--apply" ] || die "unrecognised argument '$1' — usage: reap.sh [--apply]"
135
+ apply=true
136
+ fi
137
+
138
+ base=${BASE_REF:-origin/main}
139
+
140
+ # Only a remote-tracking ref is accepted — the accept-list release-ticket.sh:229
141
+ # carries, and the one this script had none of. Both sweeps below ask a single
142
+ # question, has this work landed upstream, and only a ref the `fetch --prune`
143
+ # above maintains can answer it. Without the list a `BASE_REF=refs/heads/…` was
144
+ # taken at face value in both directions: a local `main` never fast-forwarded
145
+ # reads every merged branch as unmerged (strand everything), and
146
+ # `refs/heads/<a branch this run is about to sweep>` reads that branch's own
147
+ # commits as already upstream — `git cherry` empty, the delete authorized,
148
+ # and nothing at the delete refuses it: the compare-and-swap there refuses
149
+ # only a ref that moved, and the holder check only a branch a worktree holds.
150
+ #
151
+ # It is also what makes the qualification below sound rather than a guess. #924
152
+ # recorded qualifying as unavailable here precisely because BASE_REF might name
153
+ # a tag, a sha or a local branch, leaving no prefix that is always correct;
154
+ # restricting the input first removes that objection instead of working around
155
+ # it. Placed with the argument guards above the fetch, so a rejected invocation
156
+ # reads nothing and deletes nothing.
157
+ case "$base" in
158
+ origin/*|refs/remotes/*) ;;
159
+ *) die "BASE_REF must be a remote-tracking ref, got '$base'";;
160
+ esac
161
+
162
+ # release-ticket.sh's SECOND guard — `*/"$branch") die` — is deliberately not
163
+ # ported, and the reason is structural rather than a judgement about severity.
164
+ # There the claim's own branch is a single known name, and `origin/$branch`
165
+ # passes the accept-list above while making every measurement vacuous, because
166
+ # a stale remote-tracking ref left by a pushed-then-deleted branch resolves
167
+ # with no branch on the remote to hold the commits. This sweep has no one
168
+ # branch to name, and the `fetch --prune` above is what closes the same route:
169
+ # it drops exactly those stale refs, so a `BASE_REF=origin/<branch>` that still
170
+ # resolves afterwards names a ref the remote still has — the commits it reads
171
+ # as upstream really are on the remote, and a branch that is ahead of it still
172
+ # prints `+`. Nothing is lost in either case, which is not true of the tag
173
+ # spelling handled next.
174
+
175
+ # And then stop MEASURING against a shorthand. `origin/main` is one, and git
176
+ # resolves a shorthand through its own disambiguation order (gitrevisions:
177
+ # refs/<name>, refs/tags/<name>, refs/heads/<name>, refs/remotes/<name>, …), in
178
+ # which refs/remotes/origin/main comes LAST — so a local tag literally named
179
+ # `origin/main` outranks the remote-tracking ref, and every measurement against
180
+ # $base then answers about the TAG. Measured on this script (git 2.50.1, Apple
181
+ # Git-155): an unmerged [gone] branch holding a commit that existed nowhere
182
+ # else, plus `git tag origin/main <that branch's own tip>`, printed
183
+ # `REAPED feature/solo` at exit 0 with an empty kept[] — the sole copy of the
184
+ # commit destroyed by a probe that was asked about the tag.
185
+ #
186
+ # Nothing already here could see it. The hijack is spelled as the legitimate
187
+ # DEFAULT, so no accept-list catches it; and `git rev-parse --verify "$base"`
188
+ # exits 0 whichever ref it picked — git's own
189
+ # `warning: refname 'origin/main' is ambiguous.` reaches stderr, where this
190
+ # script reads nothing and an unattended run has no one to read it. #924, the
191
+ # fix pattern proven in release-ticket.sh:264 (#760).
192
+ #
193
+ # refs/remotes/ leaves nothing to disambiguate, and the accept-list above
194
+ # already establishes $base is spelled for that namespace. $base itself is
195
+ # unchanged and stays in every operator-facing line: `origin/main does not
196
+ # resolve` is what a caller can act on, not the qualified spelling. A BASE_REF
197
+ # whose only resolution IS a tag now refuses at the guard below instead of
198
+ # measuring against it, which is the fail-closed half of the same edit.
199
+ case "$base" in
200
+ refs/remotes/*) base_rev=$base;;
201
+ *) base_rev="refs/remotes/$base";;
202
+ esac
203
+ git rev-parse --git-dir >/dev/null 2>&1 || die "not inside a git repository"
204
+
205
+ # The worktree this run is standing in, read once and before anything is
206
+ # deleted. `--apply` removes worktrees, and the fleet's own `.worktrees/` home
207
+ # is exactly where a member stands when it runs this — so the worktree the
208
+ # script is running FROM was itself eligible for removal, and removing it
209
+ # deletes this process's cwd. Everything after that dies with
210
+ # `fatal: Unable to read current working directory`: measured (git 2.50.1,
211
+ # Apple Git-155) as `REMOVED worktree …` followed by a failed
212
+ # `git worktree prune` at exit 2, from a run whose every removal SUCCEEDED, and
213
+ # measured again on the branch sweep as a `git branch -D` that failed for that
214
+ # same reason on a branch whose worktree had just been removed. The two sweeps
215
+ # below refuse this one path and report it as a `kept` finding, which is the
216
+ # remedy an operator can act on — it is one `cd` away. Chdir-ing somewhere
217
+ # durable at the foot of the file would cover the prune only, and the prune is
218
+ # the LAST call that needs a cwd, not the only one. #992
219
+ #
220
+ # `--show-toplevel`, never `pwd`: this script may be invoked from a
221
+ # subdirectory, and that answers the worktree ROOT — the directory
222
+ # `git worktree list --porcelain` names. It does not always SPELL it the same:
223
+ # the listing echoes the path recorded at `worktree add` time, which a parent
224
+ # turned symlink since leaves non-canonical, and which `core.precomposeunicode`
225
+ # prints precomposed for a worktree whose on-disk name is NFD while git's own
226
+ # answer is the NFD bytes (measured, git 2.50.1, Apple Git-155, #2072). So
227
+ # `holds_cwd` below matches on the directory, not only the string.
228
+ #
229
+ # `2>/dev/null` and never `2>&1`, for the reason the in-progress guard below
230
+ # records at its own `rev-parse`: this capture is used as a PATH, not as
231
+ # message text, and a `~/.gitconfig` with a key outside any section makes every
232
+ # git command print `error: key does not contain a section: …` AT EXIT 0 (#985)
233
+ # — folded in, that line would arrive glued in front of the path and match no
234
+ # worktree ever again.
235
+ #
236
+ # Empty is a legitimate answer, not a failure worth dying on: `--show-toplevel`
237
+ # exits 128 with one of two known messages where cwd is in no working tree (a
238
+ # bare repo root, or inside `.git`) — "not a git repository" or "this
239
+ # operation must be run in a work tree" (measured, git 2.50.1, Apple
240
+ # Git-155) — and neither is a path either sweep can remove: the branch sweep
241
+ # binds `$wt` only from a `branch` line a bare root never prints, and the
242
+ # enumeration below skips a bare entry outright.
243
+ #
244
+ # Any OTHER failure of this probe is NOT that answer and must not be folded
245
+ # into it. Doing so silently disables both cwd-delete guards below (#1441) —
246
+ # every removal proceeds as though this run were standing in no worktree at
247
+ # all, reproducing #992's own defect signature. Fail closed instead: die,
248
+ # naming the probe that broke, so an operator chasing a downstream failure (a
249
+ # prune refusal, a branch delete dying on
250
+ # "Unable to read current working directory") lands on the real cause here
251
+ # rather than the symptom.
252
+ #
253
+ # The success path keeps `2>/dev/null`, never `2>&1`: folding stderr in would
254
+ # glue the #985 stray-gitconfig warning onto the path on a plain SUCCESS too.
255
+ # Stderr is only re-captured, on a second call, once the first has already
256
+ # failed — the classification never touches the value the guards compare
257
+ # against. `self_wt_rc=…` (not `|| self_wt=`) keeps the check off `set -e`.
258
+ self_wt_rc=0
259
+ self_wt=$(git rev-parse --show-toplevel 2>/dev/null) || self_wt_rc=$?
260
+ if [ "$self_wt_rc" -ne 0 ]; then
261
+ self_wt_err=$(git rev-parse --show-toplevel 2>&1 >/dev/null) || true
262
+ case "$self_wt_err" in
263
+ *"not a git repository"* | *"this operation must be run in a work tree"*)
264
+ self_wt=
265
+ ;;
266
+ *)
267
+ die "cannot tell whether this run is standing in a worktree slated for removal — 'git rev-parse --show-toplevel' failed with an unrecognised error (${self_wt_err:-exit $self_wt_rc}) instead of one of the two known 'not in a worktree' messages; refusing to reap with the cwd-delete guard unverified"
268
+ ;;
269
+ esac
270
+ fi
271
+
272
+ # True when removing worktree `$1` would delete this run's cwd: `$self_wt` is
273
+ # `$1` or lies anywhere beneath it (#1441's nested worktree). Asked of the
274
+ # DIRECTORY, not the string: `-ef` (same device and inode) of `$self_wt` and of
275
+ # each of its parents in turn. The byte-boundary prefix match this replaces
276
+ # missed the same directory spelled two ways — the symlinked parent and the NFD
277
+ # name the header above records share no prefix with git's own answer — and
278
+ # `--apply` deleted the cwd it was standing in, #992's signature (measured,
279
+ # #2072). An empty `$self_wt` (no worktree) names no directory, so it matches
280
+ # nothing; the walk ends when no `/` is left to strip.
281
+ #
282
+ # `elif` on `$?`, same refusing direction `wt_linkage_why` states for its own
283
+ # `-ef`: every shell this file targets (dash, bash, ksh — all three tested)
284
+ # implements it, so a `[` that cannot evaluate it (rc 2) is
285
+ # unreached today, not impossible — and unlike `wt_linkage_why`, nothing
286
+ # downstream of THIS guard re-checks the directory it protects. Reading that
287
+ # rc as a plain "not this one" would silently disable both cwd-delete guards
288
+ # exactly the way an unrecognised `self_wt` failure would (#1441's note
289
+ # above), just one layer further in.
290
+ holds_cwd() {
291
+ hc_d=$self_wt
292
+ while :; do
293
+ # shellcheck disable=SC3013,SC2319 # -ef is a ksh-derived extension bash/dash/BSD sh share, base in POSIX.1-2024; the else's $? is deliberately the `[ -ef ]` test's own rc, read before anything else runs, to fail closed (return 0) on rc>=2 same as wt_linkage_why below
294
+ if [ "$hc_d" -ef "$1" ]; then hc_rc=0; else hc_rc=$?; fi
295
+ if [ "$hc_rc" -eq 0 ] || [ "$hc_rc" -ge 2 ]; then return 0; fi
296
+ case "$hc_d" in
297
+ */*) hc_d=${hc_d%/*} ;;
298
+ *) return 1 ;;
299
+ esac
300
+ done
301
+ }
302
+
303
+ echo "\$ git fetch --prune origin" >&2
304
+ fetch_budget=$(net_fetch_budget)
305
+ fetch_rc=0
306
+ net_git "" "$fetch_budget" fetch --prune --quiet origin || fetch_rc=$?
307
+ if [ "$fetch_rc" -ne 0 ]; then
308
+ # A killed fetch and a refused one are different facts and get different
309
+ # words. Without the split, a transport that stalled reads as a refusal,
310
+ # naming a cause this script never observed.
311
+ if net_stalled "$fetch_rc"; then
312
+ die "git fetch did not finish within ${fetch_budget}s and was killed — refusing to reap on stale refs"
313
+ fi
314
+ die "fetch failed — refusing to reap on stale refs"
315
+ fi
316
+ # `$base_rev`, never `$base`: the qualified spelling is the one every
317
+ # measurement below uses, so it is the one whose existence has to be
318
+ # established — and asking about it is also what turns a BASE_REF that only
319
+ # resolves as a TAG into a refusal here rather than a merge probe answered by
320
+ # the wrong commit (#924). The message names `$base`, the spelling the caller
321
+ # passed and the only one it can act on.
322
+ git rev-parse --verify "$base_rev" >/dev/null || die "$base does not resolve"
323
+ [ "$apply" = true ] || echo "$NAME: DRY RUN — nothing will be deleted. Pass --apply to act." >&2
324
+
325
+ reaped=""
326
+ kept=""
327
+ warnings=""
328
+ # Every worktree this run removed, by path, whether a branch accounted for it or
329
+ # not. One meaning, so the key needs no qualifier: the sweep below reaps
330
+ # worktrees no `reaped` branch names, and a payload that recorded only those
331
+ # would leave a reader guessing whether the branch sweep's removals were absent
332
+ # because none happened or because nothing reports them (#381).
333
+ removed=""
334
+ # `jstr`'s output wrapped in the quotes JSON needs, or the literal `null` where
335
+ # it could not render. `die` is the wrong answer at both call sites below: by
336
+ # the time either accumulator is written this script may already have deleted
337
+ # branches, and the payload printed at the end is the caller's only record of
338
+ # that — the same reason #265 moved the printf ahead of the prune. Exiting here
339
+ # would destroy the record of work that already happened. So an unrenderable
340
+ # field becomes `null` and the run still reports what it did, the ruling
341
+ # inflight.sh's `add_evidence` records for the same shape.
342
+ #
343
+ # jfield always exits 0, which is what makes it safe inside the `$( )` below:
344
+ # a substitution that failed would contribute an empty string and splice
345
+ # `{"branch":,…}` — malformed JSON — with nothing to notice it.
346
+ #
347
+ # Five interpolations converge on this function: the branch name, `dirty
348
+ # worktree $wt`, `ignored files present in $wt: $ignored`, `cherry probe
349
+ # failed …: $cherry` (arbitrary git stderr) — the first four via `keep`, at
350
+ # eleven call sites — and the `reaped` accumulator, which calls `jfield`
351
+ # directly and never routes through `keep` at all. The branch name is the
352
+ # demonstrated trigger — `git branch 'has"quote'` is a legal refname — and raw
353
+ # it emitted a payload no parser accepts at exit 0, while the branch was
354
+ # correctly kept (#119). The stderr lines stay raw: they are prose for an
355
+ # operator, not JSON.
356
+ #
357
+ # A sixth joined the five above at #1419: grep's own stderr, `$gq_err`,
358
+ # surfaced through `gp_why "$gq_err"` in `keep`'s message at the two cherry
359
+ # checks and the two registry re-reads (reap.sh:635, 991, 1195, 1307) —
360
+ # arbitrary text on the same footing as `$cherry`, routed through the same
361
+ # jfield/jstr escaping the paragraph above already covers. Left out of the
362
+ # "eleven call sites" figure above, which still counts only the original
363
+ # five; four more now carry grep's stderr specifically.
364
+ jfield() {
365
+ if jf=$(jstr "$1"); then
366
+ printf '"%s"' "$jf"
367
+ else
368
+ echo "$NAME: could not escape a payload field — reported as null" >&2
369
+ printf null
370
+ fi
371
+ }
372
+
373
+ # An empty `$1` is the worktree sweep at the foot of this script, which has no
374
+ # branch to name: the field becomes JSON `null` rather than `""`, the value
375
+ # `jfield` already emits for a field it could not render, so no consumer meets a
376
+ # type here it did not already have to handle. Every reason that sweep produces
377
+ # ABOUT a worktree names its path, which is why the stderr label can fall back
378
+ # to a placeholder without losing which worktree was kept — the two it produces
379
+ # before the enumeration succeeds ("cannot enumerate worktrees", "could not read
380
+ # the worktrees git listed") name none because none was established.
381
+ keep() {
382
+ if [ -n "$1" ]; then kb=$(jfield "$1"); else kb=null; fi
383
+ kept="${kept}{\"branch\":$kb,\"reason\":$(jfield "$2")},"
384
+ printf ' KEEP %s — %s\n' "${1:-(no branch)}" "$2" >&2
385
+ }
386
+
387
+ # Runs `git "$@"`, and unlike a bare `$(git … 2>/dev/null)` this keeps git's
388
+ # stderr instead of discarding it — into $gp_err, never mixed into $gp_out,
389
+ # with git's own exit status returned by this function. #625: this file's
390
+ # worktree status probes used to throw stderr away, so a `fatal:` at rc 128 named
391
+ # no cause and a `warning:` at rc 0 (measured, PR #726 review — a
392
+ # permission-denied ignored directory) reached nobody. The wrong fix is
393
+ # `2>&1`: each of these probes is followed by a `[ -n "$gp_out" ]` dirty test,
394
+ # which reads the captured text as content, so folding a warning in would make a
395
+ # clean worktree with ANY git warning on it read as dirty forever.
396
+ #
397
+ # No temp file (this file creates none): git's stderr goes to fd3, which the
398
+ # group below dupes from fd1 before git runs, so it lands live in the SAME
399
+ # pipe `gp_raw=$( … )` reads — no separate pipe or file needed for it. Command
400
+ # substitution runs in its own subshell (POSIX), so a plain variable set
401
+ # inside — git's stdout, git's own $? — cannot escape it; only the TEXT
402
+ # written there survives. `gp_sep` marks where one piece ends and the next
403
+ # begins, so `gp_raw` can be split apart with plain parameter expansion once
404
+ # it is back in the real, top-level shell.
405
+ #
406
+ # THE SEPARATOR IS SAFE BECAUSE OF WHAT GIT DOES, NOT BECAUSE OF WHAT 0x02
407
+ # IS, and it is safe only for the commands this helper is currently pointed
408
+ # at, by two DIFFERENT rules for two DIFFERENT groups. Three call sites below
409
+ # read `status --porcelain` (`-uall`, or `-unormal --ignored`) and are safe
410
+ # because git quotes PATHS; a fourth, added after this comment was first
411
+ # written (#1413), reads `for-each-ref --format='%(refname)
412
+ # %(upstream:track)'` and is safe for an unrelated reason — a REFNAME,
413
+ # unlike a path, can never contain the byte at all. Nothing in the body
414
+ # checks either invariant.
415
+ #
416
+ # The path-reading three: both halves of git's answer put a control byte in
417
+ # a path beyond reach of the split, by two DIFFERENT rules — measured on git
418
+ # 2.50.1 (Apple Git-155), against a file named `weird<0x02>file` and a
419
+ # chmod-000 directory `dir<0x02>name`:
420
+ #
421
+ # $gp_out: git C-quotes the path — `?? "weird\002file"`, a literal
422
+ # backslash-002 inside quotes, never the raw byte. This does NOT hang on
423
+ # `core.quotePath`, which only demotes bytes >= 0x80 out of "unusual";
424
+ # "git quotes unusual bytes" is therefore the wrong claim to rest on,
425
+ # since #614 measured that exact escape hatch for the HIGH-BIT class (see
426
+ # derive-testcmd.sh). Zero raw 0x02 out of `--porcelain -uall` and out of
427
+ # `--porcelain --ignored`, under core.quotePath true AND false.
428
+ #
429
+ # $gp_err: git writes an unprintable byte in a path as `?` in its own
430
+ # diagnostics — `warning: could not open directory 'dir?name/'`. Zero raw
431
+ # 0x02 there either.
432
+ #
433
+ # The ref-reading fourth: no PATH-quoting rule is doing the work, because no
434
+ # quoting is needed — git refuses to CREATE the ref at all. Measured, git
435
+ # 2.50.1 (Apple Git-155): `git branch "$(printf 'a\002b')"` fails outright —
436
+ # `fatal: 'a?b' is not a valid branch name` — and so does `git update-ref
437
+ # refs/heads/"$(printf 'a\002b')" HEAD` — `refusing to update ref with bad
438
+ # name`. `%(refname)` and `%(upstream:track)` can only ever answer with
439
+ # bytes that already survived `check-ref-format` on the way in, so a raw
440
+ # 0x02 can never reach either field to begin with. A fifth call site, added
441
+ # by #2219, joins this ref group: `rev-parse --verify refs/heads/<b>`, where
442
+ # `<b>` is a name the `for-each-ref` call site produced. Its stdout is an
443
+ # object id in hex, and what it can put on stderr is git's own fixed prose
444
+ # around that same validated refname.
445
+ #
446
+ # SO DO NOT POINT `git_probe` AT A COMMAND WHOSE OUTPUT CARRIES NEITHER
447
+ # GUARANTEE. It takes `git "$@"`, so the invariant is the CALLER's to keep
448
+ # and nothing here catches a caller who drops it: a raw separator truncates
449
+ # $gp_out at that byte and concatenates the rest of the real output onto
450
+ # $gp_rc, which then reaches `return` as a non-numeric string (measured
451
+ # against a stub git, PR #1209 review). It is one flag away from the path
452
+ # group, not hypothetical — same git, same fixture: `status --porcelain
453
+ # -uall -z` carries the raw 0x02 straight through, `-z` being the
454
+ # machine-readable form that drops the quoting, and so does any command
455
+ # emitting CONTENT rather than paths or refnames (`log --format=%s`, `show
456
+ # <rev>:<path>`, both measured). The ref group has no equivalent flag —
457
+ # `for-each-ref` cannot be asked to emit an unvalidated refname — so this
458
+ # warning is really aimed at the path group and at any THIRD kind of call
459
+ # site a future caller might add.
460
+ #
461
+ # Left unguarded anyway, deliberately (#1212): every call site is shaped
462
+ # `if ! git_probe …; then keep …`, so a garbled $gp_rc can never come back 0
463
+ # and so can never turn a KEEP into a REAP. For a script whose only costly
464
+ # failure is deleting something it should have kept, that is the direction
465
+ # that matters, and it already fails closed. A numeric guard on $gp_rc was
466
+ # the competing remedy and was rejected: it buys loudness this failure mode
467
+ # does not need.
468
+ #
469
+ # `if gp_o=$(...); then gp_rc=0; else gp_rc=$?; fi`, never a bare
470
+ # `gp_o=$(...); gp_rc=$?`: under `set -e` a bare failing assignment aborts the
471
+ # subshell before `gp_rc=$?` or the printf below ever run, and `gp_raw` comes
472
+ # back empty — silently, at the one moment this function exists to not be
473
+ # silent (measured on this exact shape, PR #1068 review).
474
+ gp_sep=$(printf '\002')
475
+ git_probe() {
476
+ gp_raw=$(
477
+ {
478
+ if gp_o=$(git "$@" 2>&3); then gp_rc=0; else gp_rc=$?; fi
479
+ printf '%s' "$gp_sep$gp_o$gp_sep$gp_rc"
480
+ } 3>&1
481
+ )
482
+ gp_err=${gp_raw%%"$gp_sep"*}
483
+ gp_raw=${gp_raw#*"$gp_sep"}
484
+ gp_out=${gp_raw%%"$gp_sep"*}
485
+ gp_rc=${gp_raw#*"$gp_sep"}
486
+ return "$gp_rc"
487
+ }
488
+
489
+ # True when git's stderr says the directory walk was CUT SHORT — entries are
490
+ # missing from $gp_out — as opposed to git merely having said something.
491
+ # "Anything on stderr" is the wrong test in both directions, measured here on
492
+ # git 2.50.1 (Apple Git-155):
493
+ #
494
+ # too broad — a global gitconfig with a key outside any section makes EVERY
495
+ # git command print `error: key does not contain a section: …` at rc 0 (the
496
+ # same fault the rev-parse probe near the end of this file is redirected
497
+ # for), and an unreadable core.attributesFile prints `warning: unable to
498
+ # access '…': Permission denied`. Both leave the listing COMPLETE, so a
499
+ # non-empty-stderr gate strands every worktree it guards for as long as the
500
+ # operator's config stays broken, blaming the worktree for the fault.
501
+ #
502
+ # too narrow — gating only the `--ignored` probe misses the plain scan: an
503
+ # unreadable UNTRACKED directory makes `git status --porcelain` warn at rc 0
504
+ # and answer EMPTY, which the dirty check below then reads as clean.
505
+ #
506
+ # `warning: could not open directory '<path>': <err>` is the message git emits
507
+ # for exactly that, and only that: measured at rc 0 with entries missing on an
508
+ # unreadable untracked directory, an unreadable ignored directory, and an
509
+ # unreadable directory holding a tracked file. So both probe kinds gate on it,
510
+ # and neither gates on anything else.
511
+ gp_cut_short() {
512
+ case "$gp_err" in
513
+ *"could not open directory"*) return 0 ;;
514
+ esac
515
+ return 1
516
+ }
517
+
518
+ # `: <what the probe said>`, or nothing at all when it said nothing. Two
519
+ # reasons not to interpolate $gp_err directly. It keeps its trailing newline —
520
+ # it is read straight out of the pipe, unlike $gp_out, which command
521
+ # substitution strips — so a bare `tr '\n' ' '` leaves a trailing space inside
522
+ # the JSON reason. And a git that dies without writing to stderr (measured: a
523
+ # signal-killed git exits 137 with stderr empty) would otherwise leave a
524
+ # dangling `": "` naming no cause, on the one path this whole change exists to
525
+ # make name one.
526
+ #
527
+ # `$gp_err` is the default, not the only input: `grep_probe` below captures its
528
+ # own scanner's stderr into `$gq_err`, and both need these same two guards.
529
+ # Taken as an argument rather than by duplicating the stripper, so a fix to
530
+ # either guard cannot land in one copy and miss the other. Every git-side call
531
+ # site passes nothing and still reads `$gp_err`. #1419
532
+ gp_why() {
533
+ gp_w=$(printf '%s' "${1-$gp_err}" | tr '\n' ' ')
534
+ while :; do
535
+ case "$gp_w" in
536
+ *' ') gp_w=${gp_w% } ;;
537
+ *) break ;;
538
+ esac
539
+ done
540
+ if [ -n "$gp_w" ]; then printf ': %s' "$gp_w"; fi
541
+ }
542
+
543
+ # True when `$1`'s `.git` answers for `$1` itself; otherwise false, with the
544
+ # reason in `$lk_why`. Both sweeps call it once their `-f "$wt/.git"` test has
545
+ # established the linkage EXISTS, and before any git command run through `$wt`
546
+ # is believed — the dirty check first among them.
547
+ #
548
+ # Existing is not answering. Two shapes keep `.git` a well-formed regular file
549
+ # and move git's WORKING TREE elsewhere: a `.git` naming a foreign git dir not
550
+ # called `.git` whose `core.worktree` is another directory, and `core.worktree`
551
+ # set in the worktree's own `config.worktree` under `extensions.worktreeConfig`,
552
+ # `.git` untouched. `git -C "$wt" status` then reads THAT tree, so a clean one
553
+ # there reads clean over the work sitting in `$wt` — the dry run promised a
554
+ # removal `--apply` could not perform, `git worktree remove`'s own back-pointer
555
+ # and untracked-file checks being all that kept the work (measured on both
556
+ # shapes, both sweeps, git 2.50.1, #2042). `--show-toplevel` names the tree git
557
+ # actually answers for, so it is compared against `$1`.
558
+ #
559
+ # Compared as a DIRECTORY (`-ef`, same device and inode), never as a string:
560
+ # `$1` is the path `worktree list --porcelain` echoes and `--show-toplevel` is
561
+ # git's own resolved spelling, and the two legitimately differ for one and the
562
+ # same directory. A parent that was a plain directory at `worktree add` time
563
+ # and is a symlink now leaves the listed path non-canonical while git's answer
564
+ # is resolved (measured, #2042). And a worktree whose name is Unicode
565
+ # NFD-composed (`cafe` + U+0301) is listed PRECOMPOSED by the
566
+ # `core.precomposeunicode` git writes into every new repo on macOS, while
567
+ # `--show-toplevel` answers the on-disk NFD bytes — visually identical,
568
+ # byte-different, one directory (measured, git 2.50.1, Apple Git-155, #2072).
569
+ # `cd && pwd -P` canonicalises only the first: it echoes the spelling it was
570
+ # given, so a byte compare against it kept every healthy NFD worktree forever.
571
+ # `-ef` answers "same directory" for both and for any other spelling the
572
+ # filesystem aliases, and still refuses every redirect — each names a
573
+ # different directory. POSIX.1-2017's own `test` page does not define `-ef`
574
+ # at all, XSI or otherwise — it is a ksh-derived extension bash, dash, and
575
+ # BSD sh already share; POSIX.1-2024 (Austin Group bug 375) is what actually
576
+ # adds it, as a base utility primary. A `[` that cannot evaluate it fails,
577
+ # which is the refusing direction, as is a `--show-toplevel` naming a path
578
+ # that does not exist.
579
+ #
580
+ # `&& echo x` inside the substitution, then `%?x`: `$(...)` strips EVERY
581
+ # trailing newline, so a `core.worktree` naming a sibling directory called
582
+ # `<wt>` plus a newline byte — git accepts one as an ordinary path character —
583
+ # would otherwise name `$1` itself and pass the redirect (measured; the shape
584
+ # no-undo-audit.sh closed the same way, #2040). The sentinel leaves `$(...)`
585
+ # only git's own terminating newline to strip.
586
+ #
587
+ # What this does NOT cover, the boundary release-ticket.sh's copy of this
588
+ # compare also states (#421): shapes that swap which git DIR answers while the
589
+ # working tree stays `$1` — a `.git` naming a sibling worktree's admin dir
590
+ # (#189), or a foreign git dir whose `core.worktree` points back at `$1`.
591
+ # `--show-toplevel` answers `$1` for both. The dirty check reads `$1`'s real
592
+ # files against the borrowed index, and `git worktree remove` refuses a
593
+ # `.git` that does not point back at its admin dir, so neither is removed.
594
+ #
595
+ # A git that cannot answer at all is a refusal, never a pass: the reason is
596
+ # fetched with a second call only on that path, the way the cwd guard at the
597
+ # top of this file fetches its own, so the answer the compare reads never
598
+ # carries stderr.
599
+ wt_linkage_why() {
600
+ if ! lk_top=$(git -C "$1" rev-parse --show-toplevel 2>/dev/null && echo x); then
601
+ lk_why="has a .git linkage git cannot resolve$(gp_why "$(git -C "$1" rev-parse --show-toplevel 2>&1 >/dev/null)")"
602
+ return 1
603
+ fi
604
+ lk_top=${lk_top%?x}
605
+ # `if`, never `[ ! … ] || return 0`: a `[` that errors (rc 2) must refuse.
606
+ # shellcheck disable=SC3013 # -ef is a ksh-derived extension bash/dash/BSD sh share, base in POSIX.1-2024; this file targets dash too and -ef is verified there
607
+ if [ "$lk_top" -ef "$1" ]; then return 0; fi
608
+ lk_why="has a .git linkage that answers for $lk_top, not for it — its dirty check would read that tree"
609
+ return 1
610
+ }
611
+
612
+ # Runs `grep -q` over CAPTURED text and hands back grep's own status separately
613
+ # from the verdict grep was asked for.
614
+ #
615
+ # `grep -q` has THREE outcomes and a bare `if … | grep -q …; then` has room for
616
+ # two: rc 0 a line matched, rc 1 no line matched, rc 2+ grep could not finish
617
+ # scanning. Under `-q` both POSIX and GNU reserve 0 for a match even when an
618
+ # error also occurred, so an rc 2 means specifically "no match AND the scan
619
+ # broke". Tested two ways, that 2 lands in the NO-MATCH arm — a scanner that
620
+ # could not look reads exactly like a measurement that looked and found
621
+ # nothing. At the two merged-commit checks below, the no-match arm is what
622
+ # authorizes the branch delete and `git worktree remove`, so this swallow spends
623
+ # commits rather than merely miswording a reason: #1419 is the same
624
+ # misattribution as #789 and #1413 one tool further down the pipeline, a
625
+ # tool's own failure reported as a clean verdict about the thing it was
626
+ # scanning.
627
+ #
628
+ # The shape, so no call site reaches the third outcome by accident: this
629
+ # returns 0 whenever grep delivered a verdict at all — `$gq_rc` then holds 0
630
+ # for matched and 1 for not — and non-zero when it did not. A call site reads
631
+ # `if ! grep_probe …` for "could not look" and `[ "$gq_rc" -eq 0 ]` for
632
+ # "matched", so the two questions stay as separate in the source as they are in
633
+ # grep. What it deliberately does NOT do is decide which way an unanswerable
634
+ # scan should fall: each call site rules on that for itself, because the cost
635
+ # differs — the cherry checks must keep, the registry re-reads have nothing
636
+ # left to protect and only a reason to get right.
637
+ #
638
+ # Unlike `git_probe` above, this needs no fd3 dup and no `$gp_sep` splice:
639
+ # `git_probe` smuggles TWO values (git's stdout `$gp_o` and its rc `$gp_rc`)
640
+ # out through one command substitution's single text channel, so it has to
641
+ # encode both into that text and split them back apart. `grep -q` never has a
642
+ # stdout worth keeping — `-q` promises silence there, enforced below by
643
+ # `>/dev/null` — so this function only ever has ONE value to carry out of the
644
+ # subshell as text, grep's stderr, and the command substitution's own return
645
+ # value already IS that text: `gq_err=$(...)` needs no separator to unpack.
646
+ #
647
+ # grep's own rc rides out a second, cheaper channel that `git_probe` cannot
648
+ # use: making the `grep -q` pipeline the LAST command run inside the command
649
+ # substitution means the substitution's own exit status — what `$?` reads
650
+ # immediately after the assignment — already IS grep's rc, with nothing
651
+ # encoded and nothing to decode. `git_probe` cannot do this because it still
652
+ # needs `$gp_o` out as text too, and a command substitution's exit status and
653
+ # its captured text both come from the SAME last command, so the moment
654
+ # something runs after grep to print a value, that later command's own exit
655
+ # status overwrites grep's. Grep's stderr is kept for #625's reason at
656
+ # `git_probe` above — a probe that dies naming no cause reaches an operator as
657
+ # a bare refusal — but keeping it costs nothing here: it IS the command
658
+ # substitution's text, not a second thing smuggled alongside the rc.
659
+ #
660
+ # `if gq_err=$(...); then gq_rc=0; else gq_rc=$?; fi`, never a bare
661
+ # `gq_err=$(...); gq_rc=$?`: under `set -e` a bare failing assignment would
662
+ # abort the function before `gq_rc=$?` ever ran, the same measured reason
663
+ # `git_probe` above takes the same shape (PR #1068 review). A command
664
+ # substitution used as an `if`'s condition is exempt from `set -e` by POSIX
665
+ # definition, so `gq_rc=$?` always runs whether grep matched, didn't match, or
666
+ # broke.
667
+ #
668
+ # `2>&1 >/dev/null` inside the substitution, in that exact order: `2>&1`
669
+ # first points fd 2 at fd 1's CURRENT target, which at that moment is the
670
+ # pipe the command substitution reads back into `$gq_err` — only THEN does
671
+ # `>/dev/null` retarget fd 1 alone, leaving fd 2 still pointed at the capture
672
+ # pipe. Reversed, `>/dev/null 2>&1` would duplicate an fd 2 that already
673
+ # points at `/dev/null`, and grep's stderr would vanish along with its
674
+ # promised-silent stdout, leaving `gp_why "$gq_err"` nothing to report.
675
+ #
676
+ # `-e "$gq_pat"`, never a bare `$gq_pat`: `grep --` is not portable, and a
677
+ # pattern read as a flag is the shape that makes a guard match nothing and
678
+ # report it as a clean no-match — this function's own defect, one layer down.
679
+ #
680
+ # Extra flags come AFTER the pattern (`grep_probe "$hay" "$pat" -xF`) so the
681
+ # pattern keeps a fixed, non-optional slot no flag list can shift it out of:
682
+ # #730 measured what a positional argument does when a flag is inserted ahead
683
+ # of it.
684
+ grep_probe() {
685
+ gq_hay=$1
686
+ gq_pat=$2
687
+ shift 2
688
+ if gq_err=$(printf '%s\n' "$gq_hay" | grep -q "$@" -e "$gq_pat" 2>&1 >/dev/null); then
689
+ gq_rc=0
690
+ else
691
+ gq_rc=$?
692
+ fi
693
+ [ "$gq_rc" -le 1 ]
694
+ }
695
+
696
+ # Sets `$state` to name what a re-read of the worktree registry found after a
697
+ # `git worktree remove` refusal — shared by the branch sweep and the
698
+ # branchless/detached-worktree sweep below, which otherwise carried this
699
+ # four-way chain, `$wt_list`/`$gq_rc`/`$gq_err` and all, as two byte-identical
700
+ # copies. One copy so a fix to the chain cannot land in one sweep and miss
701
+ # the other, same reasoning as `gp_why` taking its guards as an argument
702
+ # above. The two call sites still earn their own `#1419` test fixtures: both
703
+ # pin that both sweeps actually CALL this, which one shared body cannot do by
704
+ # itself.
705
+ wt_reg_state() {
706
+ if ! wt_listing; then
707
+ state="cannot tell whether the registration survived"
708
+ elif ! grep_probe "$wt_list" "worktree $1" -xF; then
709
+ state="cannot tell whether the registration survived — the registry scan itself failed$(gp_why "$gq_err")"
710
+ elif [ "$gq_rc" -eq 0 ]; then
711
+ state="registration intact"
712
+ else
713
+ state="registration cleared"
714
+ fi
715
+ }
716
+
717
+ # The registry cross-check (#2078). The branch lookup below matches a
718
+ # `branch refs/heads/<b>` line, and an empty match lets the branch through to
719
+ # the delete. Measured, git 2.50.1 (Apple Git-155): eight real admin-directory
720
+ # faults leave `git worktree list --porcelain -z` at rc 0 — so the #622 guard
721
+ # below never fires — while the held entry either loses its `branch` line or
722
+ # leaves the listing entirely: `HEAD` garbage, empty, missing or chmod 000;
723
+ # `gitdir` missing or chmod 000; the admin directory chmod 000; `.git/worktrees`
724
+ # replaced by a file. `$wt` came back empty and `git branch -D` — the delete
725
+ # then — deleted a branch a live worktree holds in all eight, its own "used by
726
+ # worktree" refusal fooled by the same admin state. The delete is now
727
+ # `git update-ref -d`, which consults no worktree at all, and the holder check
728
+ # ahead of it (`wt_holding`) reads that same listing: measured against the
729
+ # same eight, it answers "not held" for seven and "cannot tell" only for
730
+ # `HEAD` missing, the one fault that leaves a `detached` line behind. No
731
+ # backstop exists past this point, so the listing has to be checked against
732
+ # the registry before its silence is read as "no worktree".
733
+ #
734
+ # `wt_registry_why` sets `reg_why` and returns 1 when the listing cannot be
735
+ # trusted. Two checks, because the fault families differ in what they leave:
736
+ #
737
+ # (a) COUNT. The `gitdir`/admin-dir/registry-file faults DROP the entry, so
738
+ # fewer linked worktrees are listed than are registered under
739
+ # `<git-common-dir>/worktrees/`. `count_registry` and `count_linked` mirror
740
+ # inflight.sh's pair of the same names (inflight.sh `count_registry`,
741
+ # `count_linked`, the recount at `[ "$linked" -eq "$registered" ] || {
742
+ # count_registry && count_linked; }` and the two direction-named refusals
743
+ # after it) — the stray-`mkdir` skip, the count-what-`ls`-cannot-read rule
744
+ # (#697), the `[ -r ] && [ -x ]` unreadable-registry arm and the `-ge 1`
745
+ # floor (#699) all carry that copy's measurements. One tightening: `-d` joins
746
+ # the unreadable arm, because a registry replaced by a mode-755 FILE passes
747
+ # `-r` and `-x`, globs to nothing, counts 0 against git's 0, and agrees.
748
+ #
749
+ # (b) NULL HEAD. The `HEAD` faults keep the entry, so the counts AGREE and
750
+ # (a) sees nothing: git lists it with the null object id and no `branch`
751
+ # line. A LINKED entry in that state is a worktree that held something git
752
+ # can no longer name. An unborn branch carries a null id too, but WITH its
753
+ # `branch` line, so it is not this; the main checkout (first record, and
754
+ # the only one that can be `bare`) is excluded, and a missing `HEAD` line
755
+ # reads as null, the same rule the branchless sweep's null-object-id arm
756
+ # applies. That arm stays as it is: it reports the worktree, while this one
757
+ # protects the branches. No `/^bare$/` rule here, deliberately: the #993
758
+ # fixture selects that sweep's awk by it, and a second carrier would shim
759
+ # this one too.
760
+ #
761
+ # Either finding keeps the branch under lookup, whichever it is: a dropped or
762
+ # nameless entry says nothing about WHICH branch it held, so a healthy branch
763
+ # with no worktree is exactly as unclearable as the tampered one. The check
764
+ # runs on the listing each branch's own lookup reads — re-read per branch, as
765
+ # the #622 comment below records — so a standing fault keeps every [gone]
766
+ # branch in the pass, and a transient one keeps only the branches whose
767
+ # listing it touched (the #622 transient fixture pins that granularity for
768
+ # the listing failure; this guard follows it rather than latching).
769
+ #
770
+ # Recount before refusing, exactly as inflight.sh does it (#1408, #1421): the
771
+ # registry scan and git's listing are two reads at two instants, and a
772
+ # sibling's `worktree add`/`remove` landing between them makes the counts
773
+ # disagree with nothing wrong. Same order as that copy, first pair and recount
774
+ # alike: `count_registry` FIRST, git's listing SECOND — the loop takes the
775
+ # first registry count just ahead of the #622 guard's `wt_listing`, which is
776
+ # the first listing, so no extra listing is read per branch. A mutation landing
777
+ # between the first count and the listing is already reflected in the listing,
778
+ # so the recount's registry scan agrees with it; the recount re-takes BOTH, in
779
+ # the same order, and re-reads the listing through `wt_listing`, so `$wt_list`
780
+ # — which the lookup then scans — is the very listing the recount validated.
781
+ # inflight.sh's copy recounts once (its `[ "$linked" -eq "$registered" ] ||
782
+ # { count_registry && count_linked; }`); release-ticket.sh's bounds the same
783
+ # loop at two passes (#1424) for a third-mutation window. This copy takes
784
+ # inflight.sh's single recount: a false refusal here costs one pass's wait,
785
+ # never a deletion, and a genuinely dropped entry is a standing state that
786
+ # survives every recount.
787
+ wtroot=
788
+ count_registry() {
789
+ registered=0
790
+ if [ -z "$wtroot" ]; then
791
+ wt_common=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) ||
792
+ { reg_why="could not resolve the git common directory to read the worktree registry"; return 1; }
793
+ wtroot="$wt_common/worktrees"
794
+ fi
795
+ [ -e "$wtroot" ] || return 0
796
+ [ -d "$wtroot" ] && [ -r "$wtroot" ] && [ -x "$wtroot" ] ||
797
+ { reg_why="worktree registry $wtroot could not be read"; return 1; }
798
+ for entry in "$wtroot"/*; do
799
+ [ -d "$entry" ] || continue
800
+ if contents=$(ls -A "$entry" 2>/dev/null) && [ -z "$contents" ]; then continue; fi
801
+ registered=$((registered + 1))
802
+ done
803
+ return 0
804
+ }
805
+
806
+ # Counts `$wt_list` as it stands; the caller decides whether to re-read it.
807
+ count_linked() {
808
+ listed=$(printf '%s\n' "$wt_list" | awk '/^worktree /{c++} END{print c+0}') ||
809
+ { reg_why="could not count the worktrees git listed"; return 1; }
810
+ [ "$listed" -ge 1 ] ||
811
+ { reg_why="git listed no worktrees at all — not even the main checkout"; return 1; }
812
+ linked=$((listed - 1))
813
+ }
814
+
815
+ # Reads the first `count_registry` the loop took ahead of the listing: an
816
+ # unreadable registry there has already set `reg_why`.
817
+ wt_registry_why() {
818
+ [ -z "$reg_why" ] || return 1
819
+ count_linked || return 1
820
+ if [ "$linked" -ne "$registered" ]; then
821
+ count_registry || return 1
822
+ wt_listing ||
823
+ { reg_why="the recount could not re-read the worktree listing: $(printf '%s' "$wt_err" | tr '\n' ' ')"; return 1; }
824
+ count_linked || return 1
825
+ fi
826
+ if [ "$linked" -lt "$registered" ]; then
827
+ reg_why="git listed $linked linked worktrees for $registered registry entries in $wtroot — the listing dropped an entry, and a dropped entry names no branch"
828
+ return 1
829
+ elif [ "$linked" -gt "$registered" ]; then
830
+ reg_why="git listed $linked linked worktrees but only $registered registry entries were counted in $wtroot — the registry read missed entries git can see"
831
+ return 1
832
+ fi
833
+ if ! nameless=$(printf '%s\n' "$wt_list" | awk '
834
+ function flush() { if (n > 1 && !br && h !~ /[^0]/ && hit == "") hit = w }
835
+ /^worktree /{ flush(); n++; w = substr($0, 10); h = ""; br = 0; next }
836
+ /^HEAD /{ h = substr($0, 6) }
837
+ /^branch /{ br = 1 }
838
+ END{ flush(); print hit }'); then
839
+ reg_why="could not scan the worktree listing for a linked worktree with a null HEAD"
840
+ return 1
841
+ fi
842
+ if [ -n "$nameless" ]; then
843
+ reg_why="git listed a linked worktree with a null HEAD and no branch line ($nameless) — the entry no longer says which branch it holds"
844
+ return 1
845
+ fi
846
+ return 0
847
+ }
848
+
849
+ # %(upstream:track) emits exactly [gone] as its own field — nothing to
850
+ # pattern-match, and no -v/-vv trap.
851
+ #
852
+ # %(refname) and a strip, never %(refname:short): the short form is
853
+ # ambiguity-aware, and where a TAG shares a branch's name it stops shortening
854
+ # and emits `heads/<name>` instead (measured, git 2.50.1 Apple Git-155). That
855
+ # string names no branch — `git branch -D`, the delete then, answered "branch
856
+ # not found" — and it
857
+ # does not build the `refs/heads/$b` key the worktree lookup below matches on
858
+ # either, so $wt comes back empty and the main-checkout, .git-linkage, dirty and
859
+ # ignored-files guards all stand down for precisely the branch whose name got
860
+ # away from them. %(refname) is always refs/heads/<name>, so the strip yields
861
+ # the bare name for every branch, ambiguous or not.
862
+ #
863
+ # The $2=="[gone]" field test is deliberately untouched, and it still selects
864
+ # the same branches: a space is not legal in a branch name (measured — git
865
+ # refuses `has space` as invalid), so the name is always the whole of $1, and a
866
+ # branch with no upstream leaves $2 empty rather than matching. The tracking
867
+ # forms that DO carry a space, `[ahead 1]` and its siblings, split so that $2
868
+ # holds `[ahead` — not `[gone]` either way. #634
869
+ # A command substitution inside a `for ... in` word list discards its own
870
+ # exit status entirely, in every shell measured here (bash, dash, macOS
871
+ # /bin/sh): `for x in $(false); do …; done` completes at the loop's own end,
872
+ # runs zero iterations, and never reaches `set -e` — regardless of how the
873
+ # pipeline failed. This script has `set -eu` but no `pipefail`, so a plain
874
+ # `git … | awk …` pipeline reports only its LAST stage's status: a
875
+ # `git for-each-ref` that dies still leaves awk scanning empty input, and
876
+ # awk finishes that scan at rc 0 — the identical exit this loop sees on a
877
+ # genuinely branchless repo. awk is not immune either, and this file's
878
+ # header already documents an awk that cannot finish a scan (the #614/#790
879
+ # multibyte trigger). Either failure, unguarded, reads as a clean sweep
880
+ # that never looked: no branches matched because none was ever seen,
881
+ # indistinguishable from none being reapable.
882
+ #
883
+ # Split into git_probe's own two-capture shape — already this file's answer
884
+ # to the identical git-then-awk pipeline the ignored-files scan below runs
885
+ # (`git_probe`, then a separate `awk` over `$gp_out`) — so each stage's
886
+ # status is read on its own rather than folded into the pipeline's last
887
+ # exit code. Captured into a variable and guarded, rather than looped over
888
+ # directly, so the failure gets a voice. `keep ""`, not `die`: mirrors the
889
+ # branchless sweep's own enumeration guard below (`if ! wt_listing`), for
890
+ # the same reason — dying here would also abort the second sweep and the
891
+ # final `worktree prune`, neither of which this enumeration failing has
892
+ # anything to do with, over a failure this ticket rates mild. #789
893
+ if ! git_probe for-each-ref --format='%(refname) %(upstream:track)' refs/heads; then
894
+ keep "" "could not enumerate [gone] branches — none reaped, and none reported reapable either$(gp_why)"
895
+ gone_branches=""
896
+ else
897
+ # git_probe captures git's stderr into $gp_err instead of leaving it on the
898
+ # real fd — the whole reason it exists (#625) — and every OTHER call site in
899
+ # this file reads $gp_err back out through a targeted check (gp_cut_short,
900
+ # gp_why) before falling through. This call site's success path does
901
+ # neither: an rc-0 `for-each-ref` that still WARNS (PR #1413 review) used to
902
+ # reach the operator's stderr directly, back when this was a plain
903
+ # `git … | awk …` pipeline with git's stderr inherited, and now reaches no
904
+ # one unless forwarded here explicitly.
905
+ [ -z "$gp_err" ] || printf '%s' "$gp_err" >&2
906
+ if ! gone_branches=$(printf '%s\n' "$gp_out" | awk '$2=="[gone]"{sub(/^refs\/heads\//,"",$1); print $1}'); then
907
+ keep "" "could not enumerate [gone] branches — none reaped, and none reported reapable either"
908
+ gone_branches=""
909
+ fi
910
+ fi
911
+ for b in $gone_branches; do
912
+
913
+ # The tip is read ONCE, here, and everything after it measures that frozen
914
+ # SHA rather than the live ref: the cherry below runs against `$tip`, and
915
+ # the delete at the foot of this loop is `git update-ref -d refs/heads/$b
916
+ # $tip`, which refuses unless the ref STILL equals `$tip` at that instant.
917
+ # Before #2219 the cherry read `refs/heads/$b` and the delete was
918
+ # `git branch -D "$b"`, a separate call that deletes whatever the ref holds
919
+ # when it runs — so a commit landing between the two was force-deleted at
920
+ # rc 0: the check-then-delete gap release-ticket.sh closed in #1325
921
+ # (ADR 0018). A tip that cannot be read is a keep, never a delete.
922
+ #
923
+ # `git_probe`, never `2>&1` into the capture: `$tip` is used as a SHA, and a
924
+ # stray `~/.gitconfig` warning git prints at rc 0 (#985) would arrive glued
925
+ # onto it. git's own words still reach the reason, through `gp_why`.
926
+ if ! git_probe rev-parse --verify "refs/heads/$b"; then
927
+ keep "$b" "cannot read the branch tip — not deleted$(gp_why)"
928
+ continue
929
+ fi
930
+ tip=$gp_out
931
+
932
+ # git cherry against origin/main, not a local main: a local main never
933
+ # fast-forwarded reads every merged branch as unmerged. Any + line is a commit
934
+ # that exists nowhere else.
935
+ #
936
+ # Captured, not piped: `cmd | grep -q` takes grep's exit status, never cmd's,
937
+ # so a `git cherry` that dies (exit 128 — one unreadable loose object is
938
+ # enough) prints nothing, grep sees empty input and exits 1 — the identical
939
+ # verdict a genuinely clean cherry produces, so "merged" is indistinguishable
940
+ # from "the probe could not answer". An unmerged branch is never the ambiguous
941
+ # one: its `+` line makes grep exit 0 and always keeps. The delete is
942
+ # authorized by this check and by nothing else — its compare-and-swap refuses
943
+ # a ref that moved off `$tip`, never a `$tip` that is unmerged — so an
944
+ # unanswerable probe must KEEP, the same fail-closed shape the worktree
945
+ # `status` check below already uses.
946
+ # `refs/heads/$b`, never a bare `$b`, where the tip is read above. Restoring
947
+ # the bare name makes a branch that shares its name with a tag ambiguous AS A
948
+ # REV again, and git resolves an ambiguous one by preferring refs/tags/ over
949
+ # refs/heads/ (measured, git 2.50.1 Apple Git-155). This probe would then
950
+ # answer about the TAG's commit while the delete below removes the BRANCH —
951
+ # and a tag sitting on a merged commit reports clean for a branch whose
952
+ # commits exist nowhere else. The delete is authorized by this check and by
953
+ # nothing else, so that reads straight through to destroying them: measured
954
+ # on a fixture, the enumeration fix alone turned a branch this script
955
+ # currently KEEPS into `REAPED`, at exit 0, with an empty kept[]. Qualifying
956
+ # changes nothing for an ordinary branch — both spellings name the same
957
+ # commit — and it is the same key the worktree lookup below already builds.
958
+ #
959
+ # `$base_rev` is the other side of the same rule, and it was missing until
960
+ # #924: `$base` reached this `git cherry` exactly as BASE_REF spelled it, so a
961
+ # local tag named `origin/main` outranked refs/remotes/origin/main and the
962
+ # probe answered about the TAG while `git branch -D`, the delete then,
963
+ # deleted the BRANCH — measured, an unmerged [gone] branch whose commit
964
+ # existed nowhere else REAPED at exit 0 with an empty kept[]. The
965
+ # qualification is built at the top of the file, where its own comment
966
+ # records why the accept-list beside it is what makes prefixing sound. "By
967
+ # nothing else" bounds what ELSE authorizes the delete, not whether this
968
+ # check itself can be wrong — which is why BOTH revs it consumes are
969
+ # qualified. #634
970
+ if ! cherry=$(git cherry "$base_rev" "$tip" 2>&1); then
971
+ keep "$b" "cherry probe failed — cannot tell if merged: $(printf '%s' "$cherry" | tr '\n' ' ')"
972
+ continue
973
+ fi
974
+ # A `+` only at line start is a commit. $cherry holds stderr too — 2>&1 above,
975
+ # so the failure reason can carry git's own words — and an unanchored match
976
+ # reads a `+` anywhere in a diagnostic as a commit line, keeping a branch that
977
+ # is merged. This pipe is safe where the one it replaces was not: it consumes
978
+ # a variable, never git, and the `git cherry` probe already took git's status.
979
+ # Anchored like release-ticket.sh's.
980
+ #
981
+ # What "grep's is the only status left to take" missed, and what this shape
982
+ # exists for: taking it is not the same as READING it. grep answers three
983
+ # ways, and until #1419 the `if` had two arms — an rc 2 scan that never
984
+ # examined `$cherry` fell into the merged arm, and the delete below is
985
+ # authorized by this check and by nothing else. So the deletion went ahead on
986
+ # a merge status no tool had established. `grep_probe` splits the two
987
+ # questions; the answers are ruled on here, in the order that makes the
988
+ # unanswerable case fail CLOSED like every other could-not-check in this
989
+ # file: scan first, verdict second.
990
+ if ! grep_probe "$cherry" '^+'; then
991
+ keep "$b" "cherry scan failed — cannot tell if merged$(gp_why "$gq_err")"
992
+ continue
993
+ elif [ "$gq_rc" -eq 0 ]; then
994
+ keep "$b" "unmerged commits"
995
+ continue
996
+ fi
997
+
998
+ # The registry is counted BEFORE the listing below is read — inflight.sh's
999
+ # order, which `wt_registry_why`'s recount comment explains. A registry that
1000
+ # cannot be read sets `reg_why` here and is refused after the #622 guard, so
1001
+ # a listing failure still reports as one. #2078
1002
+ reg_why=
1003
+ count_registry || :
1004
+
1005
+ # The path is the whole rest of the line, never awk's $2: `worktree list
1006
+ # --porcelain` prints it raw, so a checkout living under a directory with a
1007
+ # space in it — ordinary on macOS — was otherwise truncated at the first
1008
+ # one, and every check below then ran against a wrong, nonexistent path.
1009
+ #
1010
+ # A listing that cannot be read fails CLOSED, like every other could-not-check
1011
+ # in this file: `$wt` would be empty, every guard under `[ -n "$wt" ]` below
1012
+ # skipped, and `git branch -D`, the delete then, needed no answer from the
1013
+ # registry to delete a branch with no worktree — so a merged [gone] branch was
1014
+ # force-deleted while the sweep could not see the registry at all. The holder
1015
+ # check at the delete re-reads the listing and keeps on a failed read too, but
1016
+ # it answers one question — does a worktree hold this branch — and every guard
1017
+ # under `[ -n "$wt" ]` asks others, so this lookup still fails closed on its
1018
+ # own. Keeping it strands every [gone] branch in this pass on one repo-level
1019
+ # failure, since the listing is re-read per branch (header: every
1020
+ # precondition is recomputed); reap runs after every merge pass, so each waits
1021
+ # one pass with the cause named. #622
1022
+ #
1023
+ # A genuine awk failure is a DIFFERENT fault from the listing failing, and is
1024
+ # guarded separately: it fires only when `wt_listing` itself succeeded — a
1025
+ # real, non-empty `$wt_list` — and awk could not finish scanning it (the
1026
+ # #614/#790 multibyte trigger this file's header documents). Left bare, that
1027
+ # failure aborted the whole script on awk's own diagnostic, with no
1028
+ # `reap:`-prefixed line for a caller to grep stderr for — the same shape #243
1029
+ # fixed in release-ticket.sh's own copy of this lookup. `keep`, not `die`:
1030
+ # nothing has mutated $b yet, and dying here would also discard whatever
1031
+ # earlier iterations of this loop already reaped — the same reason the
1032
+ # branchless sweep below keeps rather than dies on its own copy of this pipe,
1033
+ # and the same reason the listing failure above keeps. #789
1034
+ if ! wt_listing; then
1035
+ keep "$b" "worktree lookup failed — cannot tell whether $b has a worktree; kept until a pass that can read the registry: $(printf '%s' "$wt_err" | tr '\n' ' ')"
1036
+ continue
1037
+ fi
1038
+ # A listing that READ is not yet a listing that can be trusted: see
1039
+ # `wt_registry_why` above. After the #622 guard, before the lookup, so the
1040
+ # lookup scans the listing this check validated (a recount re-reads it). #2078
1041
+ if ! wt_registry_why; then
1042
+ keep "$b" "worktree registry inconsistent — $reg_why; every [gone] branch is kept until a pass that reads a consistent registry"
1043
+ continue
1044
+ fi
1045
+ if ! wt=$(printf '%s\n' "$wt_list" |
1046
+ awk -v b="refs/heads/$b" '/^worktree /{w=substr($0,10)} /^branch /&&$2==b{print w}'); then
1047
+ keep "$b" "could not scan the worktree listing for $b — treating it as unresolved rather than guessing it has none"
1048
+ continue
1049
+ fi
1050
+
1051
+ # A newline in that path used to end the porcelain record before
1052
+ # `substr($0,10)` could read past it, so `$wt` was a prefix of the real path —
1053
+ # a directory not on disk, which `[ -e ]` below then reported absent and the
1054
+ # removal was authorised against. The match itself was never affected: it is
1055
+ # made on the `branch` line, so only the path this sweep REPORTS and acts on
1056
+ # was wrong. `wt_listing` now delivers the whole path with the newline
1057
+ # substituted, and a substituted path is one no `git -C` or `worktree remove`
1058
+ # here can name — so it is refused rather than acted on. #551
1059
+ #
1060
+ # `nl_path ""` is false, so a branch with no worktree falls through to the
1061
+ # `[ -n "$wt" ]` below exactly as before.
1062
+ if nl_path "$wt"; then
1063
+ keep "$b" "worktree $wt holds a newline in its path — nothing here can stat it, so whether it holds work is unknown"
1064
+ continue
1065
+ fi
1066
+
1067
+ if [ -n "$wt" ]; then
1068
+ # Three states, never the two `|| echo dirty` used to collapse it to:
1069
+ # present (readable decides, in the body below), established absent
1070
+ # (nothing to protect — reap.sh's OWN branches never rename their worktree
1071
+ # away from `[gone]`, so a directory that is really not there holds no
1072
+ # work, and it falls through to the removal), or cannot tell (keep — an
1073
+ # unanswerable probe authorizes nothing, the same fail-closed direction the
1074
+ # cherry check above already takes).
1075
+ #
1076
+ # `-e` is this `if`'s own condition, so existence is settled before any
1077
+ # git command runs through $wt: a genuinely deleted directory never
1078
+ # reaches a status call that would fail on it and read as dirty forever
1079
+ # (#83).
1080
+ if [ -e "$wt" ]; then
1081
+ # Establish the .git linkage exists before trusting anything git says
1082
+ # through it. Delete a worktree's .git file outright and `git -C` does
1083
+ # not fail: it walks UP to the enclosing repo and answers about THAT at
1084
+ # rc 0 — which the status call below would otherwise believe is this
1085
+ # worktree's own clean status. `-f`, not `-e`: an empty `.git`
1086
+ # directory and a dangling `.git` symlink leak the identical rc-0
1087
+ # answer. `-x "$wt"` stands aside for the git call below when $wt
1088
+ # itself cannot be searched, rather than guessing "no linkage" about a
1089
+ # worktree that was never actually looked at. This `$wt` is never the
1090
+ # main checkout — it was found by matching a `[gone]` branch above, and
1091
+ # `git worktree add` always writes `.git` as a regular file — so unlike
1092
+ # worktree-audit.sh this does not also need to accept a `.git`
1093
+ # directory. This `-f` test establishes only that the linkage EXISTS,
1094
+ # the same gate release-ticket.sh (#74) and worktree-audit.sh (#128) carry;
1095
+ # that it answers for `$wt` is established by the same-directory
1096
+ # `--show-toplevel` compare right after it (`wt_linkage_why`, #2042).
1097
+ # The main checkout reaches here, and must be answered before the
1098
+ # linkage guard below sees it. `git worktree list --porcelain` emits a
1099
+ # `branch refs/heads/...` line for the main worktree too, so a `[gone]`
1100
+ # branch that is the main checkout's own current branch binds `$wt` to
1101
+ # it — measured; the enumeration above does not exclude it. There `.git`
1102
+ # is a DIRECTORY (a real one always holds `HEAD` directly; an empty
1103
+ # stand-in or dangling symlink does not, which is what keeps this from
1104
+ # matching the broken-linkage shapes), not the regular file
1105
+ # `git worktree add` writes, so the `-f` guard below would call it "no
1106
+ # .git linkage" — measurably false, git answers about that repo
1107
+ # correctly through it. A reap is impossible here either way
1108
+ # (`git worktree remove` refuses a main worktree, and the holder check
1109
+ # before the delete refuses a branch its `branch` line names), so keep
1110
+ # and say which, in the dry run and under --apply alike — the plain `-f`
1111
+ # guard printed a false cause,
1112
+ # and dropping it entirely leaves the dry run promising a reap that can
1113
+ # never happen (#82).
1114
+ if [ -d "$wt/.git" ] && [ -f "$wt/.git/HEAD" ]; then
1115
+ keep "$b" "worktree $wt is the main checkout — cannot remove it or delete the branch checked out in it"
1116
+ continue
1117
+ fi
1118
+ if [ -x "$wt" ] && [ ! -f "$wt/.git" ]; then
1119
+ keep "$b" "worktree $wt has no .git linkage — git would answer for the enclosing repo, not this one"
1120
+ continue
1121
+ fi
1122
+ # Gated on `-f` rather than on "not kept above": an unsearchable `$wt`
1123
+ # fails `-f` too, and is left to the status probe below, which keeps it
1124
+ # with git's own "Permission denied" instead of a cause invented here.
1125
+ if [ -f "$wt/.git" ] && ! wt_linkage_why "$wt"; then
1126
+ keep "$b" "worktree $wt $lk_why"
1127
+ continue
1128
+ fi
1129
+ # `-uall`, never a bare `--porcelain`: the untracked mode is CONFIG, and
1130
+ # `git status` honours `status.showUntrackedFiles`. Set to `no`, the scan
1131
+ # exits 0 with EMPTY output over a worktree holding untracked work — so
1132
+ # the rc check on this line passes, `gp_cut_short` below has no stderr to
1133
+ # gate on, `[ -n "$gp_out" ]` reads clean, and the reap removes the
1134
+ # worktree and takes the work with it, at exit 0, silently. Measured with
1135
+ # a control, git 2.50.1 (Apple Git-155), on an untracked file plus an
1136
+ # untracked subdirectory:
1137
+ #
1138
+ # config `no` `--porcelain` -> rc 0, 0 bytes
1139
+ # `--porcelain -uall` -> rc 0, `?? sub/deep.txt` …
1140
+ # config unset `--porcelain` -> rc 0, `?? sub/` …
1141
+ # `--porcelain -uall` -> rc 0, `?? sub/deep.txt` …
1142
+ #
1143
+ # This is the one shape the fail-closed `if ! …` idiom structurally
1144
+ # cannot see, because the status IS 0 — #730, the rc-0 sibling of the
1145
+ # `git cherry` swallow (#264) this file's branch sweep already documents, where
1146
+ # rc was non-zero and taking the status was the whole fix. Nor can #625's
1147
+ # stderr work reach it: the config yields rc 0, empty stdout AND empty
1148
+ # stderr, so there is nothing for `gp_cut_short` to match. Pinning the
1149
+ # mode on the command line is the only fix: a probe whose EMPTY answer
1150
+ # licenses an action pins an explicit mode; a probe that only reports
1151
+ # after a gate has already refused need not (see below). `git worktree
1152
+ # remove`'s own refusal is no backstop, being the same machinery the
1153
+ # same config silences (measured at the --apply call below).
1154
+ #
1155
+ # The one bare `--porcelain` left in a SCRIPT is deliberate:
1156
+ # instruments.sh prints one to stderr to say WHAT changed, after a digest
1157
+ # over `git ls-files` has already refused. That digest covers TRACKED
1158
+ # files only, so no untracked file can trigger it and the silenced mode
1159
+ # cannot hide the thing being reported. A report, not a gate. (Prose
1160
+ # instructions to an agent are a separate inventory — see SKILL.md and
1161
+ # docs/specs/2026-07-22-run-team-agent-fleet-design.md, pinned
1162
+ # alongside the scripts.)
1163
+ #
1164
+ # `-uall` here, not `-unormal`: both override the config, but this probe
1165
+ # IS the dirty gate itself (unlike the `--ignored` reason-string probe
1166
+ # below, whose keep/reap verdict does not depend on per-file detail),
1167
+ # and `-uall` is the form #730 measured against this site.
1168
+ if ! git_probe -C "$wt" status --porcelain -uall; then
1169
+ keep "$b" "worktree $wt could not be read$(gp_why)"
1170
+ continue
1171
+ fi
1172
+ # Before the dirty check, never after it: a walk git could not finish
1173
+ # answers EMPTY, so `[ -n "$gp_out" ]` below reads it as clean and the
1174
+ # run goes on to delete a worktree it never finished reading. An earlier
1175
+ # version of this comment argued a plain scan cannot reach that warning
1176
+ # because it skips ignored paths without opening them; the scan does open
1177
+ # UNTRACKED directories, and measurably warns at rc 0 on an unreadable
1178
+ # one. $gp_out still stays clean of whatever reached stderr — that is
1179
+ # what git_probe is for — so a warning is never read as dirty content
1180
+ # either.
1181
+ if gp_cut_short; then
1182
+ keep "$b" "worktree $wt status warned, listing may be incomplete$(gp_why)"
1183
+ continue
1184
+ fi
1185
+ if [ -n "$gp_out" ]; then
1186
+ keep "$b" "dirty worktree $wt"
1187
+ continue
1188
+ fi
1189
+
1190
+ # `git worktree remove` refuses on modified and untracked files, but NOT
1191
+ # on ignored ones — it deletes those silently. In a NON-fleet worktree a
1192
+ # precious ignored file (.env, scratch) must not vanish, so check
1193
+ # --ignored and keep. A fleet worktree is different: claim-ticket.sh
1194
+ # creates it under .worktrees/ fresh from origin/main. Merged
1195
+ # (cherry-clean above) + tracked-clean (--porcelain above), its ONLY
1196
+ # ignored files are machine-generated (agent-test, node_modules, build
1197
+ # output) — nothing precious. Since every fleet worktree carries them,
1198
+ # keeping on ignored files would strand them all and defeat reap. Run
1199
+ # the ignored-keep for non-fleet trees only, keyed on the .worktrees/
1200
+ # home (robust to an older tree that predates the agent-test marker).
1201
+ case "$wt" in
1202
+ */.worktrees/*) : ;;
1203
+ *)
1204
+ # An explicit mode for the reason the plain scan above states, and
1205
+ # it is NOT redundant with it: this probe is the same machinery, so
1206
+ # the same `status.showUntrackedFiles = no` silences the backstop
1207
+ # that exists to catch what the primary gate misses, and the
1208
+ # apparent defence in depth is only apparent. Measured on the same
1209
+ # fixture: under that config `--porcelain --ignored` answers 0
1210
+ # bytes at rc 0 — the `!!` lines are suppressed too, so a precious
1211
+ # ignored file reads as absent — while `--porcelain -unormal
1212
+ # --ignored` lists both `??` and `!!` entries. #730.
1213
+ #
1214
+ # `-unormal`, not `-uall`, here: this probe only builds the
1215
+ # human-readable "keep" reason string below, and the keep/reap
1216
+ # verdict is unaffected either way — `-uall` would additionally
1217
+ # expand every file INSIDE an ignored directory (e.g. `node_modules`)
1218
+ # into its own `!!` line instead of the one line `-unormal` gives
1219
+ # the directory, detail nobody downstream reads. Measured: 5000
1220
+ # ignored files under one directory cost 129KB/6.8s under `-uall`
1221
+ # versus 293B/0.19s under `-unormal`; at 10000 files, 259KB/27.8s,
1222
+ # roughly quadratic. `-unormal` defeats the config equally well at
1223
+ # none of that cost.
1224
+ if ! git_probe -C "$wt" status --porcelain -unormal --ignored; then
1225
+ keep "$b" "worktree $wt unreadable (git status --ignored failed)$(gp_why)"
1226
+ continue
1227
+ fi
1228
+ # `--ignored` asks git to OPEN every ignored path to list what is
1229
+ # inside it (measured, PR #726 review: a `chmod 000` ignored
1230
+ # directory made this exact probe warn and exit 0). A precious
1231
+ # ignored file under a path git could not open would never reach
1232
+ # $ignored, and `git worktree remove` deletes ignored files
1233
+ # silently — so a cut-short walk fails closed rather than report what
1234
+ # git managed to see as the whole answer.
1235
+ if gp_cut_short; then
1236
+ keep "$b" "worktree $wt status --ignored warned, listing may be incomplete$(gp_why)"
1237
+ continue
1238
+ fi
1239
+ # `paste`, not `awk`, used to be this substitution's last stage, so
1240
+ # the substitution reported PASTE's status only — an awk that could
1241
+ # not finish scanning `$gp_out` (the #614/#790 trigger) failed
1242
+ # silently AND invisibly: unlike the bare assignments above, nothing
1243
+ # here even reads as "empty means none", because the captured
1244
+ # pipeline still succeeds — paste has nothing of its own to fail on
1245
+ # an empty or partial input. Restructured into two captures so each
1246
+ # fallible stage's own status survives, the rule json.sh states for
1247
+ # `jstr`'s `sed | tr` ("EVERY FALLIBLE STAGE'S STATUS IS READ") and
1248
+ # the shape release-ticket.sh's own worktree lookups already take.
1249
+ # `keep`, not `die`, for the reason the worktree lookup above gives:
1250
+ # this is per-branch and nothing has mutated $b yet. #789
1251
+ if ! ignored_lines=$(printf '%s\n' "$gp_out" | awk '/^!! /{sub(/^!! /,""); print}'); then
1252
+ keep "$b" "worktree $wt ignored-files scan failed — treating it as unresolved rather than guessing it has none"
1253
+ continue
1254
+ fi
1255
+ if [ -n "$ignored_lines" ]; then
1256
+ if ! ignored=$(printf '%s\n' "$ignored_lines" | paste -sd, -); then
1257
+ keep "$b" "worktree $wt ignored-files list could not be joined"
1258
+ continue
1259
+ fi
1260
+ keep "$b" "ignored files present in $wt: $ignored"
1261
+ continue
1262
+ fi
1263
+ ;;
1264
+ esac
1265
+ elif ! gone "$wt"; then
1266
+ keep "$b" "cannot tell whether worktree $wt exists"
1267
+ continue
1268
+ fi
1269
+
1270
+ # Refused before the removal below, and in the dry run as well as under
1271
+ # `--apply`, for the reason the main-checkout guard above records (#82): a
1272
+ # `would remove worktree` line the next `--apply` refuses is a promise this
1273
+ # script cannot keep. Unlike git's own refusals (#391) this one IS
1274
+ # predictable — the cwd is known before anything is deleted.
1275
+ #
1276
+ # Below the probes rather than above them, so every reason already true of
1277
+ # this worktree keeps its precedence: dirty, unreadable and unmerged all
1278
+ # name something about the worktree itself, while this one names only where
1279
+ # the script happens to stand. It sits here, last, because this is the
1280
+ # guard the removal is refused by.
1281
+ #
1282
+ # `continue`, so the branch is kept with its worktree — the pairing the
1283
+ # main-checkout reason already states, and the holder check before the
1284
+ # delete would refuse a branch checked out in a surviving worktree anyway.
1285
+ # #992
1286
+ #
1287
+ # Ancestor match, not exact equality: a worktree nested inside `$wt`
1288
+ # (a real, documented shape — SKILL.md names a member committing from a
1289
+ # nested worktree) has `$wt` as an ancestor on disk, so removing `$wt`
1290
+ # removes the nested one's files too — taking any uncommitted work in it
1291
+ # along, the exact #992 signature one path further out — even though
1292
+ # `$wt` itself never equals `$self_wt` in that shape (#1441). `holds_cwd`
1293
+ # carries the match and why it is on the directory, not only the string.
1294
+ if holds_cwd "$wt"; then
1295
+ keep "$b" "worktree $wt holds the working directory this run was started in — removing it would delete the cwd every git call after it needs; rerun from outside it"
1296
+ continue
1297
+ fi
1298
+
1299
+ # Reached with $wt either present-readable-clean or established absent —
1300
+ # `git worktree remove` accepts a prunable-because-absent entry at rc 0
1301
+ # and clears the stale registration outright (verified, git 2.50.1, same
1302
+ # as release-ticket.sh measures for its own delete), so no separate branch
1303
+ # is needed for the absent case.
1304
+ if [ "$apply" = true ]; then
1305
+ # No --force, ever. It refuses on modified and untracked files — but
1306
+ # that refusal reads the same `status` machinery the probe above does, so
1307
+ # it is a DEFAULT-config guarantee, not an absolute. Measured here, git
1308
+ # 2.50.1 (Apple Git-155), with a control: with `status.showUntrackedFiles
1309
+ # = no` set, removing a worktree holding an untracked file exits 0 and
1310
+ # takes the file with it; the identical fixture without that config exits
1311
+ # 128 refusing. That is why the probes above pin `-uall` (#730) and why
1312
+ # this line may not be read as a second opinion: the config that silences
1313
+ # them silences this too, so the gate above is the ONLY thing standing
1314
+ # here. The ignored-file gap it never covers under any config is handled
1315
+ # by the check above.
1316
+ #
1317
+ # A non-zero exit does NOT mean the removal had no effect. Measured here,
1318
+ # git 2.50.1 (Apple Git-155): a locked worktree exits 128 with the
1319
+ # registration INTACT, while a symlink standing in for the directory
1320
+ # exits 255 with the registration CLEARED. Reading "refused" off the exit
1321
+ # code reports the second as though nothing had happened.
1322
+ #
1323
+ # Re-read the REGISTRY, never the filesystem, and claim only what that
1324
+ # read answers. The registration and the directory are INDEPENDENT facts,
1325
+ # in both directions — measured: a peer session that finishes the same
1326
+ # removal between this lookup and this remove clears the registration
1327
+ # with nothing left on disk (the concurrency this script's own header
1328
+ # documents), and `chmod 555 .git/worktrees/<id>` deletes the whole
1329
+ # directory while the entry stays listed. So a cleared registration is no
1330
+ # evidence of an orphan, an intact one is no evidence that nothing was
1331
+ # removed, and naming a filesystem state nobody probed would be this
1332
+ # ticket's own defect — a reason naming something other than what was
1333
+ # measured — committed inside its fix. #83, reap.sh and
1334
+ # release-ticket.sh answering an unreadable worktree in opposite
1335
+ # directions, is closed; a third filesystem probe here would reopen
1336
+ # exactly that ground. `gone()` above is deliberately not reused: it
1337
+ # answers a harder question (established absence vs an unsearchable
1338
+ # prefix) that a registry read does not have, and cannot fail the way a
1339
+ # stat can.
1340
+ #
1341
+ # Captured, not piped: `git … | grep -q` takes grep's status, never
1342
+ # git's — the same swallow fixed for `git cherry` above, which the probe
1343
+ # that reports it must not reintroduce. A registry read that itself fails
1344
+ # says so, rather than being misread as "cleared".
1345
+ #
1346
+ # `grep_probe`, not a bare `grep -q`, for the half of that the capture
1347
+ # alone never covered: grep's rc 2 also read as "cleared" here, so a
1348
+ # scanner that could not examine the listing reported the alarming state
1349
+ # as a measurement. Nothing on disk turns on it — both arms keep and
1350
+ # continue — which is exactly why it is a REASON bug and not a deletion
1351
+ # bug, and why the unanswerable arm here joins the existing
1352
+ # unread-listing arm rather than inventing a third verdict. #1419
1353
+ #
1354
+ # Still keep, still continue, and nothing on disk is touched either way:
1355
+ # one refusal must not strand the remaining branches of an unattended
1356
+ # sweep, and a directory whose contents nobody has inspected is not this
1357
+ # script's to delete.
1358
+ if ! err=$(git worktree remove "$wt" 2>&1); then
1359
+ wt_reg_state "$wt"
1360
+ keep "$b" "worktree remove refused ($state): $(printf '%s' "$err" | tr '\n' ' ')"
1361
+ continue
1362
+ fi
1363
+ else
1364
+ printf ' would remove worktree %s\n' "$wt" >&2
1365
+ fi
1366
+ removed="${removed}$(jfield "$wt"),"
1367
+ fi
1368
+
1369
+ if [ "$apply" = true ]; then
1370
+ # What the compare-and-swap below does not give back: `git update-ref` is
1371
+ # ref-only plumbing and, unlike `git branch -D` (the delete here until
1372
+ # #2219), consults no worktree at all. `-D`'s own delete-time refusal on a
1373
+ # branch a worktree holds is replaced by worktree.sh's `wt_holding`, over
1374
+ # the listing re-read here rather than the one the `$wt` lookup above
1375
+ # read: the `worktree remove` above has changed it since, and a
1376
+ # `git worktree add` for this branch can land after that lookup. Held by
1377
+ # either route `-D` refused on — a `branch` line, or a detached worktree
1378
+ # stopped mid `rebase -i` or mid `git bisect` on this branch, which the
1379
+ # `$wt` lookup never binds because the listing prints no `branch` line for
1380
+ # it. Measured, git 2.50.1: `-D` refuses both, `update-ref -d` deletes
1381
+ # both, and the sibling's `rebase --continue` then fails on `cannot lock
1382
+ # ref` (#1330, #2218). A worktree the reader cannot resolve is a keep,
1383
+ # never "not held".
1384
+ #
1385
+ # Under --apply only, like the delete it guards: in the dry run the
1386
+ # worktree the `$wt` lookup found is still registered, and would read as a
1387
+ # holder of the very branch it pairs with. The dry run therefore cannot
1388
+ # predict THIS branch's own refusal — but not "exactly as it could not
1389
+ # predict `-D`'s" (#391): `-D`'s blind spot here was only ever this
1390
+ # branch's own paired worktree. A registry read that fails closed for an
1391
+ # UNRELATED worktree elsewhere in the listing (reaping.md) keeps every
1392
+ # `[gone]` branch in the pass, a repo-wide case `-D` had no equivalent of
1393
+ # — it needed no registry answer at all and failed OPEN on one it could
1394
+ # not read (#622). The dry run — printing `would reap` unconditionally
1395
+ # here — cannot predict any of those keeps either.
1396
+ #
1397
+ # A window remains between this re-read and the delete, per the ruling on
1398
+ # #1330 (Q2, ADR 0018): a checkout landing in it breaks that worktree but
1399
+ # cannot lose a commit — a commit made there moves the ref off `$tip`, and
1400
+ # the compare-and-swap refuses.
1401
+ if ! wt_listing; then
1402
+ keep "$b" "cannot re-read the worktree list to check $b before the delete — not deleted: $(printf '%s' "$wt_err" | tr '\n' ' ')"
1403
+ continue
1404
+ fi
1405
+ if wt_holding "refs/heads/$b"; then held_rc=0; else held_rc=$?; fi
1406
+ case $held_rc in
1407
+ 0)
1408
+ keep "$b" "$b $wt_holder_how in worktree $wt_holder — not deleted"
1409
+ continue
1410
+ ;;
1411
+ 1) ;;
1412
+ *)
1413
+ keep "$b" "cannot tell whether $b is held by worktree $wt_holder — not deleted"
1414
+ continue
1415
+ ;;
1416
+ esac
1417
+
1418
+ # The compare-and-swap: `update-ref -d <ref> <tip>` deletes only while the
1419
+ # ref still equals the `$tip` the cherry check measured, so a commit
1420
+ # landing since is refused with git's `cannot lock ref … is at <new> but
1421
+ # expected <tip>`, branch and commit intact. Never plain `git branch -d`:
1422
+ # upstream is gone, so it compares against a possibly-behind local HEAD
1423
+ # and refuses everything here (#760).
1424
+ #
1425
+ # `--no-deref`: measured, git 2.50.1, `update-ref -d` on a branch that is
1426
+ # a symbolic ref deletes the branch it POINTS AT and leaves the symref
1427
+ # dangling. `-D` deleted the symref itself, and so does this.
1428
+ #
1429
+ # `2>&1` into the capture, and update-ref prints nothing on stdout: a bare
1430
+ # "branch delete failed" names the step, never the fault, and git's own
1431
+ # diagnosis is the only thing that tells an operator which remedy applies
1432
+ # (#391).
1433
+ if ! err=$(git update-ref --no-deref -d "refs/heads/$b" "$tip" 2>&1); then
1434
+ keep "$b" "branch delete failed: $(printf '%s' "$err" | tr '\n' ' ')"
1435
+ continue
1436
+ fi
1437
+ # The `[branch "<b>"]` config section, which `-D` removed with the ref and
1438
+ # ref-only `update-ref` leaves behind. Measured, git 2.50.1: a later
1439
+ # `git branch --no-track <b>` inherits the stale upstream and reads
1440
+ # `[gone]` at once, so the next pass would select it. The branch is
1441
+ # already deleted, so a failure here is never a keep — but it is not
1442
+ # stderr-only either: an unattended caller reading only stdout JSON must
1443
+ # still learn the stale upstream was left, so it lands in `warnings` too.
1444
+ if ! err=$(git config --remove-section "branch.$b" 2>&1); then
1445
+ errflat=$(printf '%s' "$err" | tr '\n' ' ')
1446
+ printf ' note: %s deleted, but its branch config section was left: %s\n' "$b" "$errflat" >&2
1447
+ warnings="${warnings}{\"branch\":$(jfield "$b"),\"note\":$(jfield "branch config section was left: $errflat")},"
1448
+ fi
1449
+ echo " REAPED $b" >&2
1450
+ else
1451
+ echo " would reap $b" >&2
1452
+ fi
1453
+ reaped="${reaped}$(jfield "$b"),"
1454
+ done
1455
+
1456
+ # Second sweep: the worktrees the branch sweep above cannot see AT ALL.
1457
+ #
1458
+ # That sweep locates a worktree by the `branch refs/heads/<name>` line
1459
+ # `git worktree list --porcelain` prints for it, so a worktree carrying no such
1460
+ # line was never refused — it was never considered, which is why the
1461
+ # no-silent-caps rule did not fire either: no `would remove worktree` line, no
1462
+ # `kept` entry, and the directory left on disk while its branch was reaped
1463
+ # (#381, measured live during a merge pass). A stale worktree still answers
1464
+ # `git worktree list` and inflight.sh reads one as a live claim, so an
1465
+ # already-merged ticket then reads as taken and the candidate queue shrinks
1466
+ # with nothing reporting it.
1467
+ #
1468
+ # What leaves a fleet worktree detached is NOT recorded here, deliberately. An
1469
+ # earlier draft of this comment blamed the merge bot's server-side rebase (#149)
1470
+ # and that mechanism is measured false: in a later pass the bot reported
1471
+ # `path=rebase` for #969, #970 and #972, and a `reap.sh` dry run immediately
1472
+ # after printed `would remove worktree` for all three — a line only an ATTACHED
1473
+ # worktree reaches. run-merge-bot.md says the same for that step: the API
1474
+ # rebased the remote, not your checkout, which is left attached and merely
1475
+ # stale. The shape is observed; the route to it is not established, and
1476
+ # release-ticket.sh names a different one (an interrupted rebase) it did
1477
+ # measure. This sweep decides on the state git reports, never on how it got
1478
+ # there, so nothing below depends on the answer.
1479
+ #
1480
+ # Deliberately a second sweep rather than a shared helper over the guard chain
1481
+ # above. The two differ in more than their subject: there is no branch to name
1482
+ # in a reason, none to delete afterwards, the merged probe takes a bare object
1483
+ # id instead of a refname, and the in-progress guard below has no business on a
1484
+ # `[gone]` branch, where a stale sequencer file would strand a worktree whose PR
1485
+ # has already merged. Same call reap.sh and release-ticket.sh already make for
1486
+ # their two copies of `gone()`, for the opposite reason: there the callers
1487
+ # differ in nothing else.
1488
+ if ! wt_listing; then
1489
+ keep "" "cannot enumerate worktrees — a branchless one would go unreported: $(printf '%s' "$wt_err" | tr '\n' ' ')"
1490
+ # `h" "p`, an object id and a path: the id is fixed-width hex with no space in
1491
+ # it, so the shell splits the pair on the first space and the path keeps the
1492
+ # rest — the whole rest, since `substr($0,10)` is what reads it, never awk's
1493
+ # `$2`, or a checkout under a directory with a space in its name reads as a
1494
+ # different path. A record git printed no `HEAD` line for leaves the id empty,
1495
+ # which the null-object-id arm below already answers for.
1496
+ #
1497
+ # `bare` sets the same exclusion flag a `branch` line does. A bare repo used as
1498
+ # a worktree root prints `worktree <path>` then `bare` and NOTHING else — no
1499
+ # HEAD, no branch (measured, git 2.50.1 Apple Git-155) — so without this it
1500
+ # arrived below with an empty id and was reported with the null-object-id arm's
1501
+ # diagnosis, "has an unresolvable HEAD", which is false: git can say exactly
1502
+ # what it holds, a bare repo holds no working tree at all. It is never a
1503
+ # `[gone]`-branch worktree and there is nothing there to remove.
1504
+ #
1505
+ # Status taken, not swallowed: this pipeline's last command is the awk, so an
1506
+ # awk that could not run leaves `$detached` empty and every branchless worktree
1507
+ # goes unmentioned — this ticket's own defect, committed inside its fix. The
1508
+ # branch sweep above takes both statuses too — the listing's and its awk's —
1509
+ # and keeps the branch on either, since #622.
1510
+ #
1511
+ # Pinned since #993, at the same arm the paragraph above admits to: reap.test.mjs
1512
+ # shims a failing `awk` onto PATH, selected by this program's own `/^bare$/`
1513
+ # rule, over a repo holding one detached worktree, and requires the decline
1514
+ # below with an EMPTY removal list. Swallow this status and that fixture's
1515
+ # sweep goes silently empty — measured, the test reds on `kept.length` 0.
1516
+ elif ! detached=$(printf '%s\n' "$wt_list" |
1517
+ awk '/^worktree /{if (p != "" && !skip) print h" "p; p=substr($0,10); h=""; skip=0; next}
1518
+ /^HEAD /{h=$2}
1519
+ /^branch /{skip=1}
1520
+ /^bare$/{skip=1}
1521
+ END{if (p != "" && !skip) print h" "p}'); then
1522
+ keep "" "could not read the worktrees git listed — a branchless one would go unreported"
1523
+ else
1524
+ while IFS= read -r entry; do
1525
+ [ -n "$entry" ] || continue
1526
+ head=${entry%% *}
1527
+ wt=${entry#* }
1528
+
1529
+ # Before any probe stats `$wt`, and before the main-checkout test below,
1530
+ # which would answer `-d "$wt/.git"` about a path that is not the one git
1531
+ # listed. A newline in the path used to split the porcelain record AND the
1532
+ # `read -r` line above, so this sweep saw a prefix and, being the sweep that
1533
+ # deletes branchless worktrees, could authorise a removal against it.
1534
+ # `wt_listing` keeps the record and the line whole; the substituted byte is
1535
+ # what no command here can name, so the entry is kept and reported. #551
1536
+ if nl_path "$wt"; then
1537
+ keep "" "worktree $wt holds a newline in its path — nothing here can stat it, so whether its work has landed is unknown"
1538
+ continue
1539
+ fi
1540
+
1541
+ # The main checkout, answered before the ownership bound below so it keeps
1542
+ # the reason that is true of it rather than the one true of every stranger.
1543
+ # It reaches this sweep whenever it is itself detached, it is never under
1544
+ # `.worktrees/`, and this test needs nothing the probes below establish —
1545
+ # both operands are false for a path that does not exist. Still ahead of the
1546
+ # linkage test for the reason the branch sweep records (#82): that test would
1547
+ # otherwise call the main checkout's `.git` DIRECTORY a broken linkage.
1548
+ if [ -d "$wt/.git" ] && [ -f "$wt/.git/HEAD" ]; then
1549
+ keep "" "worktree $wt is the main checkout — cannot remove it"
1550
+ continue
1551
+ fi
1552
+
1553
+ # The ownership bound, and the first thing asked of anything else. The branch sweep above
1554
+ # authorises a delete on evidence the PR merged — `%(upstream:track)` reads
1555
+ # exactly `[gone]`, the remote branch deleted. This sweep has no such
1556
+ # evidence to read: branchless, clean and patch-equivalent to `$base` also
1557
+ # describes a human's `git worktree add --detach` scratch checkout that was
1558
+ # never a fleet ticket, and without this bound `--apply` deleted it
1559
+ # (measured, PR #985 review: the same fixture survives the branch-only
1560
+ # script and is DELETED by the branchless one). `*/.worktrees/*` is the
1561
+ # fleet's own worktree home — the set #381 describes — and the same key
1562
+ # claim-ticket.sh builds its paths under.
1563
+ #
1564
+ # A `keep`, never a silent `continue`: a directory this script looked at and
1565
+ # walked past with nothing said is the exact defect #381 exists to end, and
1566
+ # the reason has to survive being read by someone who expected a removal.
1567
+ #
1568
+ # It is also why this sweep carries no `--ignored` probe, unlike the branch
1569
+ # sweep: that probe exists to protect a .env or a scratch note in a worktree
1570
+ # OUTSIDE this home, and no such worktree reaches past this bound.
1571
+ case "$wt" in
1572
+ */.worktrees/*) : ;;
1573
+ *)
1574
+ keep "" "worktree $wt is not a fleet worktree — outside .worktrees/, so nothing here says its work has landed"
1575
+ continue
1576
+ ;;
1577
+ esac
1578
+
1579
+ # An absent `branch` line is not by itself a detached checkout: git also
1580
+ # emits none for a worktree whose HEAD it could not resolve, which it
1581
+ # reports as the null object id — a `chmod 000` or garbage admin `HEAD`
1582
+ # file, a dangling symlink or a directory standing in for one. Those are
1583
+ # the four routes #179 measured against release-ticket.sh's own lookup, and
1584
+ # they empty this key exactly as a detached HEAD does. Nothing about such a
1585
+ # worktree can be decided — there is no commit to probe for merged-ness —
1586
+ # so it is reported and left, the same fail-closed direction the cherry
1587
+ # checks take. The conjunction release-ticket.sh's `unresolved_head` makes
1588
+ # in one place is made here in two: the enumeration above already
1589
+ # established this record carries no `branch` line, which is what keeps an
1590
+ # unborn branch — a legitimate null id that DOES carry one — out of this
1591
+ # arm entirely.
1592
+ case "$head" in
1593
+ *[!0]*) : ;;
1594
+ *)
1595
+ keep "" "worktree $wt has an unresolvable HEAD — git cannot say what it holds"
1596
+ continue
1597
+ ;;
1598
+ esac
1599
+
1600
+ # `git cherry`, never `git merge-base --is-ancestor`: the branch was rebased
1601
+ # before it merged, so its tip is patch-equivalent to what landed rather
1602
+ # than an ancestor of it, and ancestry answers no for work that is fully
1603
+ # upstream. Captured, never piped into `grep -q`, for the reason the branch
1604
+ # sweep above records: the pipeline would take grep's status and a probe
1605
+ # that died would read identically to a clean one. `$head` is a full object
1606
+ # id, so no refname can shadow it the way #634 measured for a bare branch
1607
+ # name — but the BASE side is a shorthand until it is qualified, and this
1608
+ # sweep removes DIRECTORIES, so the #924 shadowing costs the files
1609
+ # themselves here and not only a branch ref: measured, a local tag named
1610
+ # `origin/main` at a detached worktree's own tip made this probe read clean
1611
+ # and `--apply` deleted the worktree holding the only copy of that commit.
1612
+ # `$base_rev` is built at the top of the file; the branch sweep's copy of
1613
+ # this probe carries the same qualification for the same reason.
1614
+ if ! cherry=$(git cherry "$base_rev" "$head" 2>&1); then
1615
+ keep "" "cherry probe failed — cannot tell if worktree $wt is merged: $(printf '%s' "$cherry" | tr '\n' ' ')"
1616
+ continue
1617
+ fi
1618
+ # Three-way, for the reason the branch sweep's copy of this check records
1619
+ # in full: grep's rc 2 is not its rc 1, and the no-match arm here reaches
1620
+ # `git worktree remove`, so the swallow cost DIRECTORIES in this sweep and
1621
+ # not only a branch ref. #1419
1622
+ if ! grep_probe "$cherry" '^+'; then
1623
+ keep "" "cherry scan failed — cannot tell if worktree $wt is merged$(gp_why "$gq_err")"
1624
+ continue
1625
+ elif [ "$gq_rc" -eq 0 ]; then
1626
+ keep "" "worktree $wt holds commits that exist nowhere else"
1627
+ continue
1628
+ fi
1629
+
1630
+ if [ -e "$wt" ]; then
1631
+ # The remaining guards the branch sweep above documents, in the same order
1632
+ # and for the same measured reasons — the main checkout already answered
1633
+ # for above, the linkage established — present (#128), then answering
1634
+ # for `$wt` itself (#2042) — before anything git says through `$wt` is
1635
+ # trusted, and existence settled by this `if` so a deleted directory
1636
+ # never reaches a status call that would read as dirty forever (#83).
1637
+ if [ -x "$wt" ] && [ ! -f "$wt/.git" ]; then
1638
+ keep "" "worktree $wt has no .git linkage — git would answer for the enclosing repo, not this one"
1639
+ continue
1640
+ fi
1641
+ if [ -f "$wt/.git" ] && ! wt_linkage_why "$wt"; then
1642
+ keep "" "worktree $wt $lk_why"
1643
+ continue
1644
+ fi
1645
+ # `-uall`: #730, see the branch sweep's copy of this probe above for the
1646
+ # full explanation. This sweep removes DIRECTORIES, so it is the arm
1647
+ # where the misread a bare `--porcelain` produces costs the files
1648
+ # themselves.
1649
+ if ! git_probe -C "$wt" status --porcelain -uall; then
1650
+ keep "" "worktree $wt could not be read$(gp_why)"
1651
+ continue
1652
+ fi
1653
+ # Same gate, same order, and the same reason as the branch sweep's copy
1654
+ # of this probe: a cut-short walk answers empty, so it has to be caught
1655
+ # before the dirty check below rather than after it.
1656
+ if gp_cut_short; then
1657
+ keep "" "worktree $wt status warned, listing may be incomplete$(gp_why)"
1658
+ continue
1659
+ fi
1660
+ if [ -n "$gp_out" ]; then
1661
+ keep "" "dirty worktree $wt"
1662
+ continue
1663
+ fi
1664
+
1665
+ # A guard the branch sweep needs no copy of, and the one thing on this
1666
+ # path git is no backstop for: `git worktree remove` WITHOUT `--force`
1667
+ # removes a worktree holding an interrupted rebase or a bisect at exit 0,
1668
+ # sequencer state and all, with `git status --porcelain` empty. Both
1669
+ # operations also DETACH, which is precisely how they arrive in this
1670
+ # sweep and nowhere else: release-ticket.sh's prose already names the
1671
+ # interrupted rebase as the way a fleet worktree wanders off its branch.
1672
+ # worktree.sh's `wt_op_state` holds the marker list, the measurements
1673
+ # and why its admin-dir read is `2>/dev/null` rather than `2>&1`; a
1674
+ # worktree it cannot read is kept, never removed.
1675
+ if ! wt_op_state "$wt"; then
1676
+ keep "" "worktree $wt could not be read"
1677
+ continue
1678
+ fi
1679
+ if [ -n "$wt_op" ]; then
1680
+ keep "" "worktree $wt has a git operation in progress ($wt_op) — removing it discards state no commit holds"
1681
+ continue
1682
+ fi
1683
+
1684
+ # No `--ignored` probe here, unlike the branch sweep: the ownership bound
1685
+ # at the head of this loop already refused every worktree outside
1686
+ # `.worktrees/`, and inside it the branch sweep exempts the probe anyway —
1687
+ # a fleet worktree's ignored files are machine-generated, and keeping on
1688
+ # them would strand every one of them.
1689
+ elif ! gone "$wt"; then
1690
+ keep "" "cannot tell whether worktree $wt exists"
1691
+ continue
1692
+ fi
1693
+
1694
+ # The branch sweep's copy of this guard carries the reasoning; the only
1695
+ # difference here is that there is no branch to keep with the directory.
1696
+ # After the ownership bound above, deliberately: a worktree this sweep would
1697
+ # never remove needs no word about where the script is standing, and the
1698
+ # bound's own reason is the one true of it. #992
1699
+ #
1700
+ # Ancestor match, not exact equality — same reasoning as the branch
1701
+ # sweep's copy of this guard: a worktree nested inside `$wt` is removed
1702
+ # along with it even though `$wt` never equals `$self_wt` in that shape.
1703
+ # (#1441)
1704
+ if holds_cwd "$wt"; then
1705
+ keep "" "worktree $wt holds the working directory this run was started in — removing it would delete the cwd every git call after it needs; rerun from outside it"
1706
+ continue
1707
+ fi
1708
+
1709
+ if [ "$apply" = true ]; then
1710
+ # No `--force`, and the same registry re-read the branch sweep documents:
1711
+ # a non-zero exit is no proof the removal had no effect, so the reason
1712
+ # names what the REGISTRY answered and claims nothing about what is left
1713
+ # on disk.
1714
+ if ! err=$(git worktree remove "$wt" 2>&1); then
1715
+ wt_reg_state "$wt"
1716
+ # `$wt` interpolated, unlike the branch sweep's byte-identical twin: there
1717
+ # `keep "$b"` names the subject, here the branch field is `null` and
1718
+ # git's own message for a locked worktree carries no path, so two
1719
+ # refusals in one run were byte-identical and an operator could not tell
1720
+ # which worktree was kept (measured, PR #985 review, two locked
1721
+ # worktrees).
1722
+ keep "" "worktree $wt remove refused ($state): $(printf '%s' "$err" | tr '\n' ' ')"
1723
+ continue
1724
+ fi
1725
+ # A line of its own, unlike the branch sweep's silent success: there is no
1726
+ # `REAPED <branch>` here to stand in for it, and a removal nothing prints
1727
+ # is the silence this ticket exists to end.
1728
+ printf ' REMOVED worktree %s\n' "$wt" >&2
1729
+ else
1730
+ printf ' would remove worktree %s\n' "$wt" >&2
1731
+ fi
1732
+ removed="${removed}$(jfield "$wt"),"
1733
+ done <<EOF
1734
+ $detached
1735
+ EOF
1736
+ fi
1737
+
1738
+ # Payload first, prune after (#265): `git worktree prune` used to be the last
1739
+ # command of the guard below — an AND-OR list then — so under `set -eu` ITS
1740
+ # OWN failure, not just a false `[ apply = true ]`, reached -e and aborted the
1741
+ # script before this printf ever ran, after the branches above were already
1742
+ # deleted. The caller lost the only record of what happened. Printing first
1743
+ # means that record survives regardless of what the prune does.
1744
+ printf '{"applied":%s,"reaped":[%s],"worktreesRemoved":[%s],"kept":[%s],"warnings":[%s]}\n' \
1745
+ "$apply" "${reaped%,}" "${removed%,}" "${kept%,}" "${warnings%,}"
1746
+
1747
+ # An `if`, not `[ ... ] && { ... }`: with the printf moved above it this guard
1748
+ # is the script's LAST command, and an AND-OR list whose test is false has
1749
+ # status 1 — which would become the script's own exit status and regress the
1750
+ # default dry run from 0 to a bare, verdictless 1, the very failure this fix
1751
+ # exists to remove. An `if` with no `else` exits 0 when its condition is false.
1752
+ # The prune's own failure reaches `die`, never -e, so it refuses loudly on 2
1753
+ # like every other failure this script can name.
1754
+ #
1755
+ # Captured, and quoted into the refusal the way `cherry probe failed` and
1756
+ # `worktree remove refused` above already are: bare, this printed a step name
1757
+ # and dropped git's stdout and stderr on the floor, so the operator read
1758
+ # `git worktree prune failed` and nothing about what git said (the class #578
1759
+ # catalogues at this script's other sites). Folded to one line by the same
1760
+ # `tr '\n' ' '` every reason here uses, so one failure stays one line. A
1761
+ # non-zero exit from this command now means the housekeeping genuinely failed:
1762
+ # the run standing in a worktree it was about to remove is refused above,
1763
+ # before any removal, rather than diagnosed here afterwards. #992
1764
+ if [ "$apply" = true ]; then
1765
+ if ! prune_err=$(git worktree prune 2>&1); then
1766
+ die "git worktree prune failed: $(printf '%s' "$prune_err" | tr '\n' ' ')"
1767
+ fi
1768
+ fi