@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,1134 @@
1
+ #!/bin/sh
2
+ # Is this worktree safe to rebase, and what would a careless resolution eat?
3
+ #
4
+ # A rebase resolved the wrong way silently reverts work already in main. It looks
5
+ # like an ordinary conflict resolution and passes CI, because the branch's own
6
+ # tests never covered what it undid.
7
+ #
8
+ # This REFUSES; it does not repair. Choosing the resolution is judgement and
9
+ # stays with the caller. Exit 0 safe, 1 refused, 2 unanswerable.
10
+ set -eu
11
+
12
+ # Byte semantics for every tool below, and not a stylistic pin. `tr` is
13
+ # locale-sensitive: under a UTF-8 locale BSD tr exits 1 on a byte that is not
14
+ # valid UTF-8, wherever in the line it sits. `tr` is not the only carrier, and
15
+ # the others are pickier: `sed` exits 1 emitting nothing at all, but only on
16
+ # some positions — measured under `LANG=en_US.UTF-8` with LC_ALL unset,
17
+ # `printf 'b\377ad.txt\n' | sed 's/^/x: /'` gives `sed: RE error: illegal byte
18
+ # sequence` at rc 1 while `printf 'bad\377path.txt\n' | sed 's/^/x: /'`
19
+ # renders it at rc 0, so a fixture proving sed immune proves only that its
20
+ # byte landed somewhere sed tolerates. `paste -sd, -` truncates its whole
21
+ # output at the byte while still exiting 0.
22
+ #
23
+ # `awk` is NOT immune, and reap.sh's own #614 fixture measured the earlier
24
+ # claim here false: it is byte-identical only when every rule matches at an
25
+ # ANCHOR before the bad byte, never needing to convert it — a rule that must
26
+ # SCAN PAST the byte to decide dies instead (BWK awk, macOS: rc 2, `towc:
27
+ # multibyte conversion failure`), and under `set -eu` that death aborts the
28
+ # whole script rather than mis-scoring one record. Reachable only from a
29
+ # fetched tree — a Linux- or latin-1-authored commit — since APFS refuses to
30
+ # hold the name locally. #582.
31
+ #
32
+ # What that cost was measured on the pipeline that used to split merge-tree's
33
+ # output: PIPESTATUS `1 0 0` — its first stage exiting 1 and truncating, the
34
+ # two behind it exiting 0 on the short input it handed them. The real status
35
+ # sat in a non-final slot, where `set -e` cannot see it and where no `|| die`
36
+ # was watching either, so a conflicting path carrying such a byte dropped every
37
+ # path after it and reported `atRisk: []` at exit 0: a FALSE SAFE from the one
38
+ # tool whose whole job is to say whether a rebase would eat a commit. That
39
+ # split is now a single byte-oriented reader whose status nothing discards
40
+ # (#583), so this pin is no longer the only thing standing between that byte
41
+ # and a false safe there. Nor is it anywhere else: the `sed` and `tr` below
42
+ # that render a path or git's own diagnostic to stderr used to take the audit
43
+ # down with them on that byte, at the exit status that means dirty, and since
44
+ # #1160 each renders through a guard (`render`, and the fold in the stash
45
+ # branch) whose failure cannot reach the verdict. What the pin still buys is
46
+ # those renders WORKING: unpinned, BSD sed exits emitting nothing and BSD tr
47
+ # exits truncating, so the operator loses the diagnostic while the payload and
48
+ # the exit status stay correct. That is now the whole cost of removing it here,
49
+ # and no-undo-audit.test.mjs' invalid-UTF-8 case is what measures it — grep
50
+ # this file for those renders; json.sh's escapers do not rely on this pin,
51
+ # pinning the locale on each call instead.
52
+ #
53
+ # Global rather than per-site, unlike inflight.sh's five: this script sorts
54
+ # nothing, folds no case, and uses a `[a-z]` range nowhere. It does hold ONE
55
+ # POSIX class — `${back%"${back##*[![:space:]]}"}`, where the worktree-linkage
56
+ # check trims `$gd/gitdir` — and that class IS locale-sensitive, measured: a
57
+ # trailing NBSP is stripped under `en_US.UTF-8` and kept under `C`. Neither
58
+ # locale can reach it here, because a `gitdir` file always ends `.git` and
59
+ # `$(cat …)` has already eaten the trailing newline, so the last non-space byte
60
+ # is always `t`. That one site is why this paragraph says "one, unreachable"
61
+ # where the five sibling scripts' copies say "none" — two of theirs now name a
62
+ # `*[!0-9]*` range instead, this one is the POSIX-class exception.
63
+ # locale-pin-prose.test.mjs holds all six inventories as lists and fails if the
64
+ # code drifts from them (#612); this paragraph is why the entry below exists.
65
+ # Non-ASCII paths are untouched either way:
66
+ # every scrub set below is \001-\037 and every byte of a multi-byte UTF-8
67
+ # sequence is >= \200.
68
+ export LC_ALL=C
69
+
70
+ # Below the locale pin, not above it with `set -eu`: `unset` touches no
71
+ # byte-sensitive tool, but locale-pin-prose.test.mjs treats ANY line here that
72
+ # is not a comment, a blank, or `set -[eux]+` as work the pin must sit above,
73
+ # and refuses on principle rather than on this line's own behaviour. Same
74
+ # placement, same reason, as release-ticket.sh's copy.
75
+ #
76
+ # The `--show-prefix` gate below is the guard against exactly this class —
77
+ # "can git operate here" is not "is this the tree it answers about" — and the
78
+ # environment walks straight past it. Both halves measured (#1020).
79
+ #
80
+ # GIT_WORK_TREE outranks `-C`, so `git -C "$wt" rev-parse --show-prefix`
81
+ # answers about the AMBIENT tree. When that tree is not an ancestor of the
82
+ # cwd, git returns an EMPTY prefix — which is the exact value the gate reads
83
+ # as "$wt IS the root" — and the `status --porcelain -uall` below then
84
+ # compares $wt's index against the ambient tree's files. Measured, with the
85
+ # ambient tree holding a copy of the branch's tracked content: a worktree
86
+ # carrying an uncommitted file comes back `clean: true` at rc 0, and the
87
+ # rebase this script gates is authorised over work that exists nowhere else.
88
+ # That is verbatim the failure the gate's own comment describes, reached
89
+ # through a door the gate cannot close.
90
+ #
91
+ # GIT_DIR reaches the linkage check instead: `$wt`'s healthy `.git` is
92
+ # compared against the ambient repository's worktree and blamed for the
93
+ # mismatch. Measured: exit 2 naming `$wt`'s `.git` as the fault, on a
94
+ # worktree whose linkage is perfect — a rebase blocked, and the operator sent
95
+ # to repair a file that was never broken.
96
+ unset GIT_DIR GIT_WORK_TREE
97
+
98
+ NAME=no-undo-audit
99
+ # `printf`, not `echo`: 11 of these messages interpolate `$wt`, a
100
+ # caller-supplied path, and `emit` below is the one place they all route
101
+ # through. Reached by a CALL, not by a second copy of `emit`'s body spelled
102
+ # here, which is what this line used to be: hand-copied the guard was
103
+ # correct and stayed correct, but #1571 then had to edit both copies to add
104
+ # the SIGPIPE trap, and a call is the only form that cannot be missed that
105
+ # way (#1684).
106
+ #
107
+ # What `die` needs from that guard is the header's rule below applied to the
108
+ # one write whose statement MUST still reach an exit: `set -e` reads the
109
+ # write's status before `exit` is ever reached, and with fd 2 closed that
110
+ # status is 1 — REFUSED on this script — so every unanswerable question
111
+ # blamed the worktree instead of saying it could not be answered (#1514,
112
+ # measured: a path that is not a worktree, `2>&-`, exit 1 where the contract
113
+ # says 2).
114
+ #
115
+ # `emit` is defined below, after `render`, and a shell resolves a function
116
+ # name at CALL time: every `die` call site sits below that definition, so
117
+ # the forward reference holds. One hoisted above it would exit 127 (`emit:
118
+ # not found`) rather than the 2 this script's contract promises — `dieSites`
119
+ # in the test file asserts the ordering rather than leaving it here.
120
+ die() { emit "$NAME: $1"; exit 2; }
121
+
122
+ # THE RULE FOR EVERY STDERR WRITE IN THIS SCRIPT, and why each one is
123
+ # guarded. Exit 0 is safe, 1 is refused, 2 is unanswerable, and a caller
124
+ # branches on which. A diagnostic answers nothing — it shows a human what the
125
+ # run already determined — so its write must not reach `set -e`, which ends
126
+ # the script on that write's own status. Both `printf` and `echo` exit 1 on a
127
+ # failed write, and 1 out of here is the dirty-worktree refusal: with fd 2
128
+ # closed, a clean tree came back "commit the worktree before rebasing", from
129
+ # the one tool whose job is to say whether a rebase would eat a commit.
130
+ # Measured before the fix — clean tree, stdout open, `2>&-`: exit 1 (#1514).
131
+ #
132
+ # The guard is centralized, never hand-appended per site: `render` carries
133
+ # it in a function body every caller inherits, and every other write to fd 2
134
+ # — `die`'s own included, since #1684 — goes through `emit()` (defined after
135
+ # `render`), which does the same. A future call site cannot add an unguarded
136
+ # `>&2` write without also adding a new function to sidestep it, and there
137
+ # are two guard bodies to keep in step rather than three. `|| :` is the third
138
+ # piece of `render`'s guard, and it is what `emit()` carries on its own: these
139
+ # sites have nothing to fall back TO, the line that could not be written IS
140
+ # the message, so there is no second, shorter thing to say about it.
141
+ # `render` needs its extra piece because a dropped LIST reads as an empty
142
+ # one — a finding silently downgraded — while a dropped single line reads as
143
+ # nothing at all, and the payload on stdout still carries every finding.
144
+ #
145
+ # The guard goes on the write itself, never on the surrounding statement:
146
+ # most call sites sit in `if`/`elif` chains or in a function whose later
147
+ # lines must still run. It covers a write that FAILS, which is what a closed
148
+ # or full fd 2 produces. A SIGNAL is a different failure class: `printf` is a
149
+ # shell builtin, so its write to fd 2 runs IN THIS PROCESS rather than a
150
+ # forked child, and the default disposition of SIGPIPE is to kill whatever
151
+ # receives it — on the spot, mid-syscall, before the interpreter ever returns
152
+ # to evaluate the `||` that follows. `|| :` cannot catch a kill; it can only
153
+ # catch a status, and a killed process never produces one for this shell to
154
+ # read (#1571, measured: a reader that exits before the script finishes
155
+ # writing — not merely a closed fd — took the whole process out at 141,
156
+ # outside the script's own 0/1/2 contract).
157
+ #
158
+ # The fix is `( trap '' PIPE; write )`, not a script-wide `trap '' PIPE`.
159
+ # Ignoring the signal turns the write's own failure back into a status — the
160
+ # write's fd 2 syscall returns EPIPE instead of delivering a kill — which is
161
+ # exactly the shape `|| :` already exists to swallow, so the fix opens no new
162
+ # failure path; it only makes the existing one reachable from a signal too.
163
+ # Confined to a subshell rather than the whole process for two measured
164
+ # reasons. First, it must leave every pipeline inside this script exactly as
165
+ # exposed to SIGPIPE as it is today: `render`'s own pipe below already
166
+ # tolerates it correctly, because `sed` there is exec'd rather than built in,
167
+ # and a forked child's death by signal reaches `set -e` as an ordinary
168
+ # nonzero status — ignoring PIPE for the whole process would reach past that
169
+ # pipe into every subprocess this script forks, which this script has no way
170
+ # to audit is equally inert under it. Second: macOS's `/bin/sh` (bash 3.2.57)
171
+ # does not recover cleanly once a script-wide `trap '' PIPE` has absorbed one
172
+ # EPIPE on a builtin write — measured, a LATER command substitution came back
173
+ # holding an earlier diagnostic line instead of the command it actually ran.
174
+ # A trap set inside a subshell never outlives it: it is gone the instant that
175
+ # subshell exits, which is also the instant the write it guards finishes.
176
+
177
+ # Every operator-facing render that pipes a captured value through an external
178
+ # tool goes through here — bar the stash-diagnostic fold below, which folds
179
+ # rather than indents and carries the same guard inline — and the point of it
180
+ # is that a render CANNOT decide the verdict (#1160).
181
+ # Written bare — `printf '%s\n' "$v" | sed 's/^/ /' >&2` — the pipeline's
182
+ # status is sed's, `set -eu` takes it, and the script exits with it: on this
183
+ # script exit 1 is the dirty-worktree refusal, so a render fabricated that
184
+ # refusal over a worktree the run had already printed `clean` for, with the
185
+ # payload never emitted and nothing naming a cause. Reachable with no shim at
186
+ # all, on the byte and the position the header above measures: with the pin
187
+ # deleted, a conflicting path spelled `b\377ad.txt` gave
188
+ # `sed: RE error: illegal byte sequence`, nothing rendered, and exit 1 over a
189
+ # worktree the same run had just reported clean. Same shape as the
190
+ # `|| die`s further down, opposite resolution: those guard statements that
191
+ # ANSWER something and so must reach exit 2, this one guards statements that
192
+ # answer nothing and so must reach no exit at all.
193
+ #
194
+ # Three pieces, each covering what the others cannot. The first `||` keeps the
195
+ # verdict out of the render's hands. The second is a message that keeps the
196
+ # failure out of silence — a bare `|| :` fixes the status and leaves a lost
197
+ # conflict list indistinguishable from an empty one, which is the same
198
+ # silent-failure class as the abort. The third is for the render whose
199
+ # fallback ALSO fails, stderr itself being gone: an unguarded `||` branch is
200
+ # one more command whose status `set -e` reads, and it would abort for the
201
+ # reason this function exists to remove. The second and third pieces used to
202
+ # be spelled out here, a hand copy of `emit`'s own body; now they are a CALL
203
+ # to it (#1685), for the same reason `die` stopped carrying its own copy
204
+ # (#1684) — a hand-copied guard is correct only until the next edit to the
205
+ # original forgets to touch both.
206
+ #
207
+ # `$1` lands in sed's REPLACEMENT text, where `&` and `\` are metacharacters.
208
+ # Every prefix passed below is a literal in this file and holds neither; a
209
+ # caller-derived prefix would have to be escaped first.
210
+ render() { # render <line-prefix> <text> <what-the-text-is>
211
+ printf '%s\n' "$2" | sed "s/^/$1/" >&2 \
212
+ || emit "$NAME: could not render $3 to stderr; the payload and the exit status stand"
213
+ }
214
+
215
+ # Every plain diagnostic below writes one already-assembled line with no
216
+ # external pipeline to fail on its own account — unlike `render`, which pipes
217
+ # through `sed` and so needs its own fallback piece. Routed through one
218
+ # function rather than a `|| :` hand-appended at each call site, so a future
219
+ # site cannot add an unguarded write without also adding a new function to
220
+ # sidestep this one.
221
+ emit() { ( trap '' PIPE; printf '%s\n' "$1" >&2 ) || :; }
222
+
223
+
224
+ # The escaping helpers (#119). json.sh's header holds the sourcing contract and
225
+ # the measurements behind it; only what is true of THIS script is repeated here.
226
+ # Below `export LC_ALL=C` deliberately: locale-pin-prose.test.mjs allows only
227
+ # comments, blanks, a shebang or a `set -` line above that pin, and `json_lib=`
228
+ # is none of them.
229
+ #
230
+ # Exit 1 from this script is a verdict too: `REFUSED — commit the worktree
231
+ # before rebasing`. A library that merely went missing would report a dirty
232
+ # worktree without having looked at one, blocking a rebase that was safe to
233
+ # start, so `[ -r ]` has to fire before the `.` can kill the shell.
234
+ json_lib="$(dirname "$0")/json.sh"
235
+ [ -r "$json_lib" ] || die "cannot read $json_lib — refusing to act without the JSON escaping helpers"
236
+ # shellcheck source-path=SCRIPTDIR
237
+ # shellcheck source=json.sh
238
+ . "$json_lib" || die "$json_lib failed to load"
239
+
240
+ # Every string that reaches the JSON goes through `jstr`/`jarr` from json.sh —
241
+ # `$wt` is argv and therefore a filesystem path, which may hold a `"`, a `\`
242
+ # or a control byte that git's ref rules would reject. The rule list, its
243
+ # ordering and the jarr/jstr split live in json.sh, once, rather than here and
244
+ # in inflight.sh and in release-ticket.sh — five copies of the same rules
245
+ # before the extraction, counting jarr and jarr_rewritten (#119).
246
+ #
247
+ # This script is the only caller that reaches the multi-line machinery: `$wt`
248
+ # is the one value here that can carry a newline, which is why json.sh's slurp
249
+ # is not dead code even though no other consumer can feed it one.
250
+ [ $# -eq 2 ] || die "usage: no-undo-audit.sh <worktree> <branch>"
251
+ wt=$1
252
+ branch=$2
253
+ base=${BASE_REF:-origin/main}
254
+ # Only a remote-tracking ref is accepted — the accept-list release-ticket.sh:229
255
+ # and reap.sh:156 carry, and the one this script had none of. worktree-audit.sh
256
+ # carries the same accept-list (worktree-audit.sh:131) and already applies the
257
+ # #1329 shorthand fix: :156-159 qualify `$base` into `$base_rev`, and both its
258
+ # rev-parse (:161) and its rev-list (:253) read `$base_rev`, never the bare
259
+ # shorthand. Its stake is smaller, though: being audit-only,
260
+ # worktree-audit.sh only ever prints a report, while this
261
+ # script GATES something consequential: the comment below
262
+ # (see "the merge bot leans on this audit to authorize a REBASE") says a caller
263
+ # uses this audit's exit status to decide whether to replay unpushed work. A
264
+ # wrong BASE_REF here does not just make a report wrong, it can feed that
265
+ # decision a false "clean" — the blast radius release-ticket.sh restricted
266
+ # BASE_REF for, so this script restricts it too rather than leaving it as
267
+ # permissive as an audit-only reader could afford. The qualify step below
268
+ # unconditionally prepends `refs/remotes/` to whatever $base is, so a spelling
269
+ # that used to resolve fine before this fix — a bare `main`, a raw SHA, `HEAD`,
270
+ # `refs/heads/main` — would otherwise turn into a ref nothing asked to exist,
271
+ # and die below with a message that blames a guess for a qualification this
272
+ # script chose to make.
273
+ #
274
+ # The die names the two spellings the list takes rather than calling them "a
275
+ # remote-tracking ref", because the list is narrower than that phrase in one
276
+ # direction and wider in the other: `refs/remotes/upstream/main` is accepted
277
+ # and `upstream/main` is refused (both measured), so a second remote's
278
+ # shorthand would otherwise be refused for not being something it is.
279
+ case "$base" in
280
+ origin/*|refs/remotes/*) ;;
281
+ *) die "BASE_REF must be spelled origin/<branch> or refs/remotes/<path>, got '$base'";;
282
+ esac
283
+
284
+ # release-ticket.sh's SECOND guard — `*/"$branch") die` — is carried too, for
285
+ # the reason release-ticket.sh:233 gives and not reap.sh:161's reason for
286
+ # leaving it out. `origin/$branch` IS a remote-tracking ref, so the accept-list
287
+ # above passes it and nothing else here refuses it, and every measurement below
288
+ # then asks whether the branch conflicts with ITSELF: merge-tree reports no
289
+ # conflicting files, the at-risk list stays empty, and the audit prints
290
+ # `conflicts: []`, `atRisk: []` at exit 0 for a worktree whose branch really
291
+ # does add/add-conflict with the real origin/main. Measured on a bare-origin
292
+ # fixture: the same tree and the same commit report `conflicts: ["conflict.txt"]`
293
+ # with one at-risk main commit when BASE_REF is unset, and the empty pair above
294
+ # when it is `origin/<the audited branch>`. That is the false "clean" the
295
+ # comment above says must not reach a rebase decision. reap.sh can leave the
296
+ # guard out because its `fetch --prune` drops the stale refs that make the same
297
+ # spelling vacuous there; this script fetches nothing — the only fetch it names
298
+ # is the advice in the `$branch_rev does not resolve` die below.
299
+ case "$base" in
300
+ */"$branch") die "BASE_REF must not name the audited branch, got '$base'";;
301
+ esac
302
+
303
+ # `origin/main` is a SHORTHAND, and git resolves a shorthand through its own
304
+ # disambiguation order (gitrevisions: refs/<name>, refs/tags/<name>,
305
+ # refs/heads/<name>, refs/remotes/<name>, …), in which refs/remotes/origin/
306
+ # main comes LAST. A local TAG or BRANCH literally named `origin/main`
307
+ # outranks the real remote-tracking branch, so every measurement against
308
+ # the bare shorthand below would answer about that ref's target instead — at
309
+ # rc 0, with git's own `warning: refname 'origin/main' is ambiguous.` on
310
+ # stderr as the only tell (measured), which this script reads nothing of and
311
+ # which an unattended caller has no one to read. The same class
312
+ # release-ticket.sh:243 and reap.sh:174 already found in the same default.
313
+ # Fix: qualify to the full refs/remotes/ path, where there is nothing left to
314
+ # disambiguate, unless it is already qualified. The accept-list above is
315
+ # what makes this qualify step safe rather than a guess — BASE_REF could
316
+ # otherwise name a tag, a SHA or a local branch, leaving no prefix that is
317
+ # always correct. `$base` itself stays unqualified in this script's `die`
318
+ # text, where the shorthand spelling is what an operator expects to read;
319
+ # where the two spellings can disagree the die names BOTH, so a refusal
320
+ # earned by `refs/remotes/<x>` is not read as a refusal about `<x>` — a
321
+ # local ref shadowing the shorthand makes "<x> does not resolve" false of
322
+ # the very spelling the operator typed. The trace lines below use
323
+ # `$base_rev` instead, because this script's own rule for those lines (see
324
+ # the `status --porcelain` trace above) is that they echo the command AS
325
+ # RUN, and the command that runs is against `$base_rev`.
326
+ case "$base" in
327
+ refs/remotes/*) base_rev=$base;;
328
+ *) base_rev="refs/remotes/$base";;
329
+ esac
330
+
331
+ # `$branch` is argv — the script's own second positional (`no-undo-audit.sh
332
+ # <worktree> <branch>`) — not an operator-typed ref spelling the way BASE_REF
333
+ # is. BASE_REF earned an accept-list before it earned a qualify step because
334
+ # qualifying an arbitrary spelling was a guess: a bare `main`, a SHA or `HEAD`
335
+ # all resolved fine unqualified, and prepending `refs/remotes/` to any of
336
+ # those would have manufactured a ref nothing asked for. `$branch` carries
337
+ # none of that ambiguity — every site below has only ever meant "the branch
338
+ # named `$branch` in the `origin` remote", so there is no second shape a
339
+ # caller could have meant and no guess an accept-list would be needed to make
340
+ # safe first. The qualify step is unconditional too, unlike base_rev's
341
+ # two-armed case: `$branch` is a bare short name off the usage line, never
342
+ # itself a `refs/remotes/...` path, so there is nothing already-qualified to
343
+ # detect.
344
+ branch_rev="refs/remotes/origin/$branch"
345
+
346
+ [ -d "$wt" ] || die "worktree $wt does not exist"
347
+ # "Can git operate here" is NOT "is this the tree it answers about", and only
348
+ # the second licenses the status below — every git command here walks UP,
349
+ # `status` included. Delete the worktree's `.git` and git resolves the ENCLOSING
350
+ # repo at rc 0, so a gate asking only the first lets the run through (a bare
351
+ # `rev-parse --git-dir` stood here and did exactly that); the status below then
352
+ # answers for that repo, and with a clean parent (`.worktrees/` gitignored, the
353
+ # fleet's own layout) the answer is EMPTY at rc 0 while the uncommitted work
354
+ # sits on disk. `clean` for a tree nothing looked at, out of a script whose
355
+ # whole job is gating an irreversible action. The `die` on a failing status
356
+ # cannot catch it: this failure is a SUCCESSFUL command answering about another
357
+ # repository.
358
+ #
359
+ # `--show-prefix` is where git states which tree it actually resolved: the path
360
+ # of the directory asked about, RELATIVE to that tree's root. Empty iff `$wt` IS
361
+ # the root, `.worktrees/9-x/` when git walked up. Ask git for the identity
362
+ # rather than infer it from what `.git` looks like on disk.
363
+ #
364
+ # Inferring from disk is one byte from a manufactured clean in every spelling:
365
+ # `-e "$wt/.git"` calls an EMPTY `.git` directory present; `-f "$wt/.git"` alone
366
+ # refuses every main checkout, whose `.git` is a DIRECTORY and which `$wt` may
367
+ # be, being any worktree the caller names; `-e "$wt/.git/HEAD"` calls a `.git`
368
+ # directory holding a lone HEAD present. git wants HEAD *and* `objects/` *and*
369
+ # `refs/` and walks up past anything less — including a REAL `.git` whose HEAD
370
+ # an interrupted write truncated (measured, git 2.50.1).
371
+ #
372
+ # The rc is captured, not swallowed: `--show-prefix` is empty both when `$wt` is
373
+ # the root and when the command FAILS, so `[ -z ]` over a swallowed failure
374
+ # would admit exactly what this refuses. Capturing it is also what retired the
375
+ # `--git-dir` gate rather than leaving it above: the two return the SAME rc on
376
+ # every shape (measured — plain directory, garbage `.git`, dangling symlink,
377
+ # unsearchable worktree all 128 for both; main checkout, linked worktree, bare
378
+ # repo, deleted/empty/lone-HEAD `.git` all 0), so keeping both left one gate
379
+ # that could never fire and an ordering dependency that did not exist.
380
+ #
381
+ # `--show-toplevel` compared RAW against `$wt` is the spelling to avoid for this
382
+ # gate: it needs a string compare, and `$wt` arrives relative (claim-ticket.sh's
383
+ # `wt=".worktrees/$issue-$slug"`), through a
384
+ # symlink, or under a macOS tmpdir git reports back through `/private` — three
385
+ # false-refusal classes `--show-prefix` cannot have, comparing nothing. It is
386
+ # asked further down all the same, against a CANONICAL `$wt`, for the one claim
387
+ # `--show-prefix` cannot make: which working tree git answers for once
388
+ # `core.worktree` has moved it (#2040). git's
389
+ # `prunable` is no use either: it marks a worktree whose DIRECTORY is gone, and
390
+ # stays silent for one still holding work whose linkage broke (measured).
391
+ prefix=$(git -C "$wt" rev-parse --show-prefix) \
392
+ || die "$wt is not a git worktree"
393
+ [ -z "$prefix" ] \
394
+ || die "git answers for the repo above $wt, not $wt — cannot tell a clean worktree from a dirty one"
395
+
396
+ # --show-prefix answers "is $wt the root git resolved" — for a `.git` FILE that
397
+ # is a question about the file's own LOCATION, since that is where git starts
398
+ # walking up from. It says nothing about "is the git-dir behind that file
399
+ # actually $wt's". A `.git` file rewritten to name a SIBLING worktree's admin
400
+ # dir still resolves its root to $wt (the file's location did not move) while
401
+ # every git command below — `status` included — answers against the sibling's
402
+ # HEAD and index. #189.
403
+ #
404
+ # So the second claim is asked separately: which git dir answered, and which
405
+ # worktree does THAT dir belong to. Never keyed on the string `--git-dir`
406
+ # returns without `--path-format=absolute`: that is the literal `.git` for a
407
+ # main checkout AND — measured, git 2.50.1 — for a LINKED worktree whose `.git`
408
+ # is a SYMLINK to another worktree's admin dir, so a guard exempting `.git` as
409
+ # "the main worktree, nothing to verify" exempts the #189 spoof spelled as a
410
+ # symlink instead of a `gitdir:` file. Absolute, and compared as paths: the one
411
+ # place in the script that compares paths, because unlike `--show-prefix` there
412
+ # is no rc/emptiness shortcut for "do these two name the same tree".
413
+ #
414
+ # `pwd -P` puts all three in ONE spelling. Only `$wt` needs it to be correct
415
+ # today: it arrives as the caller typed it — relative (claim-ticket.sh's
416
+ # `wt=".worktrees/$issue-$slug"`), or
417
+ # through a symlink — and never goes through git, while git's
418
+ # `--path-format=absolute` answers came back already resolved on every shape
419
+ # measured, symlinked `$wt` and symlinked `.git` included (measured: dropping
420
+ # `pwd -P` from `common` alone changes no verdict, git 2.50.1). It is on `$gd`
421
+ # and `common` as insurance, and the reason to apply that insurance to BOTH or
422
+ # neither is that a spelling difference between them is not a false refusal on
423
+ # one shape but on every main checkout. `$wt_real` stays canonical only for
424
+ # resolving `$wt` (symlinks, relative paths), not Unicode normalization, so
425
+ # both owner compares below compare as directories (`-ef`) for the same
426
+ # NFC/NFD reason as `$top` below (#2095, detailed there); the `core.worktree`
427
+ # check after them already compares directories, so its own correctness does
428
+ # not depend on `$wt_real`'s spelling either.
429
+ #
430
+ # `--git-common-dir` is what says which shape $gd is. A LINKED worktree gets
431
+ # its own per-worktree admin dir, so $gd differs from the common dir, and every
432
+ # such dir carries its OWN `gitdir` file, written by `git worktree add` and
433
+ # never touched by this script, pointing back at the worktree `.git` it belongs
434
+ # to. Resolved against the admin dir — git's own base for it, and git writes it
435
+ # RELATIVE, not absolute, whenever `worktree.useRelativePaths` is set — its
436
+ # directory must be $wt. Every other shape answers with the common dir itself:
437
+ # a main checkout, a submodule, a `--separate-git-dir` clone. There $gd IS the
438
+ # repo and has no back-pointer to read, so identity is where it sits — a git
439
+ # dir named `.git` belongs to its parent directory, and a `.git` redirected at
440
+ # the enclosing repo's own `.git` is caught by exactly that.
441
+ #
442
+ # Ceiling: a git dir that IS the common dir and is NOT named `.git` — a
443
+ # submodule's `.git/modules/<name>`, a `--separate-git-dir` target — records
444
+ # nothing naming its worktree (measured: no `gitdir`, and `core.worktree` only
445
+ # when git itself set one), so there is nothing HERE to verify, and the root
446
+ # claim above and the working-tree claim below are what stand for it.
447
+ # Admitted rather than refused: git's own linkage for those is one-directional
448
+ # by construction, and refusing turned two healthy checkouts into "ask a human"
449
+ # for having no record to check. The residual is a `.git` redirected at a
450
+ # FOREIGN repo of that shape whose working tree is $wt, which no `git worktree
451
+ # add` can produce.
452
+ #
453
+ # `core.worktree` redirection is NOT caught by either check so far, whatever an
454
+ # earlier version of this comment claimed (#2040, correcting #189's credit):
455
+ # `--show-prefix` is empty at rc 0 for every redirect shape measured, and this
456
+ # owner check passes the two it can see — `$gd` is $wt's own admin dir with its
457
+ # back-pointer intact when the redirect sits in `config.worktree`, and a foreign
458
+ # git dir not named `.git` is the ceiling's admitted shape. The canonical #135
459
+ # redirect, a foreign git dir literally named `.git`, IS refused here, by the
460
+ # `${gd%/.git}` owner compare, not by `--show-prefix`. The working-tree compare
461
+ # after this block is what refuses the rest.
462
+ #
463
+ # Both rev-parse calls keep a `|| die` the comment above says can never fire,
464
+ # for one reason the retired gate did not have: their job is to produce a path,
465
+ # not an rc. `set -e` does abort the script on a failed command substitution
466
+ # (measured: rc 128), so an unguarded one cannot reach the compare with an empty
467
+ # variable — but it would exit 128, and 128 is not one of the three verdicts
468
+ # this script's callers read. The `cd`/`pwd -P` lines below are left bare for
469
+ # the same measurement: unreachable, and `set -e` stops them regardless.
470
+ #
471
+ # `$(...)` strips EVERY trailing newline it captures, not one: a `$wt` or a
472
+ # `core.worktree` target whose real directory name itself ends in a literal
473
+ # newline byte loses that byte on whichever side of a compare below reads it,
474
+ # so two directories differing only by that byte compare equal — a redirect
475
+ # this script exists to refuse instead reads clean (measured, #2040). `git
476
+ # worktree add`/`git config core.worktree` both accept the byte as an
477
+ # ordinary path character; nothing upstream rejects it.
478
+ #
479
+ # `wt_real`, the if-branch `owner` below, and `top` further down all guard
480
+ # against it the same way: an `echo x` inside the substitution, so the ONLY
481
+ # newline `$(...)` can strip is the one `pwd`/`rev-parse` already appends to
482
+ # its own answer, then `${var%?x}` strips exactly the sentinel and the ONE
483
+ # character before it — nothing extra when the real answer has no trailing
484
+ # newline, and the one real byte restored when it does. `gd` and `common`
485
+ # stay bare: they are admin-directory paths git itself names, never a
486
+ # `core.worktree` target, and the branch they select never turns a
487
+ # mismatch INTO a match on this byte alone (measured).
488
+ gd=$(git -C "$wt" rev-parse --path-format=absolute --git-dir) \
489
+ || die "git will not name the git dir answering for $wt — cannot verify its linkage"
490
+ common=$(git -C "$wt" rev-parse --path-format=absolute --git-common-dir) \
491
+ || die "git will not name $wt's common git dir — cannot verify its linkage"
492
+ gd=$(cd "$gd" && pwd -P)
493
+ common=$(cd "$common" && pwd -P)
494
+ wt_real=$(cd "$wt" && pwd -P && echo x)
495
+ wt_real=${wt_real%?x}
496
+ if [ "$gd" != "$common" ]; then
497
+ back=$(cat "$gd/gitdir" 2>/dev/null) \
498
+ || die "$gd/gitdir is missing or unreadable — cannot verify $wt's linkage"
499
+ back=${back%"${back##*[![:space:]]}"}
500
+ owner=$(cd "$gd" && cd "$(dirname "$back")" && pwd -P && echo x) \
501
+ || die "$gd/gitdir names a directory that does not resolve — cannot verify $wt's linkage"
502
+ owner=${owner%?x}
503
+ # 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
504
+ [ "$owner" -ef "$wt_real" ] \
505
+ || die "$wt's .git names another worktree's admin dir — cannot tell a clean worktree from a dirty one"
506
+ else
507
+ owner=${gd%/.git}
508
+ # 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
509
+ [ "$owner" = "$gd" ] || [ "$owner" -ef "$wt_real" ] \
510
+ || die "$wt's .git names $gd, whose worktree is $owner, not $wt — cannot tell a clean worktree from a dirty one"
511
+ fi
512
+
513
+ # `core.worktree` moves the WORKING TREE and nothing the checks above read:
514
+ # they ask where git STARTED and which git dir answered, and a redirect changes
515
+ # neither. `git config --worktree core.worktree <dir>` on a linked worktree
516
+ # (with extensions.worktreeConfig), `git config core.worktree <dir>` on a main
517
+ # checkout, a relative `<dir>` in either, or a `.git` naming a foreign git dir
518
+ # not called `.git` whose `core.worktree` is `<dir>`: all pass both checks, and
519
+ # `status` then compares the index against `<dir>`'s files. `<dir>` holding the
520
+ # tracked content — any other checkout of the branch — reads `clean` at rc 0
521
+ # over the work sitting in $wt (measured, git 2.50.1, #2040). A `<dir>` INSIDE
522
+ # $wt is the same leak for every file outside it.
523
+ #
524
+ # `--show-toplevel` names the working tree git actually answers for, so it is
525
+ # compared against `$wt_real`, and the union of this with the checks above is
526
+ # the guard: none is dropped, since this one passes the #189 sibling spoof and
527
+ # a foreign `*/.git` whose `core.worktree` names $wt back. The raw-compare
528
+ # false refusals the `--show-prefix` comment warns about do not arise here:
529
+ # measured passing on a relative, symlinked and `/private`-less `$wt`, after
530
+ # `git worktree move`, under `worktree.useRelativePaths`, on a submodule, a
531
+ # `--separate-git-dir` clone and a `core.worktree` naming $wt itself.
532
+ #
533
+ # Compared as a DIRECTORY (`-ef`, same device and inode), never as a string,
534
+ # for reap.sh's reason (#2072): a worktree whose name is Unicode NFD-composed
535
+ # (`cafe` + U+0301), passed in the PRECOMPOSED spelling `worktree list
536
+ # --porcelain` echoes under the `core.precomposeunicode` git writes into every
537
+ # new repo on macOS, keeps that spelling through `cd && pwd -P`, while
538
+ # `--show-toplevel` answers the on-disk NFD bytes — visually identical,
539
+ # byte-different, one directory (measured, git 2.50.1, Apple Git-155, #2095).
540
+ # A byte compare refused every such healthy worktree. `-ef` answers "same
541
+ # directory" for both and for any other spelling the filesystem aliases, and
542
+ # still refuses every redirect — each names a different directory.
543
+ # POSIX.1-2017's `test` does not define `-ef`; it is a ksh-derived extension
544
+ # bash, dash and BSD sh share, and POSIX.1-2024 adds it. A `[` that cannot
545
+ # evaluate it fails, which is the refusing direction.
546
+ #
547
+ # `$top` is compared as git spells it, NOT canonicalised through `cd`, which
548
+ # `-ef` does not need and which would add two holes: a `core.worktree` naming
549
+ # a missing or unsearchable directory still answers at rc 0 (measured), so the
550
+ # `cd` fails and `set -e` exits 1 — the DIRTY verdict — over a tree nothing
551
+ # looked at; and an empty `$top` makes `cd ""` a no-op in the caller's cwd,
552
+ # which may be $wt. `-ef` over a missing or empty `$top` is false, not an
553
+ # error: the refusing direction, exit 2.
554
+ #
555
+ # Not refused, because git does not honour them and `status` reads $wt
556
+ # (measured): `core.worktree` in the COMMON config seen from a linked worktree,
557
+ # one reached through `include.path`, and one passed as GIT_CONFIG_COUNT or
558
+ # GIT_CONFIG_PARAMETERS. The check keys on git's answer, not on the config, so
559
+ # it cannot refuse a setting git ignores.
560
+ top=$(git -C "$wt" rev-parse --show-toplevel && echo x) \
561
+ || die "git will not name the working tree answering for $wt — cannot verify its linkage"
562
+ top=${top%?x}
563
+ # 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
564
+ [ "$top" -ef "$wt_real" ] \
565
+ || die "git answers for the working tree at $top, not $wt — cannot tell a clean worktree from a dirty one"
566
+
567
+ git -C "$wt" rev-parse --verify "$base_rev" >/dev/null || die "$base does not resolve as $base_rev"
568
+ # Left unchecked, merge-tree below fails silently and "no conflicting files" is
569
+ # printed for a question that was never actually answered.
570
+ #
571
+ # The message names what the guard observed and then what to DO, and stops. It
572
+ # used to name CAUSES instead — a branch never pushed, a stale remote-tracking
573
+ # ref, a caller who already prefixed the name "origin/" — which it cannot tell
574
+ # apart, and neither can git: unsuppressed, rev-parse answers the constant
575
+ # "fatal: Needed a single revision" for every one of them. A fetch is the right
576
+ # next move whichever fired, so an action survives where the cause list could
577
+ # not. --verify stays: without it a name that matches a FILE resolves, prints
578
+ # the path and exits 0, and the guard passes something that is not a ref.
579
+ git -C "$wt" rev-parse --verify "$branch_rev" >/dev/null \
580
+ || die "$branch_rev does not resolve — run 'git fetch origin' and retry"
581
+
582
+ # 1. Uncommitted work. This may exist nowhere else on disk. `|| true` here would
583
+ # turn a failed `status` into empty output and print "clean" over a dirty
584
+ # tree — and since the stash count stopped gating, nothing else would catch
585
+ # it. Unanswerable is exit 2, never exit 0. Same rule as worktree-audit.sh.
586
+ # `printf`, not `echo`, here and at every other site carrying caller text.
587
+ # This script is `#!/bin/sh`, and both dash and macOS sh expand escapes in an
588
+ # `echo` OPERAND — `\c` truncates the line and swallows its newline, so the
589
+ # next stderr line collides with it. `$wt` is a caller-supplied path, so a
590
+ # worktree named `back\clue` does it with no corruption at all. Recognised:
591
+ # `\c \t \n \b \f \r \v \\ \0`; unknown ones like `\s` pass through, which is
592
+ # why a `back\slash` fixture reads as coverage and catches nothing.
593
+ #
594
+ # The other operands are safe by construction, not by luck: `$stash` is a
595
+ # digit count or the literal `null`, and git forbids a backslash in a refname
596
+ # (`check-ref-format` rejects it, `git branch` refuses to create it), so
597
+ # `$base`, `$branch` and `$fork` cannot carry one.
598
+ #
599
+ # `-uall`: #730 (see reap.sh's branch sweep for the full explanation) — a
600
+ # bare `--porcelain` reads clean over a dirty tree under
601
+ # `status.showUntrackedFiles = no`. Load-bearing here beyond a reap: the merge
602
+ # bot leans on this audit to authorize a REBASE, and the work a rebase
603
+ # replays over may exist nowhere else. The trace line below echoes the
604
+ # command as RUN, flag included, so a reader reproducing it by hand does not
605
+ # reproduce the unsound form.
606
+ emit "\$ git -C $wt status --porcelain -uall"
607
+ porcelain=$(git -C "$wt" status --porcelain -uall) \
608
+ || die "git status failed in $wt — cannot tell a clean worktree from a dirty one"
609
+ if [ -n "$porcelain" ]; then
610
+ clean=false
611
+ render ' ' "$porcelain" "the uncommitted-work list"
612
+ else
613
+ clean=true
614
+ emit " clean"
615
+ fi
616
+
617
+ # Repo-global across worktrees, and a rebase never consumes a pre-existing entry
618
+ # — `--autostash` stores its own on top, never takes yours. So the count says
619
+ # nothing about whether THIS rebase loses THIS branch's work. Reported, never
620
+ # gated: gating refused every run in a repo holding any entry, and a check that
621
+ # always fires is one nobody reads. Read the list when it is nonzero — an entry
622
+ # labelled `on <this branch>` may be a dead member's only copy.
623
+ #
624
+ # It cannot cover the hazard it looks like it covers, either. A member running
625
+ # `git stash` to clear a dirty worktree leaves `porcelain` empty, so `clean` is
626
+ # already true — and `-u` takes the untracked files too, so no case is left that
627
+ # this still refuses. Entries carry `WIP on <branch>`, so an old entry on
628
+ # ANOTHER branch is separable; a stale one on THIS branch is not, and telling it
629
+ # from the member's fresh entry needs a count the caller captured before the
630
+ # member ran. This script runs once, before the rebase, so it has no baseline.
631
+ #
632
+ # Never pop, drop or apply an entry this process did not create.
633
+ #
634
+ # The count above is only honest when the list can be trusted, and it cannot
635
+ # always be. `git stash list` prints nothing at rc 0 for a reflog this process
636
+ # cannot read (`chmod 000 .git/logs/refs/stash`), nothing at rc 1 for a stash
637
+ # ref whose object is gone (`fatal: bad object refs/stash`), and nothing at rc 0
638
+ # again for a `refs/stash` FILE this process cannot read (`chmod 000
639
+ # .git/refs/stash`) — all measured, and none distinguishable from a genuinely
640
+ # empty stash by the list alone, while `0` is the one value the runbook reads as
641
+ # nothing to look at.
642
+ #
643
+ # `show-ref` is the discriminator because its exit code separates "no such ref"
644
+ # from "could not read the ref". Measured, git 2.50.1:
645
+ #
646
+ # state | stash list | show-ref | verdict
647
+ # healthy, entries | rc0 nonempty | rc0 | the count
648
+ # genuinely empty | rc0 empty | rc1 | 0
649
+ # unreadable reflog | rc0 empty | rc0 | unknown
650
+ # stash object gone | rc1 empty | rc128 | unknown
651
+ # unreadable ref file | rc0 empty | rc128 | unknown
652
+ # malformed ref file | rc0 empty | rc128 | unknown
653
+ # ref file DELETED | rc0 empty | rc1 | unknown (reflog probe)
654
+ #
655
+ # The `malformed ref file` row is a fourth CAUSE, not a fourth signature:
656
+ # `printf 'not-a-sha' > .git/refs/stash` is indistinguishable from a `chmod
657
+ # 000` on the same file — same rc pair, same `show-ref` stderr, measured. So
658
+ # the line this branch prints names three causes for four, and `ls -l` on the
659
+ # two files, which is what the runbook sends the operator to read next, shows a
660
+ # healthy mode for that row. Widening either is #437, not this ticket.
661
+ #
662
+ # `rev-parse --verify --quiet` cannot do this job: it returns 1 for the
663
+ # unreadable ref FILE for the same reason the list is empty, collapsing that
664
+ # case onto the genuinely-empty branch and printing a confident `0` with a real
665
+ # entry on the stack. A plain exit-status guard on `stash list` cannot do it
666
+ # either, because neither reflog case fails.
667
+ #
668
+ # rc 1 says the REF is absent. It does not say the stash is empty, and the
669
+ # `ref file DELETED` row is the difference: `rm -f .git/refs/stash` leaves the
670
+ # reflog naming commits that are still reachable, and `show-ref` answers 1 for
671
+ # it exactly as it does for a repo that never stashed (#376). So rc 1 buys a
672
+ # second question rather than a verdict — is the reflog gone too? Only then is
673
+ # `0` a claim this can make. It composes with the discriminant above rather
674
+ # than replacing it: the three states that land on rc 0/128 never reach the
675
+ # probe.
676
+ #
677
+ # The probe can be this blunt because git empties the reflog whenever it empties
678
+ # the stack. `pop`, `drop`, `clear` and `update-ref -d` each REMOVE
679
+ # `logs/refs/stash` outright (measured, git 2.50.1) — there is no ordinary
680
+ # lifecycle that leaves it behind, so this cannot turn an honest `0` into
681
+ # `unknown`, which would be the worse bug: this line gates an irreversible
682
+ # action, and an operator who sees `unknown` on every run stops reading it.
683
+ # `-s`, not `-e`: a zero-byte reflog names nothing recoverable.
684
+ #
685
+ # `--git-path`, never `$wt/.git/logs/...`. The stack is repo-global, and `$wt`
686
+ # is routinely a LINKED worktree — the fleet's own layout — where `.git` is a
687
+ # FILE and that path reaches nothing, so a hand-built one reads "no reflog" and
688
+ # prints the confident `0` this exists to remove, in the layout that matters.
689
+ # `--git-path` is the right question rather than `--git-common-dir` joined by
690
+ # hand because git owns the per-worktree/common split: `logs/refs` is common,
691
+ # `logs/HEAD` and `logs/refs/bisect` are not, and that rule is git's to change.
692
+ # `--path-format=absolute` is load-bearing, not decoration: the bare answer is
693
+ # already absolute from a linked worktree but relative to `-C` from a main one,
694
+ # and this script runs from the CALLER's cwd, not `$wt`'s, so the relative form
695
+ # would look for the reflog under the caller and print the confident `0` this
696
+ # exists to remove. An unsearchable `logs/refs` DIRECTORY is no longer a
697
+ # ceiling here and never printed the `0` this once recorded: the path
698
+ # resolution needs search permission on every ancestor, so it fails before the
699
+ # `-s` stat, and it now answers unknown on its own line rather than refusing
700
+ # the whole audit (#570 — see the resolution below).
701
+ # `core.logAllRefUpdates=false` is NOT a second one: it suppresses the HEAD
702
+ # reflog, but `git stash push` force-creates `logs/refs/stash` regardless, so
703
+ # such a repo probes normally and reports `unknown` (measured, git 2.50.1).
704
+ #
705
+ # This does not close every unreadable reflog: one that is merely TRUNCATED —
706
+ # some entries lost, the rest still parses — resolves the ref and returns a
707
+ # nonempty list, so the cross-check sees no disagreement and reports the
708
+ # (too-low) count as exact. That gap is a remaining ceiling. #306's
709
+ # characterization test pins it without closing it — closing it was ruled out
710
+ # separately as not worth the complexity.
711
+ #
712
+ # A corrupt loose object behind a NON-TIP entry is one shape of that ceiling,
713
+ # and it is not one, because git is loud about it. The reflog there is
714
+ # intact, so `stash list` resolves the ref, prints the entries it could read,
715
+ # says `fatal: loose object ... is corrupt` and exits 1 — a nonempty list at a
716
+ # nonzero rc, a shape none of the rows above has, so `show-ref` agrees with the
717
+ # ref and the cross-check has nothing to disagree with. The rc is the only
718
+ # signal, which is why the list is captured rather than piped: `| wc -l` made
719
+ # this statement's status `wc`'s, always 0, and git's own rc unrecoverable.
720
+ # Nothing else moves — the count is still the lines the list printed, its stderr
721
+ # is still dropped here, and a list that succeeds is still read as a count. #482.
722
+ #
723
+ # Only the CORRUPT half of that shape is loud. A non-tip object that is MISSING
724
+ # rather than corrupt leaves the reflog intact too, but `stash list` then skips
725
+ # the entry it cannot read in silence: rc 0, no stderr, one line short
726
+ # (measured: three entries, `rm` the loose object behind `refs/stash@{2}` ->
727
+ # rc 0, two lines, empty stderr, git 2.50.1). Nothing here can tell that from a
728
+ # genuinely shorter stack, so it still reports the exact-looking count and stays
729
+ # under the #306 ceiling above.
730
+ sl_rc=0
731
+ sl=$(git -C "$wt" stash list 2>/dev/null) || sl_rc=$?
732
+ # `awk 'END{print NR}'`, not `wc -l`, and the difference is the empty stack.
733
+ # `$()` has stripped the trailing newline, so `wc -l` on the bare capture counts
734
+ # one short (measured: two entries, `printf '%s'`, `wc -l` -> 1), and padding it
735
+ # back with `printf '%s\n'` turns an EMPTY stack into a lone newline `wc -l`
736
+ # counts as one entry — two errors needing a `[ -z ]` guard between them. awk
737
+ # counts the final incomplete record, so one statement answers both ends
738
+ # (measured under `/bin/sh` with `set -eu`: "" -> 0, one/two/three entries with
739
+ # no trailing newline -> 1/2/3, and no padding to strip).
740
+ stash=$(printf '%s' "$sl" | awk 'END{print NR}') \
741
+ || die "awk failed counting the stash entries — cannot report the stash count"
742
+ sr_rc=0
743
+ git -C "$wt" show-ref refs/stash >/dev/null 2>&1 || sr_rc=$?
744
+ # Resolved lazily, inside the one state that asks the question: a healthy repo
745
+ # with entries short-circuits on `$stash` and never pays for this call.
746
+ #
747
+ # It used to `|| die`, reasoning that `$wt` had already answered three
748
+ # `rev-parse` calls above so a failure here was the repo going away mid-run.
749
+ # Measurement falsified that: `--path-format=absolute` has to realify the path,
750
+ # which needs search permission on every ancestor, so an unsearchable
751
+ # `logs/refs` fails it with the repository entirely present — after the
752
+ # worktree status and those three resolutions have all succeeded on it. No
753
+ # stash history and no deleted ref are needed either, because this branch is
754
+ # what a repo that never stashed looks like. Refusing there withheld `clean`,
755
+ # `conflicts` and `atRisk` — the answers this script exists to give before an
756
+ # irreversible rebase — over a field its own line declares reported, not gated.
757
+ # A repo that really did go away still refuses, from the steps that need it:
758
+ # the status above and the merge-tree probe below each die on their own.
759
+ # `$stash_reflog_rc` rather than a bare empty `$stash_reflog`, because an empty
760
+ # path lands on `[ -s "" ]`, false, and prints the confident `0`; the state
761
+ # gets its own emission below instead of falling through to one. git's own
762
+ # `fatal:` naming the path and the errno is left on stderr, unwrapped, as the
763
+ # operator's whole lead on which directory to look at. #570.
764
+ stash_reflog=
765
+ stash_reflog_rc=0
766
+ if [ "$stash" = 0 ] && [ "$sr_rc" = 1 ]; then
767
+ stash_reflog=$(git -C "$wt" rev-parse --path-format=absolute --git-path logs/refs/stash) \
768
+ || stash_reflog_rc=$?
769
+ fi
770
+ # Two ways to the same answer, and each names its own state. The empty-list
771
+ # states are asked first and keep the sentence they already print, because a
772
+ # corrupt TIP object satisfies both tests (empty list, rc 1, `show-ref` rc 0)
773
+ # and `refs/stash` is what is wrong with it — the sentence below is about the
774
+ # ref, and it is the more specific of the two there. What is left for the rc is
775
+ # the state no cross-check can reach: git printed entries and then said it could
776
+ # not finish, so the ref resolves, nothing disagrees, and the number would be
777
+ # short by exactly the entries git refused to read (#482).
778
+ msg=
779
+ if [ "$stash" = 0 ] && [ "$sr_rc" -ne 1 ]; then
780
+ msg=" stash entries (repo-global, not gated): unknown — the list came back empty but refs/stash is not absent (an unreadable ref or reflog, or a ref pointing at a missing object)"
781
+ elif [ "$sl_rc" -ne 0 ]; then
782
+ msg=" stash entries (repo-global, not gated): unknown — the list call itself failed, so what it printed cannot be read as a count"
783
+ fi
784
+ if [ -n "$msg" ]; then
785
+ stash=null
786
+ # One of those causes is one git will name outright — the missing object,
787
+ # where it says `fatal: bad object refs/stash` and the "refs/stash is not
788
+ # absent" message degrades that into a guess across all four. So ask a second
789
+ # time, on this branch only, and let git speak for itself. `stash list` is
790
+ # silent in the other three (rc 0, no stderr — measured, git 2.50.1), so
791
+ # `$diag` is empty there and the line comes out exactly as it did before.
792
+ #
793
+ # CEILING: git is not silent in two of those three — only `stash list` is.
794
+ # `show-ref`, called above with its stderr thrown away, prints `fatal: git
795
+ # show-ref: bad ref refs/stash (0000000000000000000000000000000000000000)`
796
+ # for BOTH the unreadable and the malformed ref file: one canned line for two
797
+ # causes, naming a null SHA that neither ref holds. It is silent only for the
798
+ # unreadable reflog. Whether that wrong-but-specific line beats this
799
+ # right-but-vague one is #481; this change captures `stash list` and nothing
800
+ # else.
801
+ #
802
+ # The counting statement above takes git's exit code and nothing else, and
803
+ # that is the whole of what it takes. Capturing its stderr THERE means
804
+ # splitting stdout from stderr around one substitution, a temp file on every
805
+ # run, and a rule for git writing to stderr while succeeding — paid on every
806
+ # healthy audit to serve the one path that has already decided something is
807
+ # wrong. Here the second call costs nothing: it runs only on a run that is
808
+ # already reporting a fault, which now includes the run whose rc brought it
809
+ # here. #304, #482.
810
+ #
811
+ # `2>&1 >/dev/null` in that order captures stderr and drops stdout — the list
812
+ # itself is not wanted, it was already counted. `|| true` is load-bearing
813
+ # under `set -e`: git exits 1 in exactly the state this exists for, and an
814
+ # unguarded substitution would abort the audit before it emits a payload,
815
+ # turning a report into a refusal.
816
+ #
817
+ # `tr` because `$diag` is not one line. A stash object that is CORRUPT
818
+ # rather than missing (`echo junk > .git/objects/<xx>/<rest>`) reaches this
819
+ # same branch — list empty at rc 1, show-ref rc 0 — and git says it in 7
820
+ # lines, 10 with a bad `objects/info/alternates`. Unfolded they land at
821
+ # column 0 in the audit's stderr, which is where only its own `$ git ...`
822
+ # step headers belong. `$()` has already stripped the trailing newline, so
823
+ # the fold adds no trailing space and the silent states still append nothing.
824
+ #
825
+ # `printf`, not `echo`: `$msg` now carries git's text under `#!/bin/sh`, and
826
+ # both dash and macOS sh expand escapes in an `echo` operand — a `\c` in it
827
+ # truncates the operator's line and swallows its newline. Reachable: with
828
+ # `objects/info/alternates` holding a path containing a backslash, git prints
829
+ # it back verbatim, `error: unable to normalize alternate object path:
830
+ # /no\clue/objects`.
831
+ #
832
+ # The fold is guarded for the reason `render` at the top of this file is: it
833
+ # decides nothing — `$stash` is already `null` and this branch already
834
+ # reports a fault — while an unguarded `$( … | tr … )` inside an assignment
835
+ # hands `set -eu` tr's own status, and 1 out of this script is the
836
+ # dirty-worktree refusal. `tr` is the surer carrier of that abort than the
837
+ # `sed` renders are, per the header's own measurement — it exits on the byte
838
+ # wherever in the line it sits, where sed tolerates some positions. Losing
839
+ # the fold is not losing the line — `$msg` already names the state, and the
840
+ # fallback says which part went missing rather than printing git's text
841
+ # truncated at the byte, which is what tr leaves behind on its way out.
842
+ diag=$(git -C "$wt" stash list 2>&1 >/dev/null) || true
843
+ if [ -n "$diag" ]; then
844
+ flat=$(printf '%s' "$diag" | tr '\n' ' ') \
845
+ || flat="(git said more, and folding it onto this line failed)"
846
+ msg="$msg — $flat"
847
+ fi
848
+ emit "$msg"
849
+ elif [ "$stash_reflog_rc" -ne 0 ]; then
850
+ stash=null
851
+ # Its own sentence, and asked BEFORE the `-s` test the resolved path feeds:
852
+ # `$stash_reflog` is empty here, `[ -s "" ]` is false, and the trailing
853
+ # branch prints the confident `0` this exists to remove. It says only that
854
+ # the reflog could not be reached. The `-s "$stash_reflog"` branch asserts
855
+ # what the reflog CONTAINS — "still names entries no ref points at" — and
856
+ # that is a claim about a file this state has not read; one sentence spanning
857
+ # both states is the conflation the header rule forbids.
858
+ emit " stash entries (repo-global, not gated): unknown — the reflog path could not be resolved, so the reflog could not be read"
859
+ elif [ -s "$stash_reflog" ]; then
860
+ stash=null
861
+ # Its own sentence, not the one above: there `refs/stash` is present and
862
+ # unreadable, here it is gone while its reflog is not, and the branch above
863
+ # would tell the operator "refs/stash is not absent" about the one state
864
+ # whose whole shape is that it IS — then send them to `ls -l` on a file that
865
+ # no longer exists. No `$diag`: git is silent here, empty list at rc 0.
866
+ emit " stash entries (repo-global, not gated): unknown — refs/stash is absent but its reflog is not, and still names entries no ref points at"
867
+ else
868
+ emit " stash entries (repo-global, not gated): $stash"
869
+ fi
870
+
871
+ # 2. Which files would conflict.
872
+ #
873
+ # `-z` is load-bearing twice. It turns OFF git's C-quoting, so a path holding
874
+ # a `"` arrives verbatim instead of as the rendering
875
+ # `"has\"quote and space.txt"` — which is neither a pathspec git will match
876
+ # nor a JSON string, and which used to reach both the caller and the `git
877
+ # log` below. A space alone git does NOT quote, so that half of the fixture
878
+ # was broken by the word-split at step 3 and by nothing here; `-z` earns its
879
+ # place on `"`, `\` and the control bytes. And it separates records with NUL,
880
+ # the one byte a filename cannot contain. NUL does not survive a command
881
+ # substitution, so this lands in a file rather than a variable.
882
+ #
883
+ # merge-tree exits 0 clean, 1 conflicts found, >=2 on gross failure. Exit 1
884
+ # is NOT only "ran fine, found conflicts": git 2.50.1 spends it on
885
+ # `not something we can merge` too, which is where a BASE_REF naming a tag
886
+ # that dereferences to a blob lands — that tag satisfies the `rev-parse
887
+ # --verify` guard above, so it gets this far. The exit code cannot carry the
888
+ # distinction alone. Every run that ran at all prints the tree OID first, so
889
+ # empty output is the outcome the exit code will not name; it used to be
890
+ # read as "no conflicting files" and reported safe, which is exactly the
891
+ # branch-that-never-resolved case this step exists to catch.
892
+ mt_out=$(mktemp) || die "cannot create a temporary file"
893
+ # Armed before the SECOND `mktemp` rather than after it, because a `die` between
894
+ # the two would otherwise run with no trap installed and leave the first
895
+ # temporary on disk. `ps_out` is emptied first so the trap body is legal under
896
+ # `set -u` while it names a variable the run has not reached yet; `rm -f ""` is
897
+ # a no-op, so the trap is correct in both windows.
898
+ ps_out=
899
+ trap 'rm -f "$mt_out" "$ps_out"' EXIT
900
+ # The at-risk step's pathspec list, written by the same reader that answers the
901
+ # conflicts question below. NUL-separated, so it cannot travel in a variable;
902
+ # `mktemp` rather than a name derived from `$mt_out`, so a shared TMPDIR offers
903
+ # no predictable name to plant a symlink on.
904
+ ps_out=$(mktemp) || die "cannot create a temporary file"
905
+ emit "\$ git merge-tree --write-tree --name-only -z $base_rev $branch_rev"
906
+ mt_rc=0
907
+ git -C "$wt" merge-tree --write-tree --name-only -z "$base_rev" "$branch_rev" >"$mt_out" || mt_rc=$?
908
+ [ "$mt_rc" -le 1 ] && [ -s "$mt_out" ] \
909
+ || die "git merge-tree could not answer (exit $mt_rc) against origin/$branch — cannot determine conflicts"
910
+ # This die does not gain `$branch_rev` the way the rev-parse guard above and
911
+ # the merge-base die below do: by the time it can fire, both `$base_rev` and
912
+ # `$branch_rev` have already survived their own `rev-parse --verify`, so a
913
+ # merge-tree failure here is not a spelling question either of those dies
914
+ # could get wrong.
915
+
916
+ # --name-only output is: tree OID, then (if conflicted) the conflicted-file
917
+ # list, then an EMPTY record, then prose ("Auto-merging ...", "CONFLICT ...").
918
+ # Only the section before that empty record is filenames — the old
919
+ # `tail -n +2` grabbed the prose section too and word-split it into the
920
+ # `git log -- $conflicts` pathspec below.
921
+ #
922
+ # Read by one NUL-capable reader rather than a `tr | tr | awk` pipeline, and
923
+ # the reason is the exit status, not the parse. A POSIX pipeline's status is its
924
+ # LAST command's, so a fault in any earlier stage is invisible to `set -e` and
925
+ # to a trailing `|| die` alike: the stage yields short output, the pipeline
926
+ # exits 0, and this script reports a SMALLER conflicts list with full
927
+ # confidence — the false safe the prologue describes, and precisely the outcome
928
+ # the standard below says must be exit 2 instead. `export LC_ALL=C` answers the
929
+ # one byte that was measured getting in; it cannot make a status readable, and
930
+ # any other fault in a prefix stage reproduces the under-report. #583.
931
+ #
932
+ # `set -o pipefail` is NOT the alternative, and not merely because POSIX sh
933
+ # lacks it (dash rejects `set -o pipefail` outright). Measured: a healthy
934
+ # conflicted run already ends with the prefix stages killed by SIGPIPE —
935
+ # `pipestatus 141 141 0 0` on a run whose answer is entirely CORRECT — because
936
+ # the reader stops at the empty record BY DESIGN and leaves merge-tree's prose
937
+ # tail unread, and once that tail outgrows a pipe buffer whatever is upstream is
938
+ # still writing when the reader goes away. `pipefail` would turn every such run
939
+ # into a refusal, which is a worse failure than the one it fixes. The control
940
+ # for that is a test rather than this paragraph: no-undo-audit.test.mjs builds a
941
+ # run whose unread tail outgrows a pipe buffer and requires a full answer.
942
+ #
943
+ # One reader answers both questions, so there is nothing left to discard a
944
+ # status. stdout carries the paths for the payload, a literal NEWLINE in a
945
+ # filename parked on \001 — a shell variable cannot hold NUL, and macOS awk
946
+ # 20200816 reads RS="\0" as RS="" and silently switches to paragraph mode, so
947
+ # an unparked newline manufactured the empty record that ends the section and
948
+ # `conflicts` came back short or empty while the audit exited 0. `$ps_out` gets
949
+ # the same paths NUL-separated and `:(literal)`-prefixed, which is what the
950
+ # at-risk step feeds to xargs. The reader works in bytes end to end (`rb`,
951
+ # `stdout.buffer`), so no path is decoded and none can be rejected for its
952
+ # bytes; the locale cannot reach it.
953
+ conflicts=$(python3 -c '
954
+ import sys
955
+ recs = open(sys.argv[1], "rb").read().split(b"\0")
956
+ paths = []
957
+ for r in recs[1:]:
958
+ if not r:
959
+ break
960
+ paths.append(r)
961
+ with open(sys.argv[2], "wb") as f:
962
+ f.write(b"".join(b":(literal)" + p + b"\0" for p in paths))
963
+ sys.stdout.buffer.write(b"\n".join(p.replace(b"\n", b"\x01") for p in paths))
964
+ ' "$mt_out" "$ps_out") \
965
+ || die "could not read git merge-tree's output (python3) — cannot determine conflicts"
966
+ # Unanswerable is exit 2, and worse than what this replaced: git C-quoted such a
967
+ # path, which at least emitted JSON the caller choked on. ponytail: refusing,
968
+ # not answering. `$ps_out` already carries the newline-holding path unparked, so
969
+ # the at-risk half could answer for it; `conflicts[]` cannot, because it reaches
970
+ # the payload through a shell variable and NUL is the one byte that cannot
971
+ # travel there. Answering both halves means keeping the payload side in a file
972
+ # too. Bought for a shape nobody has produced — upgrade there if one turns up.
973
+ nl=$(printf '\001')
974
+ case "$conflicts" in
975
+ *"$nl"*) die "a conflicting path contains a newline — cannot build a pathspec for it" ;;
976
+ esac
977
+ if [ -n "$conflicts" ]; then
978
+ render ' conflict: ' "$conflicts" "the conflicting-path list"
979
+ else
980
+ emit " no conflicting files"
981
+ fi
982
+ # `jarr`/`jarr_rewritten` return non-zero when a stage fails (#119), and a bare
983
+ # `var=$(pipeline)` under `set -eu` would abort with the failing tool's own
984
+ # status — 1 out of THIS script is the dirty-worktree refusal, fabricated here
985
+ # on a worktree already measured clean, with no payload and nothing on stderr.
986
+ # The `|| die` converts it to the exit 2 this script's contract reserves for a
987
+ # question it could not answer.
988
+ conflicts_json=$(printf '%s' "$conflicts" | jarr) \
989
+ && conflicts_rewritten_json=$(printf '%s' "$conflicts" | jarr_rewritten) \
990
+ || die "could not escape the conflicting paths for $branch"
991
+
992
+ # 3. What main gained in those files since the fork. These are the commits a
993
+ # careless resolution deletes — read them before resolving, not after.
994
+ at_risk=""
995
+ if [ -n "$conflicts" ]; then
996
+ fork=$(git -C "$wt" merge-base "$base_rev" "$branch_rev") \
997
+ || die "git merge-base failed for $base ($base_rev) and $branch_rev — cannot tell what a resolution would eat"
998
+ emit "\$ git log --oneline $fork..$base_rev -- <conflicting files>"
999
+ # One pathspec per argument. Word-splitting `$conflicts` turned a path with a
1000
+ # space into two pathspecs that match nothing, and `git log` spends exit 0 on
1001
+ # a pathspec that matches nothing — so `2>/dev/null || true` was not even what
1002
+ # hid it. There was no error to swallow and no output to lose: the answer came
1003
+ # back empty on a branch that really was about to eat a commit. The swallow
1004
+ # goes anyway, because a `git log` that genuinely fails leaves the same empty
1005
+ # answer, and that one is unanswerable rather than safe.
1006
+ #
1007
+ # `:(literal)` because `--` ends the OPTIONS, not the magic: a real file named
1008
+ # `:colon.txt` is read as a pathspec expression and silently matches nothing,
1009
+ # which is the same false safe by a different byte. It is reachable: `git add
1010
+ # -A` and `git add .` track such a file happily, because the name never
1011
+ # appears as a pathspec there. Naming it as one is what fails — so
1012
+ # `git add -- :colon.txt` erroring is not evidence this guard is dead weight.
1013
+ #
1014
+ # The pathspec list arrives NUL-separated in `$ps_out`, written by the reader
1015
+ # that produced `$conflicts`, so this is a single command and not a pipeline:
1016
+ # nothing sits ahead of it with a status to discard. It used to be
1017
+ # `printf | sed | tr | xargs`, where the `|| die` could only ever answer for
1018
+ # the last of the four and a fault in any of the other three under-reported
1019
+ # `at_risk` at exit 0. #583.
1020
+ at_risk=$(xargs -0 git -C "$wt" log --oneline "$fork".."$base_rev" -- <"$ps_out") \
1021
+ || die "listing commits for the conflicting paths failed (git log or xargs) — cannot tell what a resolution would eat"
1022
+ # Above ARG_MAX (1048576 on macOS) xargs splits the pathspec list across
1023
+ # more than one `git log` invocation, and each invocation reports every
1024
+ # commit touching ITS OWN batch — so a commit whose changes span more than
1025
+ # one batch is printed once per batch it lands in. Deduped on the abbreviated
1026
+ # SHA, `--oneline`'s first field, keeping each commit's FIRST occurrence; a
1027
+ # no-op when xargs did not split. Only the SET is claimed. The order that
1028
+ # survives is the order the batches came back in, which once xargs has split
1029
+ # is PATHSPEC order, not `git log`'s reverse-chronological one — an older
1030
+ # commit can be listed above a newer, and nothing marks which case you are
1031
+ # reading. Left that way deliberately: re-sorting costs a second `git log`
1032
+ # to buy a ranking this audit does not offer, since it names the commits a
1033
+ # resolution would eat rather than ordering them.
1034
+ # Kept as its own statement rather than piped onto the xargs/git-log command
1035
+ # that produced $at_risk: piped, `awk` would become that pipeline's LAST
1036
+ # command, and with no `pipefail` in POSIX sh (dash rejects `set -o pipefail`
1037
+ # outright) its `|| die` would read awk's exit status, not git log's —
1038
+ # silently swallowing a real git-log failure behind a trivially-successful
1039
+ # awk pass on whatever partial output preceded it. A fresh statement over the
1040
+ # already-captured string leaves the xargs/git-log `|| die` reading xargs,
1041
+ # which is what its own message names.
1042
+ at_risk=$(printf '%s\n' "$at_risk" | awk '!seen[$1]++') \
1043
+ || die "awk failed deduplicating the at-risk commits — cannot tell what a resolution would eat"
1044
+ # An `if`, not `[ -n "$at_risk" ] && render …`: an empty at-risk list is a
1045
+ # normal outcome, and as the non-last member of an AND-OR list its false
1046
+ # test left that list exiting 1 — silent under `set -e` only because -e
1047
+ # skips every member but the last. The guard inside `render` cannot reach
1048
+ # that status, so the shape stays out of the way of it entirely.
1049
+ if [ -n "$at_risk" ]; then
1050
+ render ' at risk: ' "$at_risk" "the at-risk commit list"
1051
+ fi
1052
+ fi
1053
+ # Same guard, same reason as the conflicts pair above.
1054
+ at_risk_json=$(printf '%s' "$at_risk" | jarr) \
1055
+ && at_risk_rewritten_json=$(printf '%s' "$at_risk" | jarr_rewritten) \
1056
+ || die "could not escape the at-risk commits for $branch"
1057
+
1058
+ if [ "$clean" = true ]; then
1059
+ rc=0
1060
+ else
1061
+ rc=1
1062
+ emit "$NAME: REFUSED — commit the worktree before rebasing. Never \`git clean\`,"
1063
+ emit " \`git checkout .\`, \`git reset --hard\` or \`git stash\` to make a rebase start."
1064
+ fi
1065
+
1066
+ # `$wt` is a filename, so it admits both `"` and `\`; git accepts `"` in a ref
1067
+ # name, so `$branch` admits one too. `$clean` and `$stash` are this script's own
1068
+ # boolean and a digit count (or the literal `null` when the count is unknown),
1069
+ # and the four arrays arrive escaped already.
1070
+ # `*Rewritten` says which of the paired values lost bytes to the space-scrub
1071
+ # above and so is not safe to treat as the real path or ref — most concretely,
1072
+ # not safe to hand to `git diff -- <path>` in the no-undo-audit runbook step.
1073
+ # A `$(...)` in printf's ARGUMENT list sits outside the `|| die` on the printf
1074
+ # itself: a substitution that fails contributes an EMPTY argument and printf
1075
+ # still exits 0 — and an unquoted `%s` slot then emits `"...Rewritten":,`,
1076
+ # malformed JSON at exit 0, which is the failure the receipt exists to rule
1077
+ # out. Assigned first, each one is a simple command whose status `add_field`
1078
+ # can read.
1079
+ #
1080
+ # `die` is NOT the answer here (#431), unlike the conflicts and at-risk escapes
1081
+ # above, and the difference is which kind of value each renders. Those two are
1082
+ # FINDINGS — the operator can obtain them nowhere else, and step 5 of the
1083
+ # no-undo runbook hands `conflicts[]` straight to `git diff -- <path>`, where an
1084
+ # absent list reads as "nothing to prove" rather than "unproven". A run that
1085
+ # cannot render them has not answered, so they still abandon the run.
1086
+ #
1087
+ # `worktree` and `branch` are the other kind: echoes of argv the caller supplied
1088
+ # and still holds. By the time this block runs `clean` has been measured,
1089
+ # `stash` counted, and both arrays already rendered — so every field this
1090
+ # payload carries is established, and a formatter breaking HERE would convert a
1091
+ # finished audit into "unanswerable" over the formatting of two values the
1092
+ # caller typed. Each renders independently and reports JSON `null` when it
1093
+ # cannot, which is what #120 shipped for this same class in inflight.sh. Not a
1094
+ # quieter `""`: a field that could not be escaped has no usable path to hand to
1095
+ # `git diff` in any case, and `""` is indistinguishable from a path.
1096
+ #
1097
+ # The message names the escaper as well as the field, because the two fail
1098
+ # independently — `jstr` can render a string perfectly while `jrewritten` cannot
1099
+ # say whether any byte was replaced (break `tr -d` alone and that is exactly
1100
+ # what happens). Naming only the field sends a debugger to whichever it guesses.
1101
+ # `printf`, not `echo`: `$branch` is caller text like every other site here.
1102
+ #
1103
+ # Accumulated into one string rather than four named variables, the shape
1104
+ # `inflight.sh`'s `add_evidence` already uses, so each field name is spelled
1105
+ # once instead of three times. The trailing comma is kept rather than trimmed —
1106
+ # `"clean"` follows immediately — and the slot carrying it is an unquoted `%s`
1107
+ # because each value arrives already wrapped in its own quotes or as the bare
1108
+ # word `null`, so the format string must not wrap it again. $ev/$rw/$why are
1109
+ # scratch: not `local`, which /bin/sh has no builtin for, and nothing reads them
1110
+ # outside this function.
1111
+ fields=""
1112
+ add_field() {
1113
+ why=""
1114
+ if ! ev=$(jstr "$2"); then
1115
+ why=jstr
1116
+ elif ! rw=$(jrewritten "$2"); then
1117
+ why=jrewritten
1118
+ else
1119
+ ev="\"$ev\""
1120
+ fi
1121
+ if [ -n "$why" ]; then
1122
+ ev=null
1123
+ rw=null
1124
+ emit "$NAME: could not render the $1 for $branch as JSON ($why) — reported as null"
1125
+ fi
1126
+ fields="${fields}\"$1\":$ev,\"$1Rewritten\":$rw,"
1127
+ }
1128
+ add_field worktree "$wt"
1129
+ add_field branch "$branch"
1130
+ printf '{%s"clean":%s,"stash":%s,"conflicts":[%s],"conflictsRewritten":[%s],"atRisk":[%s],"atRiskRewritten":[%s]}\n' \
1131
+ "$fields" "$clean" "$stash" \
1132
+ "$conflicts_json" "$conflicts_rewritten_json" "$at_risk_json" "$at_risk_rewritten_json" \
1133
+ || die "could not write the audit for $branch"
1134
+ exit "$rc"