@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,1716 @@
1
+ #!/bin/sh
2
+ # Release a claim that was never dispatched: drop the in-progress label, remove
3
+ # the worktree, delete the branch — but only when the claim provably carries no
4
+ # work. The inverse of claim-ticket.sh.
5
+ #
6
+ # Dry-run by default; --apply mutates the tracker and the filesystem.
7
+ #
8
+ # reap.sh will not do this: no merge happened, so no remote branch was ever
9
+ # deleted, so the branch is not [gone] and reap's for-each-ref filter never
10
+ # selects it. (Having no unique commits is not a second reason — in reap that is
11
+ # what AUTHORIZES the delete.) Nothing else fires either, so the three artefacts
12
+ # survive the run and phase 0's in-flight probe reads the ticket as taken — the
13
+ # same silent queue shrink the reaping section names for merged tickets.
14
+ #
15
+ # Every precondition is recomputed inside THIS invocation rather than trusted
16
+ # from an earlier tool call, for the reason reap.sh gives: the dangerous
17
+ # direction is a worktree that gained work after it was checked. Two of them are
18
+ # recomputed a second time at the moment of the delete, which is why both
19
+ # deletes run before the label is dropped rather than after.
20
+ #
21
+ # The dirty check's second opinion is git's own — that is what `worktree remove`
22
+ # without --force is for. It covers the live-directory case ONLY: `worktree
23
+ # remove` gates its own clean check on the same stat this script does, so
24
+ # wherever the path cannot be stat'ed git reaches the same conclusion rather
25
+ # than an independent one, and the guard at the dirty check below is left as
26
+ # sole arbiter — which is why it establishes absence instead of inferring it.
27
+ #
28
+ # The commit check's is this script's own: the compare-and-swap delete refuses
29
+ # only a ref that moved, so the `ahead` count is re-run against $base right
30
+ # before it. Why not `-d`, and what that recount does and does not cover, is
31
+ # argued once at the delete site below — don't restate it here.
32
+ set -eu
33
+
34
+ # Byte semantics for the `awk`, `grep`, `sed` and `tr` below — all four really
35
+ # are here, unlike in the siblings this header was copied to. `awk` and `grep`
36
+ # parse `git worktree list --porcelain` (worktree paths and branch names),
37
+ # `git cherry`'s output, the dirty-file list and `gh`'s labels; `tr` flattens
38
+ # git's own error text into a diagnostic; and `jstr`'s `sed | tr` scrubs
39
+ # whatever string is being JSON-encoded, `$wt` included. Under a UTF-8 locale
40
+ # BSD `tr` and `sed` exit 1 on a byte that is not valid UTF-8 — `sed` emitting
41
+ # nothing at all, measured — and `grep` silently drops the line holding it.
42
+ # Such a byte reaches us from a fetched tree even where the local filesystem
43
+ # refuses to hold the name, and inside `$(...)` a `tr` failure empties the cause
44
+ # out of the diagnostic without a trace. #582 measured the cost of leaving this
45
+ # ambient in no-undo-audit.sh: a truncated list reported as a clean, confident
46
+ # answer.
47
+ #
48
+ # Safe as a global: nothing in this script sorts, folds case, or holds a POSIX
49
+ # class. It does use ONE collation range — `*[!0-9]*`, the issue-number guard
50
+ # below — and a range IS locale-sensitive by spec, its members drawn from the
51
+ # collation sequence rather than the codepoint order. Measured inert here
52
+ # (#612): `0-9` matches the ASCII digits and nothing else under `C`,
53
+ # `en_US.UTF-8`, `de_DE.UTF-8` and `tr_TR.UTF-8` alike, with superscript `²`,
54
+ # Arabic-Indic digits and `½` excluded in all four. So collation and
55
+ # case-folding — the two things `LC_ALL=C` otherwise changes — have nothing
56
+ # here to act on. locale-pin-prose.test.mjs holds that inventory as a list and
57
+ # fails if the code drifts from this paragraph in either direction.
58
+ export LC_ALL=C
59
+
60
+ # Below the locale pin, not above it with `set -eu`: `unset` touches no
61
+ # byte-sensitive tool, but locale-pin-prose.test.mjs treats ANY line here that
62
+ # is not a comment, a blank, or `set -[eux]+` as work the pin must sit above,
63
+ # and refuses on principle rather than on this line's own behaviour.
64
+ #
65
+ # An ambient GIT_WORK_TREE outranks `-C`, not just plain discovery (measured,
66
+ # #427): with GIT_WORK_TREE alone pointing at an unrelated tree, `git -C "$wt"
67
+ # rev-parse --show-toplevel` answers about THAT tree, not `$wt` — the linkage
68
+ # guard below then blames a healthy `.git`, reporting it resolves to whatever
69
+ # the ambient var named. `git -C "$wt" status --porcelain` reads the same
70
+ # poisoned environment and would silently answer for the wrong tree too, just
71
+ # without a guard in front of it to say so. Every other git call in this
72
+ # script (no `-C` at all) is equally hostage to an ambient GIT_DIR retargeting
73
+ # it away from the repository the caller actually invoked this in. Unsetting
74
+ # both here, before any of them runs, is the one fix that reaches all of them
75
+ # at once — the same pattern `ledger.mjs` and `inflight.test.mjs` apply by hand
76
+ # per child process, under a comment making the same point: inherited git vars
77
+ # outrank cwd (and, here, outrank `-C` too).
78
+ #
79
+ # GIT_DIR alone does NOT reproduce the linkage guard's misdirection (measured):
80
+ # with no GIT_WORK_TREE, the work tree falls back to the discovery default and
81
+ # `-C "$wt"` still lands on `$wt`. That is a narrower claim than "GIT_DIR is
82
+ # harmless" — left ambient, it still retargets every OTHER git call in this
83
+ # script, the ones with no `-C` to even attempt insulating them.
84
+ #
85
+ # Both halves are pinned, one fixture each: GIT_WORK_TREE by the linkage-guard
86
+ # case, GIT_DIR by `an ambient GIT_DIR does not aim the release at another
87
+ # repository (#427)`. That second fixture measures the damage end-to-end
88
+ # through one of the `-C`-less calls: with only `unset GIT_WORK_TREE` here, the
89
+ # run reports `released: true` after deleting the claim's branch name in a
90
+ # DIFFERENT repository and leaving this repository's three artefacts intact.
91
+ # It pins the class named just above, not a line-by-line proof that every
92
+ # single `-C`-less call is retargeted.
93
+ #
94
+ # No fleet caller sets either var deliberately before invoking this script
95
+ # (checked: no assignment to GIT_DIR or GIT_WORK_TREE anywhere upstream of
96
+ # `release-ticket.sh` in this repo), so this closes the class with nothing
97
+ # left depending on the ambient value.
98
+ unset GIT_DIR GIT_WORK_TREE
99
+
100
+ NAME=release-ticket
101
+
102
+ # Assigned HERE, above `die`, and not next to `block` where the accumulator is
103
+ # otherwise used: `die`'s guard below reads `$blockers`, and `set -u` is
104
+ # satisfied by an INHERITED value just as well as by one this run computed. An
105
+ # ambient environment variable named `blockers` therefore took the guard true on
106
+ # every early die — before `$issue` is assigned at all — and the receipt printf
107
+ # then died on `issue: unbound variable`, losing the diagnostic the die exists
108
+ # to print. A plain assignment overrides whatever was inherited, so the guard
109
+ # once again means "this run accumulated something". The exit code that mistake
110
+ # produced is platform-asymmetric (bash-as-/bin/sh gives 1, dash gives 2), which
111
+ # is why the pin in the tests is on the prose and not on a number.
112
+ blockers=""
113
+
114
+ # A `die` firing after a `block` used to discard every accumulated blocker —
115
+ # exit 2, prose on stderr, and no JSON receipt at all, so a caller that already
116
+ # had real findings computed got none of them. The guard is on non-empty rather
117
+ # than on existence, which keeps every early die — before json.sh is sourced
118
+ # below, before anything is accumulated — byte-identical to today: no
119
+ # `$blockers` reference is even reached.
120
+ #
121
+ # Approach 2 (#387): print the same receipt shape the blocked checkpoint and
122
+ # `halt` already use, with `$1` appended to `$blockers` exactly as `block`
123
+ # would have recorded it — not a new schema, and not a second write. Approach 1
124
+ # (emit the receipt as soon as blockers goes non-empty, before whatever can
125
+ # die) was ruled out: it lets a run print a receipt and then keep going and
126
+ # fail anyway, which is a run with two writes or a receipt describing a state
127
+ # the run then left. `label` is `null` here as it is at that checkpoint — the
128
+ # label is read after every one of these dies can fire, so this receipt cannot
129
+ # claim to know it. `$blockers` already ends in a trailing comma (`block`'s own
130
+ # accumulator does that), so splicing the newly-escaped `$1` straight after it
131
+ # needs no separator of its own — which is done in the ARGUMENT, so this format
132
+ # string stays byte-identical to the blocked checkpoint's rather than growing a
133
+ # second blockers slot only this one caller uses.
134
+ #
135
+ # release-ticket.test.mjs's "block() then die() compose a receipt that still
136
+ # parses as JSON, blockers in order (#1080)" pins this by name: two `block()`
137
+ # calls, then a `die()` splice, composed for real rather than reasoned about
138
+ # by hand the way PR #983 did. Mutation-verified both directions — `block`
139
+ # dropping its comma, or appending two instead of one — reds that test.
140
+ #
141
+ # The `||` arm is the receipt's only voice. `|| die` is what `block` and `halt`
142
+ # use and is unavailable here — it would recurse — so a bare `&&` chain left BOTH
143
+ # its failures mute: a failed `jstr`, and a failed write. The second is the worse
144
+ # one and is not a silent degrade at all: with the chain as the last command
145
+ # before `fi`, a receipt printf that cannot write (closed fd, EIO, a full disk on
146
+ # a redirect) takes `set -e` and kills the function before its own stderr prose
147
+ # below, so the die reason vanishes and the script exits 1 — this script's
148
+ # `NOT released` verdict, fabricated out of a write error. Measured on /bin/sh
149
+ # (bash 3.2), /bin/dash and bash 5.3; zsh alone survived it. The arm ends the
150
+ # list so nothing is left to trip, and it names neither failure specifically,
151
+ # because `a && b || c` fires `c` for both and this file does not report a cause
152
+ # it did not measure.
153
+ die() {
154
+ if [ -n "${blockers:-}" ]; then
155
+ die_j=$(jstr "$1") &&
156
+ printf '{"issue":%s,"branch":"%s","branchRewritten":%s,"worktree":"%s","worktreeRewritten":%s,"label":null,"released":false,"applied":%s,"blockers":[%s]}\n' \
157
+ "$issue" "$branch_j" "$branch_rw" "$wt_j" "$wt_rw" "$apply" "${blockers}\"$die_j\"" ||
158
+ printf '%s: no JSON receipt for #%s — the escape or the write failed\n' "$NAME" "$issue" >&2
159
+ fi
160
+ printf '%s: %s\n' "$NAME" "$1" >&2
161
+ exit 2
162
+ }
163
+
164
+
165
+ # The escaping helpers (#119). json.sh's header holds the sourcing contract and
166
+ # the measurements behind it; only what is true of THIS script is repeated here.
167
+ # Below `export LC_ALL=C` deliberately: locale-pin-prose.test.mjs allows only
168
+ # comments, blanks, a shebang or a `set -` line above that pin, and `json_lib=`
169
+ # is none of them.
170
+ #
171
+ # Exit 1 from this script is a verdict too: `#<n> NOT released — nothing was
172
+ # touched`, emitted with the blocker list a precondition scan actually found. A
173
+ # library that merely went missing would hand the caller that answer for a
174
+ # ticket nothing ever refused, so `[ -r ]` has to fire before the `.` can kill
175
+ # the shell.
176
+ json_lib="$(dirname "$0")/json.sh"
177
+ [ -r "$json_lib" ] || die "cannot read $json_lib — refusing to act without the JSON escaping helpers"
178
+ # shellcheck source-path=SCRIPTDIR
179
+ # shellcheck source=json.sh
180
+ . "$json_lib" || die "$json_lib failed to load"
181
+
182
+ # The worktree readers (#551, #725). worktree.sh's header holds the sourcing
183
+ # contract and the measurements behind it, and json.sh's holds the `[ -r ]`
184
+ # reasoning both guards share. This script reads exit 1 as its own blocked
185
+ # verdict, which is the whole reason that guard is not `|| die` alone.
186
+ wt_lib="$(dirname "$0")/worktree.sh"
187
+ [ -r "$wt_lib" ] || die "cannot read $wt_lib — refusing to act without the worktree readers"
188
+ # shellcheck source-path=SCRIPTDIR
189
+ # shellcheck source=worktree.sh
190
+ . "$wt_lib" || die "$wt_lib failed to load"
191
+
192
+ # The bounded, prompt-suppressed git transport (#92, #346, #347). The
193
+ # pushed-branch lookup below is unattended: with no bound it can prompt for a
194
+ # credential or a host key, or stall on a transport that connects and then goes
195
+ # quiet, and either holds a fleet slot until something outside kills it.
196
+ # net.sh's header holds the reasoning and the measurements. Sourced below
197
+ # json.sh so a lone copy of this script still blames json.sh, the name its
198
+ # missing-library test pins.
199
+ net_lib="$(dirname "$0")/net.sh"
200
+ [ -r "$net_lib" ] || die "cannot read $net_lib — refusing to act without the bounded git transport"
201
+ # shellcheck source-path=SCRIPTDIR
202
+ # shellcheck source=net.sh
203
+ . "$net_lib" || die "$net_lib failed to load"
204
+
205
+ [ $# -ge 3 ] && [ $# -le 4 ] || die "usage: release-ticket.sh <issue> <slug> <type> [--apply]"
206
+ issue=$1
207
+ slug=$2
208
+ type=$3
209
+ # Exact match, and nothing else tolerated in the slot: `--aply` silently became a
210
+ # dry run that still reported "released":true, so a caller keying on that field
211
+ # marked the claim released while every artefact survived — the silent queue
212
+ # shrink this script exists to undo, produced by a typo.
213
+ case "${4:-}" in
214
+ ''|--apply) ;;
215
+ *) die "unknown argument '$4' — the only option is --apply";;
216
+ esac
217
+ apply=false
218
+ [ "${4:-}" = "--apply" ] && apply=true
219
+
220
+ case "$issue" in ''|*[!0-9]*|0?*) die "issue must be a number, got '$issue'";; esac
221
+
222
+ branch="$type/$issue-$slug"
223
+ base=${BASE_REF:-origin/main}
224
+
225
+ # The fleet harness is exactly the caller that sets BASE_REF, and pointing it at
226
+ # the claim's own branch makes both commit guards vacuous — ahead 0 and cherry
227
+ # empty on a branch that still carries unpushed work. Only a remote-tracking ref
228
+ # can answer "is this upstream", so only one is accepted.
229
+ case "$base" in
230
+ origin/*|refs/remotes/*) ;;
231
+ *) die "BASE_REF must be a remote-tracking ref, got '$base'";;
232
+ esac
233
+ # The accept-list alone does not deliver that: `origin/$branch` IS a
234
+ # remote-tracking ref and passes it, while making both guards vacuous in exactly
235
+ # the way described above — ahead 0 and cherry empty against the branch's own
236
+ # upstream, whatever it carries. The compare-and-swap delete then removes a
237
+ # commit that exists nowhere else at exit 0. Name-based, not a rev-parse
238
+ # comparison: a pristine claim's tip equals origin/main's — the normal case.
239
+ case "$base" in
240
+ */"$branch") die "BASE_REF must not name the claim's own branch, got '$base'";;
241
+ esac
242
+
243
+ # Neither guard above can see the third route to a vacuous $base, because the
244
+ # hijack is spelled as the legitimate DEFAULT. `origin/main` is a SHORTHAND, and
245
+ # git resolves a shorthand through its own disambiguation order (gitrevisions:
246
+ # refs/<name>, refs/tags/<name>, refs/heads/<name>, refs/remotes/<name>, …), in
247
+ # which refs/remotes/origin/main comes LAST. So a local TAG named `origin/main`
248
+ # — `git tag origin/main refs/heads/$branch` — outranks the remote-tracking ref
249
+ # and every measurement against $base then answers about the claim's own tip:
250
+ # ahead 0, cherry empty, and the delete-time recount 0 as well. All three guards
251
+ # vacuous at once, the compare-and-swap delete refuses nothing, and the branch
252
+ # and its unpushed commit go at exit 0, "released":true, no blockers.
253
+ # Measured on a real bare-origin fixture; `git rev-parse origin/main` prints the
254
+ # tag's OID under git's own `refname 'origin/main' is ambiguous` warning, which
255
+ # nothing here reads. Pre-#760 `-d` refused this ("not fully merged") — the
256
+ # guards were already vacuous under it, so `-d` was the sole backstop, and this
257
+ # is the one class its removal reopened.
258
+ #
259
+ # The fix is to stop MEASURING against a shorthand: the accept-list already
260
+ # establishes $base names a remote-tracking ref, so qualify it to the full
261
+ # refs/remotes/ path, where there is nothing left to disambiguate. $base itself
262
+ # is unchanged and stays in every user-facing message — `12 commit(s) ahead of
263
+ # origin/main` is what an operator wants to read, not the qualified spelling.
264
+ case "$base" in
265
+ refs/remotes/*) base_rev=$base;;
266
+ *) base_rev="refs/remotes/$base";;
267
+ esac
268
+
269
+ git rev-parse --git-dir >/dev/null 2>&1 || die "not inside a git repository"
270
+ git rev-parse --verify "$base_rev" >/dev/null || die "$base does not resolve"
271
+
272
+ # Locate the worktree by the branch it has checked out, the way reap.sh does —
273
+ # not by claim-ticket.sh's ".worktrees/$issue-$slug", which is relative to the
274
+ # caller's cwd.
275
+ #
276
+ # Only a LINKED worktree is ours: `worktree list --porcelain` lists the main one
277
+ # first, and a checkout that happens to sit on this branch would otherwise be
278
+ # selected for removal. git refuses to remove it — but not before the label was
279
+ # dropped, which is the half-release this script exists to prevent. Measured in
280
+ # a fresh clone, where the branch really is the main checkout's HEAD.
281
+ #
282
+ # `worktree list --porcelain` is reading `<git-common-dir>/worktrees`, the
283
+ # admin directory git itself writes one subdir per linked worktree into. When
284
+ # that directory — or any file git needs inside one of its entries — cannot be
285
+ # read, git does not error: it silently drops the affected entries and still
286
+ # exits 0 (verified, git 2.50.1). `wt` and `stray` below would then read as "no
287
+ # worktree of ours" for a claim that has one — the same absent-vs-unreadable
288
+ # confusion `gone` keeps this script out of elsewhere, applied by hand here
289
+ # because the question is about a directory git reads, not about a path this
290
+ # script stats. So establish the listing is COMPLETE before trusting an absence
291
+ # it reports — not by guarding its exit status, which stays 0 throughout.
292
+ #
293
+ # Do not try to predict which reads git needs: stat'ing each entry directory is
294
+ # one level too shallow, because naming an entry needs read+execute on the
295
+ # PARENT only. `chmod 000` on the `gitdir` FILE inside an entry passes every
296
+ # permission test this script could make on the entry itself and still drops
297
+ # the worktree from the listing — measured, and that is #84 unclosed. Count
298
+ # instead: one registry entry on disk per linked worktree, against what git
299
+ # reported. A mismatch is a silent drop, whichever file inside was unreadable.
300
+ #
301
+ # Absent entirely is fine and answers nothing here: a repo where a worktree
302
+ # was removed and pruned (or never had one) has no `worktrees` dir at all, and
303
+ # that emptiness is real, not a permission problem — zero entries against the
304
+ # main worktree alone is a match, so the release goes through.
305
+ common=$(git rev-parse --path-format=absolute --git-common-dir) ||
306
+ die "cannot resolve the git common directory"
307
+ wtroot="$common/worktrees"
308
+
309
+ # A function, not inline, because the count is taken twice: once here, and
310
+ # once more at the recount below if the cross-check disagrees with git's own
311
+ # listing (#694). The body is unchanged from what stood here as plain
312
+ # top-level code before this ticket — mirrors inflight.sh's own
313
+ # count_registry, which the same recount need already lives behind there,
314
+ # adapted for the difference the ticket turns on: that copy returns a status
315
+ # into an accumulate-and-continue probe, this one dies, so the loop itself
316
+ # still just dies on an unreadable registry rather than returning past it.
317
+ count_registry() {
318
+ registered=0
319
+ [ -e "$wtroot" ] || return 0
320
+ # The parent needs its own check even so, and this is not redundant with the
321
+ # count: unreadable, the glob below expands to nothing, and zero-on-disk would
322
+ # AGREE with the empty listing git returns for the same reason.
323
+ [ -r "$wtroot" ] && [ -x "$wtroot" ] ||
324
+ die "worktree registry $wtroot could not be read — whether #$issue has a worktree is unknown"
325
+ # A registry entry is a directory; anything else in here is not git's and must
326
+ # not be counted as a worktree git failed to report.
327
+ for entry in "$wtroot"/*; do
328
+ [ -d "$entry" ] || continue
329
+ # Skip only an EMPTY directory. That is an operator's stray `mkdir`, which
330
+ # git ignores — and counting one refuses EVERY release of every ticket in
331
+ # the repo, forever, over something git is right to ignore (measured, git
332
+ # 2.50.1: git lists 2 worktrees where a bare `-d` count said 2 registered
333
+ # against 1 linked). A stray FILE was already skipped by the `-d` above; a
334
+ # stray directory was not, which is why the file case shipped green.
335
+ #
336
+ # Emptiness, NOT the absence of a `gitdir` file, and the difference is a
337
+ # wrong "free": git drops an entry whose `gitdir` was deleted, so keying the
338
+ # skip on that file lets the entry through as "not git's", the count agrees,
339
+ # no refusal fires, and the release proceeds while the checkout may still be
340
+ # on disk (measured: listed 1 → linked 0, and a gitdir-keyed count returns 0
341
+ # to match). A corrupt entry still holds git's own files — commondir, HEAD,
342
+ # index, logs, refs — so emptiness separates it from a stray where the
343
+ # missing `gitdir` does not. This is #384's own second commit, and #395
344
+ # exists partly to keep this copy from inheriting the discriminator it
345
+ # replaced.
346
+ #
347
+ # `ls`'s STATUS, not just its output, and that is the whole point: an entry
348
+ # we could not LIST is not an empty one, and `2>/dev/null` hides the
349
+ # difference. A stray `mkdir` lists empty at rc 0; an entry chmod'd 000
350
+ # (unsearchable) OR 0111 (searchable, so an `-x` test passes it, but not
351
+ # readable) fails EACCES and prints nothing just the same. Reading only the
352
+ # output skips that entry as "not git's" — and git drops it too, so the
353
+ # counts AGREE, no refusal fires, and the claim is freed with the member's
354
+ # uncommitted work still on disk (measured: exit 0, `released:true`,
355
+ # `blockers:[]`, branch deleted, in-progress label dropped, checkout
356
+ # standing). Could not read it, so we cannot tell → count it and let the
357
+ # mismatch below fire.
358
+ if contents=$(ls -A "$entry" 2>/dev/null) && [ -z "$contents" ]; then continue; fi
359
+ registered=$((registered + 1))
360
+ done
361
+ return 0
362
+ }
363
+ count_registry
364
+
365
+ # The path is the whole rest of the line, never $2: `worktree list --porcelain`
366
+ # prints it raw, so any checkout living under a directory with a space in it —
367
+ # ordinary on macOS — would otherwise be truncated at the first one.
368
+ #
369
+ # A newline in that path was the same truncation one byte further out: the plain
370
+ # porcelain ends every attribute with one, so the record split and every
371
+ # `substr($0,10)` below stopped at the newline. `wt_listing` reads `-z` and
372
+ # swaps the separators, so a record ends where git says it ends. #551
373
+ #
374
+ # `|| die`, where this was a bare assignment: left bare the read died on `set -e`
375
+ # under git's own diagnostic, with no line carrying the `release-ticket:` prefix
376
+ # a caller greps stderr for — the very reason every lookup OVER this listing is
377
+ # already guarded that way.
378
+ #
379
+ # A function, not inline, because the recount below (#694) needs this whole
380
+ # pair — git's own read and the count derived from it — re-taken TOGETHER, not
381
+ # just re-assigned in isolation. `linked` and `wt_list`/`wt_err` are this
382
+ # function's OUTPUT, exactly as `registered` is `count_registry`'s.
383
+ count_linked() {
384
+ wt_listing || die "could not read the worktree list for #$issue: $wt_err"
385
+ # The main worktree is always listed first and has no registry entry of its own,
386
+ # hence the -1.
387
+ #
388
+ # awk, not `grep -c … || true`. `grep -c` exits 1 on zero matches — legitimate,
389
+ # and `set -e` would read it as fatal — so a `|| true` has to absorb it, and
390
+ # that same `|| true` absorbs a grep that could not RUN AT ALL just as happily.
391
+ # The count is then the empty string, `$((listed - 1))` is -1 (measured), and
392
+ # the mismatch report below blames `git worktree list` for a count no listing
393
+ # can produce — sending the operator after git when the fault was a fork
394
+ # failure. awk needs no such case separated out: the program contains no `exit`,
395
+ # so it returns 0 whether or not anything matched, and every non-zero status is
396
+ # a real failure. This script already removed exactly this shape elsewhere.
397
+ #
398
+ # What this count does NOT cover, stated because it reads as though it might: a
399
+ # path with a newline in it never moved this number. The orphaned continuation
400
+ # line the plain porcelain produced did not begin `worktree `, so `listed - 1`
401
+ # still equalled `registered` and the cross-check AGREED with a read that had
402
+ # truncated the path. Re-measured on a real linked worktree added at
403
+ # `…/wt/fix-33<LF>slug`, git 2.50.1 (Apple Git-155):
404
+ #
405
+ # git worktree add -b fix/33-slug "../wt/$(printf 'fix-33\nslug')"
406
+ # git worktree list --porcelain | awk '/^worktree /{n++} END{print n+0}'
407
+ # ls .git/worktrees | wc -l
408
+ #
409
+ # `listed - 1` equals `registered` while the same listing's `substr($0,10)` hands
410
+ # back `…/wt/fix-33`, a path `[ -d ]` says is not there. The blindness is the
411
+ # point, not the arithmetic: the orphan line adds no `worktree ` line, so no
412
+ # count over this listing can see the truncation. It is a count of records against
413
+ # registry entries and catches an entry git DROPPED; the path inside a record it
414
+ # does keep is `nl_path`'s to refuse, below. Under `-z` the count is now right by
415
+ # construction — one `worktree ` line per record, whatever the path holds. #551
416
+ listed=$(printf '%s\n' "$wt_list" | LC_ALL=C awk '/^worktree /{c++} END{print c+0}') ||
417
+ die "could not count the worktrees git listed for #$issue"
418
+ # The `|| die` above closes only the route where awk could not RUN. An empty but
419
+ # SUCCESSFUL listing reaches the same -1: awk exits 0 printing `0`, the guard
420
+ # cannot fire, and the mismatch report below blames `git worktree list` for the
421
+ # very count the guard above exists to keep out of an operator's face. One
422
+ # comparison closes it for every branch below at once. `-ge 1`, not `-gt 1`:
423
+ # `listed=1` is the main checkout alone, `linked=0`, the ordinary repo with no
424
+ # linked worktree at all — a guard that refused that would refuse most releases
425
+ # in this repo. Real `git worktree list --porcelain` always prints the main
426
+ # worktree, so reaching this needs a broken or shimmed git; the refusal
427
+ # direction was already right, only the number was nonsense. #699
428
+ [ "$listed" -ge 1 ] ||
429
+ die "git listed no worktrees at all for #$issue — not even the main checkout, so the listing cannot be trusted"
430
+ linked=$((listed - 1))
431
+ }
432
+ count_linked
433
+ # Name the direction actually observed. The two disagreements have opposite
434
+ # causes and send the reader to opposite places, so one message cannot serve
435
+ # both: FEWER listed than registered is git silently dropping an entry it could
436
+ # not read, which is the fault this whole check exists to catch. MORE listed
437
+ # than registered is the reverse — the on-disk count is the stale read, a
438
+ # sibling agent's `git worktree add` having landed between the two, which in a
439
+ # parallel fleet is routine rather than exotic. Calling that "the listing is
440
+ # incomplete" sends an operator hunting a permissions fault that is not there.
441
+ # Recount before refusing (#694). The registry scan above and git's listing
442
+ # just taken are two reads at two different instants, not one atomic read, and
443
+ # a sibling agent's `git worktree add` or `remove` landing in the gap makes the
444
+ # two counts disagree with nothing actually wrong — measured against this
445
+ # script directly: 3/100 dry-run releases aborted on this cross-check under a
446
+ # throttled churner, 48-66/80 unthrottled, all with zero real faults among them.
447
+ #
448
+ # inflight.sh already recounts here (#694) into its own accumulate-and-continue
449
+ # probe; this script's whole contract is `die` on any unmet precondition
450
+ # instead, so the port keeps that shape rather than inheriting the accumulator.
451
+ # Both copies recount BOTH `registered` and `linked` — this one from #1408,
452
+ # inflight.sh's from #1421, which closed the same window in that copy.
453
+ # Re-taking `registered` alone leaves `linked` pinned to the FIRST `wt_listing`
454
+ # call: a second sibling mutation landing after that call returns but before
455
+ # the lone recount re-scans the registry inflates `registered` without touching
456
+ # `linked`, which can flip which branch fires below and name the wrong cause —
457
+ # reporting "the listing is incomplete" (implying a fault) for what is,
458
+ # underneath, the same benign race the elif below already names correctly.
459
+ # Verified against this script directly with a shim landing a second mutation
460
+ # in exactly that window.
461
+ #
462
+ # A mutation landing between the FIRST count and git's listing is already
463
+ # reflected in that listing, so the second count agrees with it — that is the
464
+ # invariant the ORIGINAL pair above relies on. Recounting `registered` and
465
+ # `linked` together, in the same order (`count_registry` first, `count_linked`
466
+ # second, mirroring lines 364-434 above), gives the RECOUNT pair that same
467
+ # invariant: escaping it needs a mutation inside the narrower window these two
468
+ # calls open between themselves, not the whole span back to the first
469
+ # `wt_listing` (measured on inflight.sh's copy while it was still
470
+ # registered-only, the same shape of window: 1.99% -> 0.00% at 2 mutations/s,
471
+ # 56.6% -> 1.29% saturated). A genuinely dropped entry is a standing state, not
472
+ # a moment, so it survives every recount below and still refuses.
473
+ #
474
+ # The order is kept the same as the original pair for THIS argument's sake —
475
+ # it lets the invariant above carry over instead of being re-derived for a
476
+ # different order — not because a different order would be wrong. Verified
477
+ # directly (#1424): swapping the recount to `count_linked` first then
478
+ # `count_registry` still passes all four tests below (the two single-mutation
479
+ # absorptions and the two #1408 regression cases) unchanged. Both functions
480
+ # only read — neither writes anything the other observes — so whichever runs
481
+ # first merely trades which of the two symmetric windows (before the first
482
+ # call, between the two, after the second) a same-shaped mutation would need
483
+ # to land in; it does not change whether the pair converges. Nothing below
484
+ # depends on this order for correctness; it is kept fixed only so this
485
+ # comment's own reasoning stays about one order instead of two.
486
+ #
487
+ # The unreadable-registry case above is unaffected: `count_registry`'s own
488
+ # `[ -r ] && [ -x ]` guard on $wtroot dies the same way on every call, before
489
+ # any recount is ever reached. The cannot-read-inside case is NOT unaffected
490
+ # the same way — an entry inside $wtroot that `ls -A` cannot read is counted as
491
+ # registered rather than dying (above), so a stale one survives every recount
492
+ # too, but what fires on it is the mismatch below, not `count_registry` itself:
493
+ # a different guard, a different exit code, under "the listing is incomplete" —
494
+ # a cause that is not actually what happened.
495
+ #
496
+ # The recount pair above is itself two reads at two different instants, not
497
+ # one atomic read: a THIRD sibling mutation landing between the recount's own
498
+ # `count_registry` and `count_linked` calls escapes the single-recount
499
+ # invariant the same way a second mutation once escaped the original pair,
500
+ # and mislabels the same benign race under one of the two `die`s below (#1424,
501
+ # deferred from #1408's own review). Verified directly with a shim landing a
502
+ # first mutation ahead of the initial listing and a second squarely inside the
503
+ # recount's own gap: the wrong-direction message reproduced against this
504
+ # script before the loop below existed.
505
+ #
506
+ # Closing that for good needs a single atomic snapshot of the registry and
507
+ # git's listing together, and this repo has no primitive for one: git exposes
508
+ # no combined read, and building one would mean a lock held not just here but
509
+ # in every other script that mutates the registry (claim-ticket.sh, reap.sh,
510
+ # and any other `git worktree add`/`remove` caller in the fleet) — a
511
+ # repo-wide locking protocol this script has no authority to impose on
512
+ # siblings it does not control, for a window that already needs three
513
+ # precisely-timed mutations landing in gaps with no subprocess call in them at
514
+ # all. Disproportionate, so not attempted.
515
+ #
516
+ # What IS cheap: recounting more than once. Each additional pass demands one
517
+ # MORE precisely-timed sibling mutation to defeat, compounding against the
518
+ # same mutation being both willing and able to land in an ever-later gap
519
+ # within this one invocation — while a genuine corruption is a standing
520
+ # state, not a moment, and still survives every pass and still refuses once
521
+ # the loop below runs out. `recount_tries` bounds it at one more attempt than
522
+ # #1408 already took (closing the specific #1424 residual without turning
523
+ # this into the open-ended chase the issue itself calls out) rather than a
524
+ # measured constant — sustained real churn settling in two extra reads is not
525
+ # something this fixture can measure a percentage for, unlike the numbers
526
+ # above.
527
+ recount_tries=2
528
+ while [ "$linked" -ne "$registered" ] && [ "$recount_tries" -gt 0 ]; do
529
+ count_registry
530
+ count_linked
531
+ recount_tries=$((recount_tries - 1))
532
+ done
533
+ if [ "$linked" -lt "$registered" ]; then
534
+ die "git listed $linked worktrees for $registered registry entries in $wtroot — the listing is incomplete, so no absence it reports can be trusted"
535
+ elif [ "$linked" -gt "$registered" ]; then
536
+ die "git listed $linked worktrees but only $registered registry entries were counted in $wtroot — the registry read missed entries git can see, so no absence it reports can be trusted"
537
+ fi
538
+
539
+ # Every lookup ASSIGNED from the listing is guarded, for the reason the worktree
540
+ # counter above is: left bare, an awk that could not answer ends the run on its
541
+ # own diagnostic, with no line carrying the `release-ticket:` prefix a caller
542
+ # greps stderr for. The lookups OVER it are guarded too, but never this way —
543
+ # `locked` and `unresolved_head` below read the same `$wt_list` through awk and
544
+ # answer THROUGH its exit status, where telling "could not run" from "no match"
545
+ # needs more than a `|| die`. Each captures that status itself and refuses above
546
+ # the range its answer occupies; `locked` carries why (#454).
547
+ #
548
+ # Neither #243 trigger is what makes these guards worth having, and both are
549
+ # narrower than they look. A newline in <slug> reaches the branch lookup as a
550
+ # `-v` value, where BSD awk refuses it outright but mawk and gawk accept it
551
+ # (measured), so on those the run simply walks past. An undecodable byte would
552
+ # arrive as record data instead — the trigger no policy on <slug> could also
553
+ # cover — but it is held shut here by one line, `export LC_ALL=C` above: under
554
+ # a UTF-8 locale these very programs exit 2 on such a byte, under `C` they read
555
+ # it as data (both measured, #582). What the guards actually answer for is an
556
+ # awk that could not run AT ALL, which no locale or implementation rules out.
557
+ #
558
+ # Guarding these ASSIGNMENTS cannot turn an empty answer into a refusal: none of
559
+ # them has a non-zero `exit`, so matching nothing is status 0 (measured), and an
560
+ # absent worktree stays the answer the checks below expect. The predicates are
561
+ # the opposite case — their `exit` is how they answer at all — which is why the
562
+ # same sentence cannot be written about them and why their guard is not this one.
563
+ wt=$(printf '%s\n' "$wt_list" |
564
+ awk -v b="refs/heads/$branch" '/^worktree /{w=substr($0,10);n++} /^branch /&&$2==b&&n>1{print w}') ||
565
+ die "could not read the worktree git listed for #$issue"
566
+ main_branch=$(printf '%s\n' "$wt_list" | awk '/^worktree /{n++} n==1&&/^branch /{print $2; exit}') ||
567
+ die "could not read the main checkout's branch from git's listing for #$issue"
568
+ # The main checkout's path, and the anchor the orphan probe below reconstructs a
569
+ # claim's directory from. Off git's own listing rather than $PWD: this script is
570
+ # routinely run from inside a member's worktree, where a cwd-relative
571
+ # ".worktrees/..." names nothing.
572
+ main_wt=$(printf '%s\n' "$wt_list" | awk '/^worktree /{print substr($0,10); exit}') ||
573
+ die "could not read the main checkout's path from git's listing for #$issue"
574
+
575
+ # claim-ticket.sh creates the worktree on this branch, but it does not stay
576
+ # there: an interrupted rebase leaves it detached, and a member can switch it.
577
+ # The branch lookup above then finds nothing, which reads as "no worktree of
578
+ # ours" — so the dirty check is skipped entirely and the script reports a
579
+ # release that left the worktree standing, with the member's uncommitted work in
580
+ # it. Next run the in-flight probe still sees it and the ticket still reads as
581
+ # taken: the exact failure this script exists to fix, reported as success.
582
+ #
583
+ # The directory name is the one part of the claim that does not move, so match
584
+ # on it — by exact suffix, not a pattern, since <slug> is caller-supplied.
585
+ #
586
+ # Except that it DOES move: `git worktree move` renames the directory, and the
587
+ # suffix stops matching (measured, git 2.50.1). On its own that is a miss, not a
588
+ # fault — a moved worktree still on this branch is found by `wt` above. The two
589
+ # together are the fault: a claim whose HEAD git cannot resolve loses its
590
+ # `branch` line, so `wt` is empty, and if it was ALSO moved then `stray` is empty
591
+ # too — both blindnesses from the same claim, and the arms below never run. The
592
+ # script then released it: branch deleted, label dropped, `released:true` at rc
593
+ # 0, over a directory holding staged work and no longer reachable as a
594
+ # repository (measured, on the fixture this file's suite now carries).
595
+ #
596
+ # The registry ENTRY is what survives a move, and it is the only handle left on
597
+ # such a claim — but an entry is a NAME, and a name cannot prove ownership, so
598
+ # it answers only as a corroborated fallback, below the predicates that
599
+ # corroboration needs — `entry_stray`, after `unresolved_head`. The suffix key
600
+ # here is unchanged, and answers first.
601
+ #
602
+ # Through the ENVIRON, not `-v`, for the reason `locked` gives: `-v` processes
603
+ # escape sequences in its value, so a needle holding a literal backslash arrives
604
+ # mangled and can then never equal what the porcelain printed byte-for-byte.
605
+ # Unlike `locked`'s path, this needle is built from argv rather than read off
606
+ # disk — but argv is not exempt from a backslash either, and awk itself still
607
+ # exits 0 having simply matched nothing: the permissive answer, in a probe whose
608
+ # whole job is to catch a claim whose branch moved (#799). ENVIRON does no such
609
+ # processing.
610
+ stray=$(printf '%s\n' "$wt_list" |
611
+ D="/$issue-$slug" awk '/^worktree /{n++; p=substr($0,10); d=ENVIRON["D"]
612
+ if (n>1 && substr(p, length(p)-length(d)+1) == d) {print p; exit}}') ||
613
+ die "could not scan git's listing for a stray worktree for #$issue"
614
+
615
+ has_branch=false
616
+ git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null && has_branch=true
617
+
618
+ # Every string that reaches the JSON goes through `jstr` from json.sh. <slug>
619
+ # and <type> are caller-supplied and git's own stderr is quoted back verbatim,
620
+ # so without it a single `"` or backslash anywhere emits a payload the caller
621
+ # cannot parse — while the delete has already happened and the exit code still
622
+ # says success. The rule list and its ordering live in json.sh, once, rather
623
+ # than here and in inflight.sh and in no-undo-audit.sh (#119).
624
+ # A `$(...)` in printf's ARGUMENT list sits outside the `|| die` on the printf
625
+ # itself: a substitution that fails contributes an EMPTY argument and printf
626
+ # still exits 0 — and an unquoted `%s` slot then emits `"...Rewritten":,`,
627
+ # malformed JSON at exit 0, which is the failure the receipt exists to rule
628
+ # out. Assigned first, each one is a simple command whose status the `&&` chain
629
+ # can read and this `|| die` can act on.
630
+ # `branch` is settled from argv at the top and `wt` from the worktree listing
631
+ # above, both before any receipt below can print, so the four fields are escaped
632
+ # once here.
633
+ branch_j=$(jstr "$branch") && branch_rw=$(jrewritten "$branch") \
634
+ && wt_j=$(jstr "$wt") && wt_rw=$(jrewritten "$wt") \
635
+ || die "could not escape the receipt fields for #$issue"
636
+
637
+ # A mutation refused mid-release. `die` printed prose and
638
+ # exited before every printf, so a caller parsing this script's stdout got
639
+ # nothing at all out of the one case where it most needs to know what happened.
640
+ # Enumerate what landed, name the compensating action, still emit the receipt.
641
+ #
642
+ # WHAT LANDED decides the headline, never the call site: the first mutation
643
+ # attempted — the worktree removal when there is one, `git update-ref -d` when
644
+ # registration is already cleared — refuses with nothing landed, and announcing
645
+ # a partial release over that overstates exactly the state this script exists to
646
+ # report precisely. A partial release is a refusal that followed a successful
647
+ # mutation. Distinct again from the blocked message that reports refused
648
+ # preconditions, which means nothing was ATTEMPTED.
649
+ #
650
+ # The two are NOT a matched pair, and one evenly-shaped detail line asserted
651
+ # that they were. `git update-ref -d` updates a ref, which lands or does not, so a
652
+ # boolean call log answers for it completely. `git worktree remove` has TWO
653
+ # effects and drops them in order: it deletes the registration before the
654
+ # directory and does not put the registration back when the directory delete
655
+ # fails (measured, git 2.50.1). Its exit code therefore answers for neither, and
656
+ # `nothing landed` over a cleared registration was a positive assertion that was
657
+ # false. So `wt_outcome` carries a measured release outcome — CONTEXT.md's four
658
+ # states — taken by `release_outcome` after the call rather than read off its rc.
659
+ #
660
+ # `Unreleased` to start because nothing has been attempted yet, and the line is
661
+ # not printed at all when this claim has no worktree of ours: a state whose
662
+ # definition is "registration and directory both still present" may not be
663
+ # asserted about a worktree that was never there.
664
+ wt_outcome=Unreleased
665
+ # Why the measurement could not be taken, empty whenever it could. Only
666
+ # `Indeterminate` ever carries one, and `halt` appends it to that state's report:
667
+ # "could not be measured" names the failure without naming its cause, which is
668
+ # the one line an operator mid-release has nothing else to go on. #551
669
+ wt_why=
670
+ done_branch=false
671
+ halt() {
672
+ if [ -n "$wt" ]; then
673
+ case $wt_outcome in
674
+ Unreleased) landed="registration and directory both still present";;
675
+ Deregistered) landed="the registration is cleared, the directory is still on disk";;
676
+ Released) landed="registration and directory both gone";;
677
+ *) landed="what the removal landed could not be measured";;
678
+ esac
679
+ [ -z "$wt_why" ] || landed="$landed: $wt_why"
680
+ wt_report="worktree $wt is $wt_outcome — $landed"
681
+ fi
682
+ # The receipt carries the outcome in the blocker string, the one field a
683
+ # caller that never sees stderr can read it out of. No new key: nothing in the
684
+ # repo parses this payload, so a field would be shape for no consumer.
685
+ detail=$1
686
+ [ -z "$wt" ] || detail="$1 — $wt_report"
687
+ if [ "$wt_outcome" = Deregistered ] || [ "$wt_outcome" = Released ] || [ "$done_branch" = true ]; then
688
+ printf '%s: #%s PARTIALLY RELEASED — %s\n' "$NAME" "$issue" "$1" >&2
689
+ elif [ "$wt_outcome" = Indeterminate ]; then
690
+ # Neither headline. Asserting `nothing landed` here would be the original
691
+ # defect with a different trigger, and asserting a partial release would
692
+ # invent one; the operator is told the measurement failed instead.
693
+ printf '%s: #%s HALTED mid-release — what landed could not be measured: %s\n' "$NAME" "$issue" "$1" >&2
694
+ else
695
+ printf '%s: #%s HALTED mid-release — nothing landed: %s\n' "$NAME" "$issue" "$1" >&2
696
+ fi
697
+ [ -z "$wt" ] || printf ' %s\n' "$wt_report" >&2
698
+ echo " branch deleted: $done_branch, in-progress: still on the issue" >&2
699
+ echo " the ticket still reads as taken — finish or restore it by hand" >&2
700
+ blocker_j=$(jstr "$detail") || die "could not escape the halt blocker for #$issue"
701
+ printf '{"issue":%s,"branch":"%s","branchRewritten":%s,"worktree":"%s","worktreeRewritten":%s,"label":%s,"released":false,"applied":true,"blockers":["%s"]}\n' \
702
+ "$issue" "$branch_j" "$branch_rw" "$wt_j" "$wt_rw" "$has_label" "$blocker_j"
703
+ exit 2
704
+ }
705
+
706
+ # Assigned first, exactly as `halt` does above: a `$(jstr …)` spliced straight
707
+ # into the accumulator is not a simple command, so `set -e` reads only the
708
+ # assignment and a failed escape would abort at exit 1 — this script's blocked
709
+ # verdict — with neither the receipt that verdict carries nor a line on stderr.
710
+ block() {
711
+ block_j=$(jstr "$1") || die "could not escape the blocker for #$issue"
712
+ blockers="${blockers}\"$block_j\","
713
+ printf ' BLOCKED: %s\n' "$1" >&2
714
+ }
715
+
716
+ # Is the worktree registered at $1 locked? Both remedies this script can name
717
+ # turn on the answer, so both callers below ask: `git worktree remove` refuses a
718
+ # locked entry outright — before it looks at the directory at all, so present,
719
+ # gone or a stand-in makes no difference — and `git worktree prune` SKIPS one
720
+ # silently at rc 0, printing nothing and clearing nothing (measured, git 2.50.1,
721
+ # on a locked entry whose directory had been deleted). Handing the operator
722
+ # either command for a locked entry names an action that cannot work, and every
723
+ # later run then blocks identically: the permanent refusal this script exists to
724
+ # clear.
725
+ #
726
+ # Read off the porcelain listing already captured above (`wt_list`) rather than a
727
+ # second `git worktree list` call. `cur` is reset on EVERY `worktree ` line, so a
728
+ # sibling's `locked` line can never answer for this path. A `locked [<reason>]`
729
+ # line is matched by its prefix, since the reason is optional and rides on the
730
+ # same line when present, and it is looked for anywhere in the record rather
731
+ # than at a fixed offset: a DETACHED worktree has no `branch` line at all, and a
732
+ # stray is detached by definition.
733
+ #
734
+ # The path goes in through the ENVIRON, not `-v`. POSIX has awk process escape
735
+ # sequences in a `-v` assignment, so a repo living under a directory with a
736
+ # literal backslash in it reached the program mangled — `back\slash` arriving as
737
+ # `backslash`, measured — and could then never equal what the porcelain printed.
738
+ # The comparison fell to "not locked", which is the permissive answer in a guard
739
+ # whose whole job is to refuse to answer permissively. ENVIRON does no such
740
+ # processing.
741
+ # And the status is CAPTURED rather than answered with, for the same reason one
742
+ # rung down (#454). This predicate's answer IS awk's exit status — 0 locked, 1
743
+ # not locked — so an awk that could not run lands above both and, called in a
744
+ # condition as both callers must call it, is read as the FALSE answer: "not
745
+ # locked" again, the permissive one. Measured through this script with awk
746
+ # failing only for the program holding this lock test: the lock blocker never
747
+ # fires, the run asks the tracker and reaches `git worktree remove`, and the
748
+ # receipt then blames the lock rather than the tool that could not answer.
749
+ # `set -e` catches none of it — it is ignored throughout a function invoked in a
750
+ # condition, measured on /bin/sh (bash 3.2), /bin/dash, bash 5.3 and zsh — and
751
+ # the `|| die` the assignments above use cannot serve here, because there is no
752
+ # status left over to die on once the answer has consumed it.
753
+ #
754
+ # `&& return 0` ahead of the status test, not a bare pipeline whose status the
755
+ # next line reads: that makes the pipeline a non-final AND-OR element, where
756
+ # `set -e` is ignored in EVERY context, so a bare call outside a condition
757
+ # reaches the guard as well. Written the bare way that same call never reaches
758
+ # the guard at all — `set -e` kills the script on the pipeline itself, silently,
759
+ # carrying awk's own status out instead of this guard's exit 2 and its
760
+ # `$NAME`-prefixed diagnostic. Not a fail-open: the bare form answers nothing,
761
+ # it dies unattributably (measured, /bin/sh and /bin/dash, awk exiting 2, 5
762
+ # and 127).
763
+ locked() {
764
+ printf '%s\n' "$wt_list" |
765
+ P="$1" awk '/^worktree /{cur=(substr($0,10)==ENVIRON["P"])} cur&&/^locked/{f=1} END{exit !f}' && return 0
766
+ [ $? = 1 ] || die "could not read whether the worktree at $1 is locked for #$issue"
767
+ return 1
768
+ }
769
+
770
+ # Did git fail to resolve $1's HEAD, rather than find it genuinely detached or
771
+ # on some other branch? Four ways an admin HEAD file breaks all produce the
772
+ # same porcelain shape — the null object id with no `branch` line: `chmod 000`
773
+ # on it, garbage content in it, a dangling symlink in its place, or a
774
+ # directory in its place (measured, git 2.50.1). release-ticket.test.mjs
775
+ # builds all four. `chmod 000` is the only one needing a permission bit, so it
776
+ # alone carries the `EUID0` skip the file's other permission fixtures do and
777
+ # measures nothing on a root runner; the other three reproduce as any user.
778
+ #
779
+ # BOTH conditions, never one alone. The null OID alone is also an UNBORN
780
+ # branch (`git worktree add --orphan`) — that one carries a real `branch`
781
+ # line, so admitting it here would refuse a healthy worktree the moment it
782
+ # exists. The absent `branch` line alone is also a genuine DETACHED checkout —
783
+ # that one carries a real sha, not the null OID, so admitting it here would
784
+ # swallow the ordinary case the `else` below exists for.
785
+ #
786
+ # Not `detached`: git prints that line on TWO of the four broken shapes above
787
+ # (the dangling symlink and the directory-in-HEAD's-place both got it,
788
+ # measured) as well as on a genuine detached checkout, so its presence is not
789
+ # evidence of a real detached checkout and its absence is not evidence of this
790
+ # fault either. A guard keyed on it instead of on `branch` misclassifies half
791
+ # of what it exists to catch — and that is pinned, not just reasoned: adding
792
+ # `cur&&/^detached$/{hasbranch=1}` reds the symlink and directory fixtures and
793
+ # nothing else (measured). Not because they are the only porcelain in the suite
794
+ # carrying the line — the genuine `--detach` fixtures print it too — but because
795
+ # those carry a real sha, so `nullhead` never fires for them and the added
796
+ # trigger has nothing left to flip.
797
+ #
798
+ # The status is tested for the reason `locked` gives, and the permissive
799
+ # answer here is the one this arm exists to stop being given: an awk that could
800
+ # not run reads as "HEAD resolves fine", the run falls through to the
801
+ # branch-mismatch `else`, and the receipt asserts the worktree is not on the
802
+ # claim's branch — about a HEAD nothing could read.
803
+ unresolved_head() {
804
+ printf '%s\n' "$wt_list" |
805
+ P="$1" awk '
806
+ /^worktree /{cur=(substr($0,10)==ENVIRON["P"])}
807
+ cur&&/^HEAD 0+$/{nullhead=1}
808
+ cur&&/^branch /{hasbranch=1}
809
+ END{exit !(nullhead && !hasbranch)}' && return 0
810
+ [ $? = 1 ] || die "could not read whether git can resolve the HEAD of the worktree at $1 for #$issue"
811
+ return 1
812
+ }
813
+
814
+ # Is anything at all occupying $1? Not the same question as `gone`, which asks
815
+ # whether an absence is established; this one asks whether the path is taken.
816
+ # `-e` alone FOLLOWS symlinks, so a DANGLING one reads as absent while it still
817
+ # occupies the path and still fails the next `git worktree add` (`fatal: '...'
818
+ # already exists`) — and that is residue this very script can leave: where a
819
+ # symlink POINTS AT the registered worktree directory, `git worktree remove`
820
+ # deletes that directory and returns 0, leaving the link behind and now dangling.
821
+ # NOT the symlink standing in for the directory: that is the rc-255 row of the
822
+ # table below, and there the target survives emptied, so `-e` alone already sees
823
+ # it. Both measured, git 2.50.1. Same reason the non-directory precondition
824
+ # below tests -L separately.
825
+ #
826
+ # Neither shape impeaches the rc-0 fast path at the removal, so nothing there
827
+ # needs re-measuring: no shape measured returns 0 with the path git was asked to
828
+ # delete still occupied — the dangling residue sits on the LINK, which is a
829
+ # different path and reaches this predicate through the orphan probe.
830
+ occupied() { [ -e "$1" ] || [ -L "$1" ]; }
831
+
832
+ # The registration PROBE at the heart of the arm below: is $1 still listed in
833
+ # $now, the fresh post-removal listing? #798. `locked` and `unresolved_head`
834
+ # read their own awk's exit status STRAIGHT as the answer — 0 true, 1 false —
835
+ # so an awk that could not run (rc >= 2: killed, OOM, a broken interpreter) and
836
+ # an awk that ran fine and found no match (rc 1, the genuine "not registered")
837
+ # both land on the false side of the same elif, and #798 measured what that
838
+ # fold did here: with nothing left to distinguish them, the run fell through to
839
+ # `elif occupied "$1"; then wt_outcome=Deregistered` and wrote a false
840
+ # Deregistered into the JSON receipt for a registration nothing established was
841
+ # actually cleared.
842
+ #
843
+ # `locked` and `unresolved_head`'s own fix (#454) is not enough copied
844
+ # verbatim: both `die` on an awk that could not run, which is right for a
845
+ # precondition gate — abort before any mutation is attempted — and wrong here.
846
+ # `release_outcome` runs AFTER `git worktree remove` has already run, is called
847
+ # as a bare statement rather than inside a `$( )`, and its caller reads
848
+ # `$wt_outcome` right after the call returns; a `die` here would abort the
849
+ # function with nothing set — worse than the defect it replaces. Nor can the
850
+ # status be captured with a bare pipeline followed by a separate `reg=$?` line:
851
+ # measured, that does not survive this script's `set -eu` either — `set -e`
852
+ # kills the script on the pipeline itself before the assignment is ever
853
+ # reached. So this stays a boolean predicate in the `locked`/`unresolved_head`
854
+ # shape — a non-final AND-OR element (`… && return 0`), never a bare pipeline
855
+ # whose status a later line reads — but the "could not run" case is carried out
856
+ # through `$wt_why` instead of `die`, for `release_outcome` to route to
857
+ # Indeterminate exactly as it already does for a listing git could not
858
+ # produce, one arm up. 0 registered, 1 genuinely not registered (`$wt_why`
859
+ # stays empty, already cleared by the caller before this runs), anything else
860
+ # could not be told apart from "not registered" by rc alone (`$wt_why` is set
861
+ # to say so, straight into the field the caller already reserves for it).
862
+ ro_registered() {
863
+ printf '%s\n' "$now" |
864
+ P="$1" awk '/^worktree /{if (substr($0,10)==ENVIRON["P"]) f=1} END{exit !f}' && return 0
865
+ [ $? = 1 ] || wt_why="could not tell whether $1 is still registered for #$issue"
866
+ return 1
867
+ }
868
+
869
+ # Which release outcome does $1 hold after a `git worktree remove` that refused?
870
+ # Measured, never inferred from the rc — that inference is this file's #208.
871
+ # git drops the registration BEFORE the directory and does not restore it when
872
+ # the directory delete fails, so one call has three landing shapes and the exit
873
+ # code separates none of them. All measured on git 2.50.1:
874
+ #
875
+ # dirty worktree rc 128, registration and directory kept
876
+ # symlink standing in for the dir rc 255, registration CLEARED, path kept
877
+ # unwritable .git/worktrees rc 255, registration and directory gone
878
+ #
879
+ # A FRESH listing, never `wt_list`: that one was captured before any mutation,
880
+ # so answering from it would re-read the state this function exists to
881
+ # re-measure. Read with the same ENVIRON-keyed awk `locked` uses, and for the
882
+ # same reason — a `-v` assignment mangles a backslash in the path, and the
883
+ # comparison then falls to the permissive answer.
884
+ #
885
+ # The tri-valued directory probe is `occupied` composed with `gone`, exactly the
886
+ # pairing `gone`'s own contract prescribes for a caller that needs present and
887
+ # cannot-stat apart. No second predicate and no third value inside `gone`: it is
888
+ # now a single definition in worktree.sh that every caller in the fleet shares,
889
+ # so a third value added for this one caller lands in all of them — and this file
890
+ # already carries two answers on unreadable worktrees (#83) from a concept that
891
+ # got duplicated. #725
892
+ #
893
+ # Only the four named states, so the two cells CONTEXT.md has no name for are
894
+ # not asserted: a registration that survived a directory that did not is
895
+ # reported Indeterminate rather than squeezed into Unreleased, whose definition
896
+ # is that BOTH are still present.
897
+ # Writes `$wt_outcome`, and `$wt_why` whenever the answer is Indeterminate for a
898
+ # reason git named. It does NOT echo the state: a `$( )` around the call would
899
+ # put the whole body in a subshell, and the cause — which `wt_listing` leaves in
900
+ # `$wt_err` — would die with it. That is not hypothetical, it is what this
901
+ # function did: the one case where the headline degrades to "what landed could
902
+ # not be measured" was the one case whose cause never reached the operator, on
903
+ # stderr or in the receipt. Assigning globals is what carries it out. #551
904
+ release_outcome() {
905
+ # `wt_listing` writes the shared `$wt_list`, and this function must not disturb
906
+ # the pre-mutation capture the guards above read off it. Saved and put back in
907
+ # the same breath — and now load-bearing rather than defensive, because without
908
+ # the subshell there is nothing else keeping the two reads apart.
909
+ ro_prior=$wt_list
910
+ ro_read=true
911
+ wt_listing || ro_read=false
912
+ ro_err=$wt_err
913
+ now=$wt_list
914
+ wt_list=$ro_prior
915
+ wt_why=
916
+ if [ "$ro_read" = false ]; then
917
+ # The listing is how the registration is read, so a listing git could not
918
+ # produce leaves the registration unknown — not absent. `$ro_err` is git's
919
+ # own prose for why it could not, flattened to one line for the receipt.
920
+ wt_outcome=Indeterminate
921
+ wt_why=$(printf '%s' "$ro_err" | tr '\n' ' ')
922
+ elif ro_registered "$1"; then
923
+ if occupied "$1"; then wt_outcome=Unreleased; else wt_outcome=Indeterminate; fi
924
+ elif [ -n "$wt_why" ]; then
925
+ # awk could not run at all (rc >= 2), which is a different fact from
926
+ # "ran fine and found nothing" — the latter alone means Deregistered is on
927
+ # the table below. #798
928
+ wt_outcome=Indeterminate
929
+ elif occupied "$1"; then
930
+ wt_outcome=Deregistered
931
+ elif gone "$1"; then
932
+ wt_outcome=Released
933
+ else
934
+ wt_outcome=Indeterminate
935
+ fi
936
+ }
937
+
938
+ # A path holding a newline, refused rather than acted on. `wt_listing` delivers
939
+ # it whole with the newline substituted, and the substituted byte is one no
940
+ # `git worktree remove`, no `[ -d ]` and no `git -C` below can name — so every
941
+ # check over it would answer about a different path, which is exactly the silent
942
+ # truncation this ticket exists to end. #551
943
+ #
944
+ # `block`, not `die`: this is a refused precondition like every other one here,
945
+ # and the caller gets the receipt that verdict carries. `nl_path ""` is false, so
946
+ # a lookup that found nothing is unaffected.
947
+ #
948
+ # All three keys, because they are three different routes to a worktree of this
949
+ # claim's and a newline anywhere in the chain is the same defect: `wt` off the
950
+ # branch line, `stray` off the directory-name suffix, and `main_wt` — which the
951
+ # orphan probe below builds its path from, so a truncated one sends that probe
952
+ # at a directory nobody registered.
953
+ if nl_path "$wt"; then
954
+ block "worktree $wt holds a newline in its path — nothing here can stat it, so whether it holds work is unknown"
955
+ fi
956
+ if nl_path "$stray"; then
957
+ block "worktree $stray holds a newline in its path — nothing here can stat it, so whether it holds work is unknown"
958
+ fi
959
+ if nl_path "$main_wt"; then
960
+ block "the main checkout $main_wt holds a newline in its path — no path this script builds from it can be stat'd"
961
+ fi
962
+
963
+ if [ "$main_branch" = "refs/heads/$branch" ]; then
964
+ block "branch $branch is checked out in the main checkout — release it from elsewhere"
965
+ fi
966
+
967
+ # The registry ENTRY as a second key for this claim's worktree, consulted ONLY
968
+ # when the suffix key found nothing. `git worktree move` renames the directory
969
+ # and rewrites the entry's `gitdir` file to follow it, but never renames the
970
+ # ENTRY (both measured, git 2.50.1) — so a moved claim whose HEAD git cannot
971
+ # resolve, invisible to `wt` and to the suffix key alike, is still reachable
972
+ # through `$wtroot/$issue-$slug/gitdir`. That file holds `<worktree path>/.git`,
973
+ # and the path git prints in the porcelain is its content with `/.git` stripped,
974
+ # echoed VERBATIM with no canonicalisation of its own (measured: a hand-written
975
+ # `gitdir` naming a path through a symlink is printed back through the symlink),
976
+ # which is what lets the comparison be byte equality against the listing rather
977
+ # than a second opinion about the same path.
978
+ #
979
+ # The entry NAME cannot prove ownership, and the union this fix first shipped
980
+ # assumed it could. git derives the name from the directory's basename at
981
+ # `worktree add` and appends a digit when that name is taken, so an unrelated
982
+ # worktree registered first under `<issue>-<slug>` owns that entry while this
983
+ # claim's is `<issue>-<slug>1`; if that stranger is then MOVED its path no
984
+ # longer carries the suffix, and this key reaches a worktree the suffix key
985
+ # never would. Measured on that fixture, as a plain union: a claim with nothing
986
+ # left to release went from `released:true` at rc 0 to a permanent refusal
987
+ # naming the stranger's directory as this claim's, and a claim whose own HEAD
988
+ # was unreadable had the correct cause over its own directory replaced by the
989
+ # wrong cause over the stranger's. Both are pinned below.
990
+ #
991
+ # So corroborate rather than trust, and let the suffix key answer first. A
992
+ # worktree that resolves to a branch which is not this claim's is demonstrably
993
+ # not this claim's — the `else` arm below says exactly that about it — so it
994
+ # must not refuse the release. One whose HEAD git cannot read MAY genuinely be
995
+ # this claim's, and refusing is the safe direction there; the blocker then
996
+ # states only what the entry establishes, which is the entry NAME.
997
+ #
998
+ # Through the ENVIRON, not `-v`, for the reason `locked` gives: this key is a
999
+ # path read off disk, and a `-v` assignment processes escape sequences in it, so
1000
+ # a repo under a directory with a backslash in its name would arrive mangled and
1001
+ # the comparison would fall to the permissive answer — no match, and back to the
1002
+ # silent release this exists to stop. The suffix key above went through ENVIRON
1003
+ # too, for the same reason (#799): its needle is built from argv rather than
1004
+ # read off disk, but argv is not exempt from a backslash either.
1005
+ #
1006
+ # Absent entry, unreadable entry, or one pointing somewhere git is not listing:
1007
+ # `entry_stray` is empty and the suffix key alone answers, exactly as before.
1008
+ # Not a fail-open — an entry git could not read is one git drops from the
1009
+ # listing, and the listed-vs-registered count above refuses first.
1010
+ stray_own="matches this claim's directory name $issue-$slug"
1011
+
1012
+ # $1 single-quoted for pasting into a shell, answered in `$shq`, with every
1013
+ # embedded `'` emitted as `'\''` — the only way to carry a quote through a
1014
+ # single-quoted string, which has no escape of its own: the quoted run ends, a
1015
+ # backslash-escaped quote stands on its own outside it, and a fresh quoted run
1016
+ # begins. Without it the path's own quote CLOSES the one the hint below opened
1017
+ # and the operator is handed a command the shell refuses to parse at all
1018
+ # (`unexpected EOF`, rc 2, measured) — loud rather than wrong, but an
1019
+ # instruction that cannot run, over a path git accepts in both a refname and a
1020
+ # worktree directory name. #1100
1021
+ #
1022
+ # A parameter-expansion loop, not the `sed` one-liner it wants to be. Two
1023
+ # measurements say why, both on /bin/sh (bash 3.2) and /bin/dash:
1024
+ #
1025
+ # - `esc=$(printf '%s' "$1" | sed …)` on its own line puts this hint behind a
1026
+ # binary that can be missing or shimmed — this script's own suite shims
1027
+ # `sed` — and left unguarded `set -e` kills the run there at sed's status
1028
+ # with sed's diagnostic and no mention of the claim (rc 127).
1029
+ # - Inline, which is the shape the string below wants, the two substitutions
1030
+ # share one assignment word and only the LAST one's status survives: a
1031
+ # failed first substitution contributes an EMPTY path at exit 0, where no
1032
+ # `|| die` can see it. The hint would then read `grep -Fxl '' …`, which
1033
+ # under `-x` matches no `gitdir` line at all (rc 1, no output, BSD grep
1034
+ # 2.6.0) — no entry reported while the entry is right there, the same
1035
+ # silent wrong answer the quoting exists to stop, and the same shape as the
1036
+ # `$( )` in printf's argument list the receipt fields above are assigned
1037
+ # ahead of.
1038
+ #
1039
+ # The loop spawns nothing, so there is no status to guard. Answered in a global
1040
+ # rather than echoed for that second reason exactly — the caller needs this
1041
+ # twice in one string, and a `$( )` around each call is the condemned shape —
1042
+ # and in globals rather than `local`, which is not POSIX and which the repo's
1043
+ # `shellcheck -x -S warning` gate refuses at SC3043.
1044
+ shquote() {
1045
+ shq=
1046
+ shq_rest=$1
1047
+ # `${…%%\'*}` is the run up to the next quote and `${…#*\'}` everything past
1048
+ # it, so each turn appends one run plus the escape and stops when no quote is
1049
+ # left. The pair of quotes goes on at the end, around the whole accumulation.
1050
+ while [ "$shq_rest" != "${shq_rest#*\'}" ]; do
1051
+ shq="$shq${shq_rest%%\'*}'\\''"
1052
+ shq_rest=${shq_rest#*\'}
1053
+ done
1054
+ shq="'$shq$shq_rest'"
1055
+ }
1056
+ # WHICH entry, for the unresolved-HEAD arm alone. That arm is the one fault with
1057
+ # no remedy to name — measured on a corrupt-HEAD entry, `git worktree repair`
1058
+ # and `git worktree prune -v` both leave it standing at rc 0, and `remove` with
1059
+ # and without `--force` both refuse at rc 128 — so "by hand" is the instruction
1060
+ # and the only thing left to hand over is where by hand goes.
1061
+ #
1062
+ # A search, not a name built from the directory. The entry name is git's own,
1063
+ # on the two measurements the block above already turns on. So `${stray##*/}`
1064
+ # would assert a path this script never read, which is the defect class #179
1065
+ # exists to remove, and after a move or behind an entry thief it resolves to
1066
+ # somebody else's entry outright.
1067
+ #
1068
+ # `-x`, not a substring: `gitdir` holds exactly one line whose whole content is
1069
+ # `<path>/.git`, so whole-line equality is the precise test and subsumes the
1070
+ # `/.git` anchor. A substring is wrong in BOTH directions — it hits a sibling
1071
+ # whose directory extends this one (measured: a search for a `9-x` worktree
1072
+ # also hits `9-x-renamed`'s entry) and one registered under a path that ends
1073
+ # with this one. `-F` because the subject is a path and its metacharacters are
1074
+ # not a pattern.
1075
+ #
1076
+ # SINGLE quotes around both paths, glob outside them, because this string is
1077
+ # pasted into a shell and a path is not shell text: under double quotes a `$`
1078
+ # in the path expands again when the operator runs it and the search comes back
1079
+ # EMPTY at rc 1 — no entry reported while the entry is right there, this arm's
1080
+ # own defect one step further out — and an unquoted `$wtroot/*/gitdir` splits
1081
+ # on a space. Through `shquote`, because quoting a path is not the same as
1082
+ # wrapping it in quotes: the one character that defeats a quoted string is the
1083
+ # quote, and git accepts one in a worktree directory name.
1084
+ #
1085
+ # Empty on the entry key, which read `$wtroot/$issue-$slug/gitdir` itself and
1086
+ # puts that name in `$stray_own`: searching for what it already measured would
1087
+ # be the step backwards. Assigned before that key can answer, so `$stray` here
1088
+ # is the suffix key's or nothing.
1089
+ shquote "$stray/.git"
1090
+ stray_needle=$shq
1091
+ shquote "$wtroot"
1092
+ stray_find="; find that entry with: grep -Fxl $stray_needle $shq/*/gitdir"
1093
+ if [ -z "$wt" ] && [ -z "$stray" ] && [ -r "$wtroot/$issue-$slug/gitdir" ]; then
1094
+ entry_wt=$(cat "$wtroot/$issue-$slug/gitdir") ||
1095
+ die "could not read the worktree registry entry $wtroot/$issue-$slug/gitdir for #$issue"
1096
+ entry_wt=${entry_wt%/.git}
1097
+ entry_stray=$(printf '%s\n' "$wt_list" |
1098
+ E="$entry_wt" awk '/^worktree /{n++; p=substr($0,10)
1099
+ if (n>1 && p == ENVIRON["E"]) {print p; exit}}') ||
1100
+ die "could not scan git's listing for a stray worktree for #$issue"
1101
+ if [ -n "$entry_stray" ] && unresolved_head "$entry_stray"; then
1102
+ stray="$entry_stray"
1103
+ stray_own="holds this claim's registry entry name $issue-$slug"
1104
+ stray_find=
1105
+ fi
1106
+ fi
1107
+
1108
+ if [ -z "$wt" ] && [ -n "$stray" ]; then
1109
+ # Which remedy applies turns on whether that directory is still there, and
1110
+ # asking only the registration named the wrong one whenever it is not: the
1111
+ # entry outlives the directory — `worktree list --porcelain` keeps listing it,
1112
+ # annotated `prunable`, after an `rm -rf` — so a claim with nothing left to
1113
+ # hand-release was told to hand-release it. That instruction names no action
1114
+ # the operator can take, so nothing cleared the entry and every later run
1115
+ # blocked identically: the permanent refusal, with the label and the branch
1116
+ # standing and the in-flight probe still reading the ticket as taken, that this
1117
+ # script exists to clear.
1118
+ #
1119
+ # Blocked either way, never released. This worktree is not on the claim's
1120
+ # branch, so releasing would delete a different ref and then reach the
1121
+ # `git worktree prune` a completed apply ends with — unanchoring a detached HEAD's
1122
+ # commits, which no ref points at, as a side effect of releasing something
1123
+ # else. Naming that prune hands the operator the command that does clear the
1124
+ # entry (verified, git 2.50.1: the run after it releases) and leaves the
1125
+ # discard their decision.
1126
+ #
1127
+ # A LOCK outranks both, because it is what makes both refuse: prune skips a
1128
+ # locked entry and remove rejects one, so neither remedy above is reachable
1129
+ # until the operator unlocks. Named first for that reason, not because it is
1130
+ # more likely.
1131
+ #
1132
+ # UNRESOLVED HEAD outranks the branch-mismatch else, but not the two above:
1133
+ # a lock still makes every remedy unreachable regardless of what HEAD says,
1134
+ # and a gone directory still means prune regardless of what HEAD says — this
1135
+ # fault is only interesting while there is a directory and no lock to talk
1136
+ # about. Below it, the `else` — this arm's whole reason to exist is that the
1137
+ # `else` cannot tell "genuinely on some other branch" from "git could not
1138
+ # tell", and asserts the former for both.
1139
+ #
1140
+ # `$stray_own` defaults, at its assignment above, to the only claim the
1141
+ # suffix key establishes — the directory-name match — so every arm below,
1142
+ # including this `else`, states just that unless the entry key overrode it.
1143
+ # This `else` can never see that override: entry-key credit is granted only
1144
+ # where `unresolved_head` is true, which is not this branch.
1145
+ #
1146
+ # A directory NAME is not ownership, and this arm is where that bites. The
1147
+ # suffix key admits any linked worktree whose basename is `<issue>-<slug>` and
1148
+ # prints the FIRST in porcelain order, so a stranger registered under that
1149
+ # basename and sorting ahead of the claim is what it answers with — measured
1150
+ # on a healthy decoy at `.worktrees/0-decoy/<issue>-<slug>`, which took this
1151
+ # blocker while the claim's own detached directory sat behind it (#1064, and
1152
+ # the fixture is pinned below). `is this claim's` then sent an operator to
1153
+ # hand-release somebody else's live tree, over a worktree the script had just
1154
+ # read a DIFFERENT branch off — the one case where it can say the assertion is
1155
+ # false. Name the collision instead: same directory name, wrong branch, which
1156
+ # is all the key established and is CONTEXT.md's own definition of a Stray.
1157
+ #
1158
+ # In the ordinary case the match IS the claim's own directory, and the weaker
1159
+ # sentence stays true of it — a directory named `<issue>-<slug>` matches that
1160
+ # name. Nothing distinguishable is lost, because the script cannot distinguish
1161
+ # the two: that is the reason it must not assert the difference.
1162
+ #
1163
+ # Still a refusal, and deliberately: a same-basename directory under
1164
+ # `.worktrees` is a collision an operator should look at whoever owns it, and
1165
+ # releasing would delete the claim's branch while this tree stands. Wording
1166
+ # only — the match and the verdict are unchanged.
1167
+ # The unlock command below is the one other pasted remedy in this chain that
1168
+ # takes `$stray` as an argument — `git worktree prune` and `release it by
1169
+ # hand` name no path — so it is the one other arm `shquote` must cover for
1170
+ # the same reason #1100 covered the entry search: an embedded `'` closes the
1171
+ # quote this hint has no quote of its own to reopen, and the operator is
1172
+ # handed a command that runs against a truncated, different path instead of
1173
+ # being refused outright. (#1554)
1174
+ shquote "$stray"
1175
+ stray_shq=$shq
1176
+ if locked "$stray"; then
1177
+ block "worktree $stray $stray_own and is locked — git worktree unlock $stray_shq, then prune or remove it"
1178
+ elif gone "$stray"; then
1179
+ block "worktree $stray $stray_own and its directory is gone — git worktree prune to clear the registration"
1180
+ elif unresolved_head "$stray"; then
1181
+ block "worktree $stray $stray_own but git could not read its HEAD, so its branch is unknown — inspect its entry's HEAD file under $wtroot by hand$stray_find"
1182
+ else
1183
+ block "worktree $stray $stray_own but is not on $branch — release it by hand"
1184
+ fi
1185
+ fi
1186
+
1187
+ # An Orphaned worktree directory: this claim's directory still on disk with its
1188
+ # registration already cleared. `stray` cannot see it BY CONSTRUCTION — it is
1189
+ # awk over git's registry, and there is no registration left to match — so the
1190
+ # run after a Deregistered halt found no `wt` and no `stray`, deleted the
1191
+ # branch, dropped the label and exited 0 with `"released":true,"blockers":[]`
1192
+ # over a directory that is still there. The next `claim-ticket.sh` for the slug
1193
+ # then died on it (`[ -e "$wt" ] && die`), with nothing left to explain why.
1194
+ #
1195
+ # So probe the path directly instead of through the registry, reconstructed from
1196
+ # the same `<issue>-<slug>` pairing `stray` matches on. Anchored at the main
1197
+ # checkout, since claim-ticket.sh writes `.worktrees/$issue-$slug` relative to
1198
+ # its own cwd — a claim made from anywhere but the repo root is outside this
1199
+ # probe's reach, which is a miss and never a false refusal.
1200
+ #
1201
+ # In the PRECONDITION block deliberately, not in the mutation path: here the dry
1202
+ # run predicts the refusal for free, where placed below it would report only
1203
+ # under --apply and rebuild the dry/apply asymmetry #86, #385 and #386 were
1204
+ # filed against.
1205
+ #
1206
+ # Gated on this claim having no registration of ours. With `wt` or `stray` set
1207
+ # the directory IS registered and a guard above owns it — which is what keeps a
1208
+ # healthy claim, whose worktree sits at exactly this path, from blocking here.
1209
+ #
1210
+ # The remedy is a manual removal and deliberately never `git worktree prune`:
1211
+ # prune clears registrations, and the defining property of this state is that
1212
+ # there is no registration left to clear, so naming it would hand the operator a
1213
+ # command that cannot work and every later run would block identically — the
1214
+ # permanent refusal the stray guard above describes for the mirror-image case.
1215
+ # Nor an automatic delete: a refusal is a finding to report, and nothing here
1216
+ # has inspected what is in that directory.
1217
+ #
1218
+ # Absence is ESTABLISHED by `gone`, never inferred from `occupied` alone, for
1219
+ # the reason the dirty check gives: read as "no orphan", a `.worktrees` this
1220
+ # script may not search would release the claim over one.
1221
+ if [ -z "$wt" ] && [ -z "$stray" ]; then
1222
+ orphan="$main_wt/.worktrees/$issue-$slug"
1223
+ if occupied "$orphan"; then
1224
+ block "worktree directory $orphan is this claim's and has no registration — inspect it and remove the directory by hand"
1225
+ elif ! gone "$orphan"; then
1226
+ block "cannot tell whether an orphaned worktree directory is at $orphan, so whether #$issue can be released is unknown"
1227
+ elif [ "$has_branch" = false ] && [ -z "$blockers" ]; then
1228
+ # A mistyped <slug>/<type> names a branch that does not exist, and without
1229
+ # this die the run would drop the label off a ticket whose real claim is
1230
+ # untouched — invisible to candidates.mjs and still in-flight. Refuse
1231
+ # instead of guessing.
1232
+ #
1233
+ # Deferred past the orphan probe above (#624) rather than fired the moment
1234
+ # `has_branch` reads false: this exact input — no branch, no worktree, no
1235
+ # stray — is also what #208's knock-on leaves behind, a claim whose branch
1236
+ # a prior half-release already deleted with its directory still on disk.
1237
+ # Fired unconditionally, that state got the same "check the <slug> and
1238
+ # <type> arguments" prose as a genuine typo, naming the wrong cause over a
1239
+ # directory sitting right there with a real remedy. The orphan probe above
1240
+ # answers that question first, so this die runs only once it has had its
1241
+ # say.
1242
+ #
1243
+ # The `-z "$blockers"` conjunct is load-bearing, not dead weight (a prior
1244
+ # round of this comment argued the opposite and was wrong): `$blockers` can
1245
+ # be non-empty here even though this arm's own occupied/gone siblings above
1246
+ # did not fire. `git checkout --orphan release/5-foo` on the MAIN checkout
1247
+ # points HEAD at refs/heads/release/5-foo before any commit exists, so
1248
+ # `main_branch` (read off `git worktree list --porcelain`) already equals
1249
+ # `refs/heads/$branch` and the EARLIER, unrelated "branch ... is checked
1250
+ # out in the main checkout" guard above has already `block`ed — while
1251
+ # `git rev-parse --verify --quiet refs/heads/$branch` fails on the unborn
1252
+ # ref, so `has_branch` still reads false (measured). Without this guard the
1253
+ # die fires anyway, appending its own usage-error prose to a receipt that
1254
+ # already named the real cause, and exiting 2 instead of the correct
1255
+ # blocked-at-1 verdict. Guarding on `$blockers` lets that earlier finding
1256
+ # stand as the only word on an otherwise silent run.
1257
+ die "no branch $branch and no worktree on it — check the <slug> and <type> arguments"
1258
+ fi
1259
+ fi
1260
+
1261
+ if [ "$has_branch" = true ]; then
1262
+ # Commits ahead — a member that did work. Measured on the branch ref rather
1263
+ # than the worktree's HEAD: the worktree above was located BY that ref, so the
1264
+ # two agree, and this still runs when the worktree is already gone.
1265
+ ahead=$(git rev-list --count "$base_rev..refs/heads/$branch") ||
1266
+ die "cannot count commits on $branch against $base"
1267
+ [ "$ahead" -eq 0 ] || block "$ahead commit(s) ahead of $base"
1268
+
1269
+ # Commits that exist nowhere else. Against the remote-tracking ref, never a
1270
+ # local main: a local main you never fast-forwarded reads every merged branch
1271
+ # as unmerged. Stricter than `ahead` in what it means, weaker in what it
1272
+ # catches — a commit already cherry-picked upstream is upstream-equivalent
1273
+ # here (a `-` line) and only `ahead` blocks it. Both, or that one walks.
1274
+ #
1275
+ # Run and count in two steps. Piped straight into `grep -c ... || true`, a
1276
+ # `git cherry` that failed outright (rc 128 on a corrupt object store, say)
1277
+ # yielded a count of 0 and the check silently passed; only the `ahead` guard
1278
+ # above, failing on the same conditions, kept that from being a delete.
1279
+ cherry=$(git cherry "$base_rev" "refs/heads/$branch") ||
1280
+ die "git cherry failed on $branch against $base, so whether it carries unique commits is unknown"
1281
+ uniq=$(printf '%s' "$cherry" | grep -c '^+' || true)
1282
+ [ "$uniq" -eq 0 ] || block "$uniq commit(s) unique to $branch (git cherry)"
1283
+ fi
1284
+
1285
+ # A pushed branch — work that survives the local delete and that a PR may
1286
+ # already point at. Live query, so this one cannot be stale; a failure here is
1287
+ # an unknown answer, never a "no".
1288
+ # stderr stays on stderr, never folded into the value: the emptiness of $remote
1289
+ # IS the answer, so an SSH host-key notice on a successful query used to read as
1290
+ # a branch that exists. git's own message is more useful on the terminal anyway.
1291
+ # 30s: `ls-remote` moves refs and no objects, so this is generous for the work,
1292
+ # and it is the budget inflight.sh's own `ls-remote` runs on. `FLEET_NET_TIMEOUT`
1293
+ # is the shorten-only override this lookup shares with the fleet's fetches — but
1294
+ # NOT with inflight.sh's `ls-remote`, which reads `INFLIGHT_LS_REMOTE_TIMEOUT`
1295
+ # and nothing else, so shortening this one does not shorten that one. The rule
1296
+ # is net_budget's, in net.sh.
1297
+ ls_budget=$(net_budget 30 "${FLEET_NET_TIMEOUT:-}")
1298
+ ls_rc=0
1299
+ remote=$(net_git "" "$ls_budget" ls-remote --heads origin "refs/heads/$branch") || ls_rc=$?
1300
+ if [ "$ls_rc" -ne 0 ]; then
1301
+ # A killed lookup and a refused one are different facts and get different
1302
+ # words. Both leave the same verdict — the answer is unknown, so nothing is
1303
+ # released — but only one of them names a cause this script observed.
1304
+ if net_stalled "$ls_rc"; then
1305
+ die "git ls-remote did not finish within ${ls_budget}s and was killed, so whether $branch was pushed is unknown"
1306
+ fi
1307
+ die "git ls-remote failed, so whether $branch was pushed is unknown"
1308
+ fi
1309
+ [ -z "$remote" ] || block "branch $branch exists on origin"
1310
+
1311
+ # `-d`, because a directory that is not there holds no uncommitted work. Deleted
1312
+ # by hand, a worktree leaves its admin files registered, so `worktree list
1313
+ # --porcelain` keeps listing the entry and the status below ran against a path
1314
+ # that is gone: it failed, the die read that as "unknown", and the claim could
1315
+ # then never be released — label, branch and worktree entry all surviving every
1316
+ # run while the in-flight probe kept reading the ticket as taken. git agrees at
1317
+ # the delete: `worktree remove` accepts the gone entry and clears the admin
1318
+ # files outright, so the `prune` below finds nothing left to do (verified, git
1319
+ # 2.50.1) — and it is only reachable at all once that remove has succeeded.
1320
+ #
1321
+ # Not git's own `prunable` annotation, which marks this entry but is not the
1322
+ # same question: removing only a LIVE worktree's .git file marks it `prunable`
1323
+ # too, with the directory and every uncommitted change still sitting in it.
1324
+ # Keying on the annotation would skip the check on that one, and `worktree
1325
+ # remove` then refuses it (rc 128) — so instead of the refusal the linkage guard
1326
+ # below reaches on its own, the run gets as far as `halt` and exits 2 over a
1327
+ # worktree still holding the work, reporting it as a claim nothing touched.
1328
+ #
1329
+ # Absence is ESTABLISHED by `gone`, never inferred from a failed -d, because -d
1330
+ # is also false for a directory we are not permitted to stat — and on this path
1331
+ # the delete-time recomputation the header leans on is absent (`worktree remove`
1332
+ # accepts the entry either way, as `gone` explains), so this is the only check
1333
+ # left standing. Read as "gone", an unsearchable prefix released the claim —
1334
+ # branch deleted, label dropped, exit 0, `"blockers":[]` — with the member's
1335
+ # uncommitted work still on disk and now orphaned.
1336
+ #
1337
+ # `occupied`, where this read `[ ! -e "$wt" ]`: `gone` reports a path that EXISTS
1338
+ # as not-established-absent, which is the same answer it gives for one it cannot
1339
+ # stat, and only the second is unknown — so the existence test has to be the one
1340
+ # that agrees with `gone` about what "exists" means. It did not. Every `test`
1341
+ # primary except `-L` STATS, so a DANGLING symlink is `-e` false, and once `gone`
1342
+ # stopped calling that established-absent (#725) this guard read it as "cannot
1343
+ # tell" and died at exit 2 with no receipt — for a path whose state is known
1344
+ # exactly, and which the stand-in blocker below already answers. Measured on
1345
+ # release-ticket.test.mjs's own dangling-link fixture, which is what caught it.
1346
+ #
1347
+ # `! occupied && ! gone` is the tri-valued pairing `gone`'s contract prescribes,
1348
+ # and the same one `release_outcome` composes: present or link-present is not
1349
+ # unknown, established-absent is not unknown, and what is left over is.
1350
+ #
1351
+ # `! nl_path` for the same reason the dangling link needed `occupied`, and it is
1352
+ # the same trap a second time: `gone` now refuses a substituted path too (#551),
1353
+ # so without this exemption the pairing reads it as "cannot tell" and dies — for
1354
+ # a path the newline blocker above has already answered in the operator's own
1355
+ # terms, downgrading a receipt-carrying `NOT released` verdict to an exit-2 die
1356
+ # that says nothing the receipt did not. Measured on a worktree registered at a
1357
+ # path holding a newline.
1358
+ if [ -n "$wt" ] && ! nl_path "$wt" && ! occupied "$wt" && ! gone "$wt"; then
1359
+ die "cannot tell whether $wt exists, so whether it holds uncommitted work is unknown"
1360
+ fi
1361
+
1362
+ # A lock refuses independently of the directory's shape — present, gone or a
1363
+ # stand-in — so this runs whenever $wt is ours, not only when -d holds below.
1364
+ # Without it a locked worktree cleared every blocker, the dry run predicted a
1365
+ # release, and --apply reached `git worktree remove`, which refused it (rc 128)
1366
+ # after the dirty check below had already said clean. See `locked` for why the
1367
+ # answer is read off `wt_list`.
1368
+ if [ -n "$wt" ] && locked "$wt"; then
1369
+ block "worktree $wt is locked — git worktree remove refuses a locked entry"
1370
+ fi
1371
+
1372
+ # `worktree remove` validates $wt/.git before touching anything else, and a
1373
+ # regular file sitting at $wt has none — refused at rc 128 ("does not exist"),
1374
+ # measured. The dirty check below only opens when $wt IS a directory, so a
1375
+ # non-directory there cleared every guard silently and only --apply found out.
1376
+ #
1377
+ # -L, and it is not what the -e/-d pair already covers: every other `test`
1378
+ # primary FOLLOWS the link, so a symlink pointing at the real worktree directory
1379
+ # reads as present-and-a-directory and walked through both of them. That one is
1380
+ # the worst case in the file — `worktree remove` UNREGISTERS the entry and only
1381
+ # then fails ("Not a directory", rc 255, measured on git 2.50.1), so the run
1382
+ # halts reporting a worktree it did not remove after it had already landed
1383
+ # something. A dangling link is the other shape: -e is false through it, so
1384
+ # `gone` above calls it established-absent and the unknown-existence die stands
1385
+ # down by design, leaving this the only guard between it and git's rc-128
1386
+ # "'…/.git' does not exist" — the refusal the paragraph above was written for.
1387
+ #
1388
+ # -L tests the final component only, and `git worktree add` always creates that
1389
+ # as a real directory, so no worktree this fleet made trips it.
1390
+ if [ -n "$wt" ] && { [ -L "$wt" ] || { [ -e "$wt" ] && [ ! -d "$wt" ]; }; }; then
1391
+ block "worktree $wt exists but is not a directory — git worktree remove will refuse it"
1392
+ fi
1393
+
1394
+ if [ -n "$wt" ] && [ -d "$wt" ]; then
1395
+ # Establish that a .git linkage EXISTS before believing the status below.
1396
+ # Delete the .git file outright — directory and every uncommitted file still on
1397
+ # disk — and `git -C` does not fail: it walks UP to the enclosing repository and
1398
+ # reports the PARENT's status at rc 0. `.worktrees/` is gitignored here, so the
1399
+ # worktree never appears in that status either: with a clean parent the answer
1400
+ # is empty, a positive assertion that the claim is clean produced without ever
1401
+ # having looked at it. The -d gate above does not reach it (the directory is
1402
+ # there) and neither does the status die below (git succeeded).
1403
+ #
1404
+ # Existence is not enough on its own: a .git naming a gitdir whose
1405
+ # core.worktree is some OTHER directory is a well-formed regular file too, and
1406
+ # git then answers happily about that other tree at rc 0 (measured, #135). The
1407
+ # block below closes that — this one only establishes the file is there to
1408
+ # examine.
1409
+ #
1410
+ # `-f` and not `-e`: an empty `.git` DIRECTORY leaks exactly like an absent
1411
+ # one — git walks up and reports the parent at rc 0 — and -e is true for it
1412
+ # (measured). A linked worktree's .git is always a regular file, since
1413
+ # `git worktree add` writes one, so -f costs nothing and refuses that too. A
1414
+ # dangling .git symlink is likewise rc 0, not the rc 128 the status die needs,
1415
+ # so this guard is what catches that one as well.
1416
+ #
1417
+ # `! -x` for the reason the block above gives: -f is ALSO false for a .git we
1418
+ # are not permitted to stat, and this guard may not infer absence from that any
1419
+ # more than -d may. An unsearchable worktree still has its .git, so leave it to
1420
+ # the status die, which keeps git's own "Permission denied" rather than
1421
+ # asserting an absence nothing established (measured: chmod 644 on the worktree
1422
+ # makes -f false with the .git sitting right there).
1423
+ [ -f "$wt/.git" ] || [ ! -x "$wt" ] || die "$wt has no .git file, so whether it holds uncommitted work is unknown"
1424
+
1425
+ # Now establish the linkage points BACK at $wt, not merely that it exists.
1426
+ # Gated on -f rather than "we didn't just die": an unsearchable $wt fails -f
1427
+ # too, and this block must not run for it — `git -C "$wt" rev-parse` would
1428
+ # fail there under this script's own "cannot read the git repository"
1429
+ # message, replacing the "Permission denied" the status die below is there
1430
+ # to preserve.
1431
+ #
1432
+ # `git -C "$wt" rev-parse --show-toplevel` answers with the linkage's own
1433
+ # idea of $wt's working tree. Comparing it against $wt itself refuses every
1434
+ # shape that moves git's WORKING TREE away from $wt while $wt/.git still
1435
+ # passes the `-f` gate above — #74/#115's walk-up (an absent, empty-directory,
1436
+ # or dangling-symlink .git) fails that gate and is refused there instead,
1437
+ # never reaching this compare: #135's own repro, a hand-written .git naming
1438
+ # a gitdir whose core.worktree is elsewhere, whether or not that gitdir is
1439
+ # named `.git`; and core.worktree set in the worktree's own config.worktree
1440
+ # under extensions.worktreeConfig, the .git file untouched (all measured, git
1441
+ # 2.50.1).
1442
+ #
1443
+ # no-undo-audit.sh calls this "the spelling to avoid". Its three false-refusal
1444
+ # classes (a relative $wt, a symlinked path, macOS's /private) cannot arise
1445
+ # here: the two are compared as directories, not strings (below). Measured
1446
+ # passing on all three, and after `git worktree move`. That script's spelling
1447
+ # is no substitute either: `--show-prefix` is empty at rc 0 for both
1448
+ # core.worktree shapes above.
1449
+ #
1450
+ # What this does NOT cover (#421): shapes that swap which git dir answers
1451
+ # while the working tree stays $wt. A .git naming a SIBLING worktree's admin
1452
+ # dir (#189; copying one worktree's contents, .git included, over another
1453
+ # produces it), or a foreign git dir whose core.worktree points back at $wt.
1454
+ # `--show-toplevel` answers $wt for both, so the compare passes them. They
1455
+ # are stopped downstream, before anything changes: the status below reads
1456
+ # $wt's real files against the borrowed index, so uncommitted work shows as
1457
+ # dirty (measured); and when it does not, `git worktree remove`, the first
1458
+ # mutation, ahead of the branch and the label, refuses at rc 128 ("does not
1459
+ # point back to .git/worktrees/<name>", measured). The cost is a dry run that
1460
+ # can call such a claim releasable and an --apply that then halts. Left
1461
+ # there on purpose: these shapes need a hand-copied .git or deliberate
1462
+ # tampering, `git worktree` never writes one, and #421 ruled a stricter
1463
+ # check here not worth its code.
1464
+ #
1465
+ # Compared as a DIRECTORY (`-ef`, same device and inode), never as a string,
1466
+ # or this false-refuses a HEALTHY worktree: `$wt` is the path `worktree list
1467
+ # --porcelain` echoes and `--show-toplevel` is git's own resolved spelling,
1468
+ # and the two legitimately differ for one and the same directory. A parent
1469
+ # that was a plain dir at `worktree add` time and is a symlink now leaves the
1470
+ # listed path non-canonical while git's answer is resolved (measured). And a
1471
+ # path holding a Unicode NFD-composed name (`cafe` + U+0301) is listed
1472
+ # PRECOMPOSED by the `core.precomposeunicode` git writes into every new repo
1473
+ # on macOS, while `--show-toplevel` answers the on-disk NFD bytes — visually
1474
+ # identical, byte-different, one directory (measured, git 2.50.1, Apple
1475
+ # Git-155, #2094; reap.sh's copy of this compare, #2072). Under bash —
1476
+ # macOS's own `/bin/sh` — `cd "$wt" && pwd -P` canonicalised only the
1477
+ # first: it echoes the spelling it was given, so a byte compare against it
1478
+ # refused every healthy NFD worktree at exit 2 there; dash's own `pwd -P`
1479
+ # resolves through to the on-disk NFD bytes instead, so that shell's old
1480
+ # byte compare would not have refused the same worktree. `-ef`
1481
+ # answers "same directory" for both and for any other spelling the
1482
+ # filesystem aliases, and still refuses every redirect above — each names a
1483
+ # different directory. POSIX.1-2017's `test` does not define `-ef`; it is a
1484
+ # ksh-derived extension bash, dash and BSD sh share, and POSIX.1-2024 adds it.
1485
+ # A `[` that cannot evaluate it fails, and so does a `--show-toplevel` naming
1486
+ # a path that does not exist: both are the refusing direction.
1487
+ #
1488
+ # `&& echo x` inside the substitution, then `%?x`: `$(...)` strips EVERY
1489
+ # trailing newline, so a `core.worktree` naming a sibling directory called
1490
+ # `$wt` plus a newline byte — git accepts one as an ordinary path character —
1491
+ # would otherwise name `$wt` itself and pass the redirect, the dirty check
1492
+ # then reading that sibling's clean copy over $wt's work (measured, #2073;
1493
+ # the shape no-undo-audit.sh closed the same way, #2040, and reap.sh's copy
1494
+ # of this compare, #2042). The sentinel leaves `$(...)` only git's own
1495
+ # terminating newline to strip.
1496
+ #
1497
+ # A $wt whose own leaf was replaced by a symlink — never `git worktree add`'s
1498
+ # own shape, hand tampering only — still reaches this compare, because the
1499
+ # `-L` guard just above `block`s rather than `die`s (see its own comment).
1500
+ # `-ef` follows the link, and `--show-toplevel` resolves through it to the
1501
+ # same real, possibly newline-suffixed, directory, so the two compare equal
1502
+ # and that case stays exactly as blocked — "not a directory" at exit 1 — never
1503
+ # a fabricated "does not point at itself" mismatch at exit 2 (#2073).
1504
+ if [ -f "$wt/.git" ]; then
1505
+ toplevel=$(git -C "$wt" rev-parse --show-toplevel && echo x) ||
1506
+ die "cannot read the git repository at $wt (its .git file or the gitdir it names), so whether it holds uncommitted work is unknown"
1507
+ toplevel=${toplevel%?x}
1508
+ # 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
1509
+ [ "$toplevel" -ef "$wt" ] ||
1510
+ die "$wt's .git does not point at $wt — it resolves to $toplevel — so whether it holds uncommitted work is unknown"
1511
+ fi
1512
+
1513
+ # Same reason: folded-in stderr would be counted as uncommitted changes.
1514
+ #
1515
+ # `-uall`: #730 (see reap.sh's branch sweep for the full explanation) — a
1516
+ # bare `--porcelain` reads clean over a dirty tree under
1517
+ # `status.showUntrackedFiles = no`, releasing a claim whose only copy of
1518
+ # that work is the directory about to be deleted. The `git worktree remove`
1519
+ # refusal this block's own comment leans on is no backstop — same
1520
+ # machinery, same config.
1521
+ if ! dirty=$(git -C "$wt" status --porcelain -uall); then
1522
+ die "cannot read the status of $wt, so whether it holds uncommitted work is unknown"
1523
+ fi
1524
+ # Ignored files are deliberately not a blocker: the runner claim-ticket.sh
1525
+ # writes into a claimed worktree is excluded (ignored) there, and older
1526
+ # checkouts hold a `.gitignore`'d `.agent-test.sh` from the pre-ADR-0015
1527
+ # bootstrap, so blocking on ignored files would strand every
1528
+ # claim. `git worktree remove` deletes ignored files
1529
+ # silently and refuses on modified and untracked ones (verified, git 2.50.1) —
1530
+ # which is this same check, recomputed by git at the moment of the delete, and
1531
+ # only while the directory is there. That is the header's live-directory case:
1532
+ # git gates that refusal on the same stat this block's `-d` gate does, so on a path
1533
+ # neither can stat it accepts the entry at rc 0 instead, and `gone` is what
1534
+ # stands between the member's work and the delete.
1535
+ n=$(printf '%s' "$dirty" | grep -c . || true)
1536
+ [ "$n" -eq 0 ] || block "worktree $wt has $n uncommitted change(s)"
1537
+ fi
1538
+
1539
+ # Report the blockers before asking GitHub anything. The answer cannot change —
1540
+ # every artefact stays put either way — and reaching for the tracker first turns
1541
+ # an offline blocked claim into an unanswerable one, burying the finding the
1542
+ # caller actually needs. "label":null says it was never read.
1543
+ if [ -n "$blockers" ]; then
1544
+ echo "$NAME: #$issue NOT released — nothing was touched" >&2
1545
+ printf '{"issue":%s,"branch":"%s","branchRewritten":%s,"worktree":"%s","worktreeRewritten":%s,"label":null,"released":false,"applied":%s,"blockers":[%s]}\n' \
1546
+ "$issue" "$branch_j" "$branch_rw" "$wt_j" "$wt_rw" "$apply" "${blockers%,}"
1547
+ exit 1
1548
+ fi
1549
+
1550
+ # Read the label before touching anything, so a tracker that cannot answer stops
1551
+ # the run before any delete rather than halfway through it.
1552
+ #
1553
+ # One name per line, matched whole. Captured with 2>&1 and substring-matched,
1554
+ # any stderr from a SUCCESSFUL gh — its "a new release is available" notice, an
1555
+ # auth warning — broke the delimiting, the match missed, and the script deleted
1556
+ # the worktree and the branch while leaving in-progress on the ticket: exit 0,
1557
+ # "label":false, indistinguishable from a legitimately already-dropped label,
1558
+ # and the ticket invisible to candidates.mjs with no artefact left to explain it.
1559
+ echo "\$ gh issue view $issue --json labels" >&2
1560
+ if ! labels=$(gh issue view "$issue" --json labels --jq '.labels[].name'); then
1561
+ die "gh issue view $issue failed, so the in-progress label cannot be released"
1562
+ fi
1563
+ # grep's OWN scan failing (rc 2+) must not read as "no in-progress label":
1564
+ # the same defect PR #1519 fixed in reap.sh's grep_probe (#1543). A bare
1565
+ # `if … grep -qx …; then has_label=true; else has_label=false; fi` has room
1566
+ # for only two of grep's three `-q` outcomes — rc 0 matched, rc 1 none did,
1567
+ # rc 2+ the scan itself broke — so a scan that could not look would read
1568
+ # here exactly like a measurement that looked and found the label already
1569
+ # gone, and the release below would leave the ticket invisible to
1570
+ # candidates.mjs with no artefact left to explain it — the same failure
1571
+ # mode the comment above this block already guards against on the `gh` side.
1572
+ if printf '%s\n' "$labels" | grep -qx in-progress; then rt_gp_rc=0; else rt_gp_rc=$?; fi
1573
+ case $rt_gp_rc in
1574
+ 0) has_label=true ;;
1575
+ 1) has_label=false ;;
1576
+ *) die "could not scan #$issue's labels for in-progress (grep exited $rt_gp_rc), so whether it can be released is unknown" ;;
1577
+ esac
1578
+
1579
+ if [ "$apply" = false ]; then
1580
+ echo "$NAME: DRY RUN — nothing removed. Pass --apply to act." >&2
1581
+ [ "$has_label" = true ] && echo " would: gh issue edit $issue --remove-label in-progress" >&2
1582
+ [ -n "$wt" ] && printf ' would: git worktree remove %s\n' "$wt" >&2
1583
+ [ "$has_branch" = true ] && echo " would: git update-ref -d refs/heads/$branch <its current tip>" >&2
1584
+ else
1585
+ # Label LAST. The two local deletes are the ones that refuse — that refusal is
1586
+ # the dirty check recomputed by git at the moment of the delete, so it is
1587
+ # expected, not exceptional. Dropping the label first meant every such refusal
1588
+ # left in-progress already gone: with the worktree still standing the ticket
1589
+ # read free to candidates.mjs while re-claiming failed on the existing branch.
1590
+ # Run them first and a refusal leaves the claim exactly as it was, label and
1591
+ # all, which reads as still taken — the direction that costs nothing.
1592
+ if [ -n "$wt" ]; then
1593
+ # No --force, ever. A refusal is a finding to report, never something to
1594
+ # force past. Quote git's own reason: this fires precisely when something
1595
+ # appeared that the checks above did not see, so naming a cause here would
1596
+ # be a guess.
1597
+ printf '$ git worktree remove %s\n' "$wt" >&2
1598
+ # Measure on the REFUSAL only. git's two deletes are ordered, not atomic, so
1599
+ # a non-zero rc tells us a step failed and nothing about which — that is the
1600
+ # whole of #208. A zero rc is different in kind: both deletes completed, and
1601
+ # `Released` restates git's own success rather than inferring past a
1602
+ # failure. Re-measuring here would also make the happy path answerable by a
1603
+ # probe that can return Indeterminate, refusing releases that plainly worked.
1604
+ if ! err=$(git worktree remove "$wt" 2>&1); then
1605
+ release_outcome "$wt"
1606
+ halt "git worktree remove refused $wt: $(printf '%s' "$err" | tr '\n' ' ')"
1607
+ fi
1608
+ wt_outcome=Released
1609
+ fi
1610
+
1611
+ if [ "$has_branch" = true ]; then
1612
+ # Recount at the delete, because a delete call carries no opinion of its
1613
+ # own here any more than `-D` used to. `tip` is read ONCE, before the
1614
+ # recount and before the delete, and every measurement below reads off
1615
+ # that frozen SHA rather than the mutable ref: the recount counts commits
1616
+ # reachable from $tip, not from refs/heads/$branch, so nothing that
1617
+ # happens after this line can move what the recount already answered.
1618
+ # The delete then closes on $tip too — `git update-ref -d
1619
+ # refs/heads/$branch $tip` refuses unless the ref STILL equals $tip at
1620
+ # that exact moment. That is the compare-and-swap `git branch -D` could
1621
+ # not offer: `-D` deletes whatever the ref currently holds, so a commit
1622
+ # landing between the old recount and the old call — both here, plus the
1623
+ # milliseconds `-D` itself needed to run — was still force-deleted at
1624
+ # exit 0. Reading $tip first and comparing everything against it,
1625
+ # including the delete, turns "recount, then hope nothing moved before
1626
+ # the call" into "delete only if nothing moved". Measured against $base,
1627
+ # not local HEAD, so it answers the safety question without
1628
+ # reintroducing the staleness `-d` fails on (#760). The `git cherry` half
1629
+ # is deliberately not recounted: a commit that landed in the window is
1630
+ # ahead of $base by construction, and one cherry would mark `-` is
1631
+ # patch-equivalent to something already upstream.
1632
+ tip=$(git rev-parse --verify "refs/heads/$branch") ||
1633
+ halt "cannot read $branch's tip at the delete"
1634
+ n=$(git rev-list --count "$base_rev..$tip") ||
1635
+ halt "cannot recount commits on $branch against $base at the delete"
1636
+ [ "$n" -eq 0 ] ||
1637
+ halt "$branch gained $n commit(s) since the checks — not deleted"
1638
+
1639
+ # What the CAS does not give back: `git update-ref` is ref-only plumbing
1640
+ # and, unlike `-D`, consults no worktree at all — so the one guard the CAS
1641
+ # trades away is `-D`'s own delete-time refusal on a branch a worktree
1642
+ # holds. Replaced here with worktree.sh's `wt_holding` over the listing,
1643
+ # re-read fresh rather than trusted from the scan that computed `$wt`
1644
+ # above (and the main-checkout guard beside it): both of those answered
1645
+ # this question before the `gh issue view` call, and a `git worktree add`
1646
+ # for this exact branch landing after that scan and before this line
1647
+ # checks it out somewhere neither one ever saw. This still leaves its own,
1648
+ # smaller, check-then-act window between the re-read below and the
1649
+ # `update-ref` call itself — narrower than the one it replaces, for the
1650
+ # same reason the recount above narrows rather than closes: it is a
1651
+ # separate git invocation, and nothing here can ask `update-ref` to verify
1652
+ # it atomically with the delete the way `-D` verified its own.
1653
+ #
1654
+ # What that window can cost, per the ruling on #1330 (Q2): a checkout
1655
+ # landing in it leaves that worktree holding a deleted branch, which
1656
+ # breaks the worktree. It cannot lose a commit. A commit made there before
1657
+ # the delete moves the ref off $tip, and the compare-and-swap below then
1658
+ # refuses. Measured, git 2.50.1: with a commit made in the window,
1659
+ # `update-ref -d` exits 1 on `is at <new> but expected <tip>` and the
1660
+ # branch keeps the commit; with none, the delete lands and that worktree
1661
+ # reads `No commits yet` on its branch.
1662
+ #
1663
+ # Held by either route `-D` refused on, not only the porcelain `branch`
1664
+ # line: a worktree stopped mid `rebase -i` or mid `git bisect` on this
1665
+ # branch is listed `detached`, with no `branch` line, while git still
1666
+ # counts the branch as its own. Measured, git 2.50.1: `-D` refused both,
1667
+ # a listing-only check let the delete through, and the sibling's `rebase
1668
+ # --continue` / `bisect reset` then failed on the missing ref. `wt_holding`
1669
+ # reads those detached worktrees' rebase/bisect state out of their admin
1670
+ # dirs, and halts here as unknown — never passes as "not held" — on any
1671
+ # of three shapes it cannot resolve: an admin dir it cannot read even
1672
+ # once the worktree's own directory is confirmed gone and it has looked
1673
+ # in this repo's own registry for it (a worktree `rm -rf`'d out from
1674
+ # under git), a listed path it cannot hand back to git byte for byte, or
1675
+ # a porcelain record naming neither `branch` nor `detached` at all — a
1676
+ # worktree whose admin `HEAD` holds garbage, not a ref. #2218, ADR 0018
1677
+ wt_listing || halt "cannot re-read the worktree list to check $branch before the delete: $wt_err"
1678
+ if wt_holding "refs/heads/$branch"; then cas_rc=0; else cas_rc=$?; fi
1679
+ case $cas_rc in
1680
+ 0) halt "$branch $wt_holder_how in worktree $wt_holder — not deleted" ;;
1681
+ 1) ;;
1682
+ *) halt "cannot tell whether $branch is held by worktree $wt_holder — not deleted" ;;
1683
+ esac
1684
+
1685
+ # update-ref, authorized by the `ahead` and `git cherry` guards above,
1686
+ # this recount, and the worktree check above — and carrying its own
1687
+ # compare-and-swap on $tip on top, which `-D` never had. reap.sh
1688
+ # authorizes its own [gone] deletes with `git cherry` ALONE — not this
1689
+ # pairing. `-d` measures against HEAD and the branch's upstream, and a
1690
+ # claim has no upstream until its first push (claim-ticket.sh passes
1691
+ # --no-track, #760), so `-d` falls back to local HEAD alone and refuses a
1692
+ # pristine claim whenever local main is behind origin/main —
1693
+ # half-releasing it: worktree deleted, branch stranded, in-progress still
1694
+ # on the issue. Measured.
1695
+ echo "\$ git update-ref -d refs/heads/$branch $tip" >&2
1696
+ if ! err=$(git update-ref -d "refs/heads/$branch" "$tip" 2>&1); then
1697
+ halt "git update-ref -d refused $branch: $(printf '%s' "$err" | tr '\n' ' ')"
1698
+ fi
1699
+ done_branch=true
1700
+ fi
1701
+
1702
+ if [ "$has_label" = true ]; then
1703
+ echo "\$ gh issue edit $issue --remove-label in-progress" >&2
1704
+ gh issue edit "$issue" --remove-label in-progress >/dev/null ||
1705
+ halt "could not drop in-progress from issue $issue"
1706
+ fi
1707
+ # Housekeeping, and the final statement under `set -e`: unchecked, a prune
1708
+ # failure exited 1 out of a release that had fully succeeded — the code this
1709
+ # script uses for "NOT released, nothing was touched" — before printing any
1710
+ # receipt. Nothing about the release depends on it, so it cannot decide the
1711
+ # exit status.
1712
+ git worktree prune || echo "$NAME: git worktree prune failed; the release itself is done" >&2
1713
+ fi
1714
+
1715
+ printf '{"issue":%s,"branch":"%s","branchRewritten":%s,"worktree":"%s","worktreeRewritten":%s,"label":%s,"released":true,"applied":%s,"blockers":[]}\n' \
1716
+ "$issue" "$branch_j" "$branch_rw" "$wt_j" "$wt_rw" "$has_label" "$apply"