@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,1106 @@
1
+ #!/bin/sh
2
+ # Is ticket <N> already being worked on?
3
+ #
4
+ # Three probes, all of them, every time: an existing PR, a remote branch, a
5
+ # local worktree or branch. Any hit means taken. They are not redundant — a PR
6
+ # can exist with its branch deleted, a branch can exist with no PR yet, and a
7
+ # worktree can exist before anything is pushed.
8
+ #
9
+ # Exit 0 free, 1 taken, 2 the question could not be answered. A probe that
10
+ # cannot answer no longer aborts the run: it is recorded unknown and the other
11
+ # two still run. Each probe also commits a signal the moment it is established
12
+ # rather than at its own end, so a hit is never discarded by a later failure —
13
+ # neither one in another probe, nor one in a later stage of the probe that
14
+ # found it. Exit 2 from a probe failure carries a payload — the same shape as
15
+ # 0 and 1, plus an "unknown" list naming which probes could not look.
16
+ #
17
+ # Four failures still exit 2 with no payload at all, the four the script table
18
+ # in docs/specs/2026-07-23-fleet-plugin-design.md lists. Three of them land
19
+ # before anything has been established: a bad argument, not being inside a git
20
+ # repository, and no such issue. That last one fires inside probe 1, after its
21
+ # own `gh issue view` has already run — it is not a pre-probe check, it is the
22
+ # premise all three probes rest on, so it abandons the run rather than
23
+ # recording one probe's unknown. The fourth is the opposite end: the verdict
24
+ # itself cannot be written at all, which fails after every probe has finished,
25
+ # with everything established and no way to say it. An evidence string that
26
+ # cannot be rendered is NOT one of the four (#120): the verdict is already
27
+ # correct at that point, and a formatter breaking must not retract it — that
28
+ # field is emitted as JSON null instead, on the payload the verdict already
29
+ # earned. No gap left in that: `jstr`'s own `sed` stage used to be invisible —
30
+ # a pipeline reports only its LAST stage, so a failed `sed` rendered the field
31
+ # as "", the same value "found nothing" uses, with no null and no stderr line.
32
+ # json.sh captures each fallible stage and reads its status, so that failure now
33
+ # reaches `add_evidence` and lands in the null branch like any other (#119).
34
+ set -eu
35
+
36
+ # Byte semantics for the `tr`, `sed` and `awk` below. There is no `grep`: this
37
+ # script deliberately has none, and two comments further down — "One awk, not
38
+ # `awk | sed | grep | paste`" and "awk, not `grep -c … || true`" — are the
39
+ # standing argument for why. `tr` splits `git worktree list --porcelain -z`,
40
+ # flattens `gh`'s error text into a diagnostic, and scrubs control bytes inside
41
+ # `jstr`, which `sed` shares; `awk` parses refs, branch names and worktree
42
+ # paths. Under a UTF-8 locale BSD `tr` and `sed` exit 1 on a byte that is not
43
+ # valid UTF-8 — `sed` emitting nothing at all, measured.
44
+ #
45
+ # `awk` is NOT immune, and reap.sh's own #614 fixture measured the earlier
46
+ # claim here false: it is byte-identical only when every rule matches at an
47
+ # ANCHOR before the bad byte, never needing to convert it — a rule that must
48
+ # SCAN PAST the byte to decide dies instead (BWK awk, macOS: rc 2, `towc:
49
+ # multibyte conversion failure`). What keeps every `awk` call below safe from
50
+ # that is not the global pin two paragraphs down: each one already carries its
51
+ # OWN inline `LC_ALL=C` (grep this file for it), independent of the ambient
52
+ # locale or this global export — which is also why a regression test for this
53
+ # script's global pin has to attack one of those inline pins directly;
54
+ # deleting the global `export LC_ALL=C` below changes nothing for any of them.
55
+ #
56
+ # Such a byte reaches us from a fetched tree even where the local filesystem
57
+ # refuses to hold the name, and inside `$(...)` a `tr` failure empties the
58
+ # cause out of the diagnostic without a trace. #582 measured the cost of
59
+ # leaving this ambient in no-undo-audit.sh: a truncated list reported as a
60
+ # clean, confident answer.
61
+ #
62
+ # Safe as a global: nothing in this script sorts, folds case, or holds a POSIX
63
+ # class. It does use ONE collation range — `*[!0-9]*`, the issue-number guard
64
+ # below — and a range IS locale-sensitive by spec, its members drawn from the
65
+ # collation sequence rather than the codepoint order. Measured inert here
66
+ # (#612): `0-9` matches the ASCII digits and nothing else under `C`,
67
+ # `en_US.UTF-8`, `de_DE.UTF-8` and `tr_TR.UTF-8` alike, with superscript `²`,
68
+ # Arabic-Indic digits and `½` excluded in all four. So collation and
69
+ # case-folding — the two things `LC_ALL=C` otherwise changes — have nothing
70
+ # here to act on. locale-pin-prose.test.mjs holds that inventory as a list and
71
+ # fails if the code drifts from this paragraph in either direction.
72
+ #
73
+ # This completes a pin this script already started: the five `LC_ALL=C` prefixes
74
+ # below predate it and are now redundant. Left in place — each documents the
75
+ # hazard at its own site, and deleting them is churn this ticket did not
76
+ # measure — but no new site needs one.
77
+ export LC_ALL=C
78
+
79
+ # Below the locale pin, not above it with `set -eu`: `unset` touches no
80
+ # byte-sensitive tool, but locale-pin-prose.test.mjs treats ANY line here that
81
+ # is not a comment, a blank, or `set -[eux]+` as work the pin must sit above,
82
+ # and refuses on principle rather than on this line's own behaviour. Same
83
+ # placement, same reason, as release-ticket.sh's copy.
84
+ #
85
+ # GIT_DIR is the half with teeth here. Probe 3's git calls are all bare —
86
+ # `rev-parse --git-common-dir`, `for-each-ref`, `worktree list` — so an
87
+ # ambient one asks the WRONG repository whether this ticket is taken.
88
+ # Measured, standing in a checkout that holds both the branch and the
89
+ # worktree for #501, with `GIT_DIR` naming a second clone that holds neither:
90
+ # `no local branch or worktree for #501`, and with probes 1 and 2 silent the
91
+ # verdict is `taken: false` on a ticket already claimed. That is the
92
+ # double-claim phase 0 runs this script to prevent, and inflight.test.mjs's
93
+ # own fixture builder already deletes both variables for exactly this reason
94
+ # — a defence that protected the SUITE while leaving every real caller
95
+ # exposed.
96
+ #
97
+ # GIT_WORK_TREE is unset alongside it and is measured INERT here, three
98
+ # targets tried (the checkout root, a second clone, a plain directory): no
99
+ # call in any probe touches a work tree — `for-each-ref` and `ls-remote` read
100
+ # refs, `worktree list` and `--git-common-dir` read the admin directory — so
101
+ # there is no behaviour for it to change and no behavioural fixture can pin
102
+ # it. It stays on the line because the pair is one hazard with one remedy,
103
+ # and because "inert today" is a measurement of the current call set, not a
104
+ # property of the script. ambient-git-vars-prose.test.mjs pins the line
105
+ # itself, which is what keeps that half from being quietly dropped.
106
+ unset GIT_DIR GIT_WORK_TREE
107
+
108
+ NAME=inflight
109
+ die() { printf '%s: %s\n' "$NAME" "$1" >&2; exit 2; }
110
+
111
+ # The escaping helpers (#119). json.sh's header holds the sourcing contract and
112
+ # the measurements behind it; only what is true of THIS script is repeated here.
113
+ # Below `export LC_ALL=C` deliberately: locale-pin-prose.test.mjs allows only
114
+ # comments, blanks, a shebang or a `set -` line above that pin, and `json_lib=`
115
+ # is none of them.
116
+ #
117
+ # Exit 1 from this script means `taken`, so a library that merely went missing
118
+ # would fabricate a claim on a free ticket — which is why `[ -r ]` has to fire
119
+ # before the `.` can kill the shell.
120
+ json_lib="$(dirname "$0")/json.sh"
121
+ [ -r "$json_lib" ] || die "cannot read $json_lib — refusing to answer without the JSON escaping helpers"
122
+ # shellcheck source-path=SCRIPTDIR
123
+ # shellcheck source=json.sh
124
+ . "$json_lib" || die "$json_lib failed to load"
125
+
126
+ # The bounded, prompt-suppressed git transport (#92, #346, #347). It landed here
127
+ # for probe 2 alone and now lives in net.sh, where every other unattended `git`
128
+ # network call in the fleet reaches it too; net.sh's header holds the reasoning
129
+ # and the measurements. Sourced BELOW json.sh, deliberately: exit 1 from this
130
+ # script means `taken`, and the missing-library refusal every caller shares is
131
+ # already pinned on json.sh's name, so a second lib guard above it would change
132
+ # which file a lone copy of this script blames.
133
+ net_lib="$(dirname "$0")/net.sh"
134
+ [ -r "$net_lib" ] || die "cannot read $net_lib — refusing to answer without the bounded git transport"
135
+ # shellcheck source-path=SCRIPTDIR
136
+ # shellcheck source=net.sh
137
+ . "$net_lib" || die "$net_lib failed to load"
138
+
139
+ [ $# -eq 1 ] || die "usage: inflight.sh <issue-number>"
140
+ n=$1
141
+ case "$n" in ''|*[!0-9]*|0?*) die "issue must be a number, got '$n'";; esac
142
+
143
+ git rev-parse --git-dir >/dev/null 2>&1 || die "not inside a git repository"
144
+
145
+ hits=""
146
+ add_hit() { hits="${hits}\"$1\","; echo " HIT: $1" >&2; }
147
+
148
+ # A probe that cannot answer records itself here instead of dying. Same
149
+ # shape as `hits`, same trailing-comma-then-trim pattern at the end. The
150
+ # message is printed exactly as `die` used to print it — only the exit is
151
+ # gone — so every existing diagnostic string below still reads the same on
152
+ # stderr, and a caller grepping for one is unaffected by this change.
153
+ unknown=""
154
+ add_unknown() { unknown="${unknown}\"$1\","; printf '%s: %s\n' "$NAME" "$2" >&2; }
155
+
156
+ # Evidence defaults. A probe that fails leaves its own field empty rather
157
+ # than unset — `set -u` would otherwise abort the payload assembly at the
158
+ # bottom for a probe that never got the chance to fill it in, and empty is
159
+ # already what "found nothing" looks like in this field, disambiguated by
160
+ # `unknown` rather than by the field itself.
161
+ pr=""
162
+ remote=""
163
+ local_b=""
164
+ wt=""
165
+
166
+ # The three temp files, and the ONE EXIT trap that removes them. `sh` keeps a
167
+ # single EXIT trap, so a second `trap … EXIT` further down does not add a
168
+ # handler — it REPLACES this one, silently leaking whatever the first was going
169
+ # to remove. All three are therefore declared here and cleaned here rather
170
+ # than each probe installing its own. Declared empty, too, so the trap can run
171
+ # under `set -u` after a `die` that fired before any was created.
172
+ errfile=""
173
+ wtfile=""
174
+ wdfile=""
175
+ # `${…:+}` so a file that was never created contributes no argument at all
176
+ # rather than an empty one, and `rm -f` with no operands is specified to exit 0.
177
+ #
178
+ # `|| printf`, not a bare `rm -f`: this trap fires OUTSIDE the three probe
179
+ # functions, where `set -e` is still live, so a failing `rm -f` exits 1 — and
180
+ # the contract reads 1 as "taken", which would let cleanup overwrite a verdict
181
+ # already computed and announced. The same hazard the verdict `printf` at the
182
+ # foot of this file guards with `|| die`. The reporter returns 0, so the declared
183
+ # status survives and the cleanup failure is still said out loud rather than
184
+ # swallowed by a bare `|| :`.
185
+ #
186
+ # `printf`, not `echo`: these are mktemp paths, and `echo` expands a backslash
187
+ # in one. It returns 0 just as `echo` did, so the status argument above is
188
+ # unchanged. Format string double-quoted because the trap body is already
189
+ # single-quoted.
190
+ trap 'rm -f ${errfile:+"$errfile"} ${wtfile:+"$wtfile"} ${wdfile:+"$wdfile"} ||
191
+ printf "%s: could not remove %s %s %s\n" "$NAME" "$errfile" "$wtfile" "$wdfile" >&2' EXIT
192
+
193
+ # Probe 1 — a PR that is actually ABOUT this ticket.
194
+ #
195
+ # NOT `gh pr list --search "<N>"` on its own. That is a full-text search and is
196
+ # uselessly noisy: measured here, searching 41 returned six PRs, five of which
197
+ # merely contained the digits somewhere. Trusting it makes nearly every ticket
198
+ # read as taken, so the fleet skips free work silently and permanently.
199
+ #
200
+ # Nor a closing-keyword regex over the body. Also measured here: PR #344 is a
201
+ # docs fix ABOUT issue references, so its body quotes `Closes #41.` inside a
202
+ # markdown table. A regex cannot tell quoted text from a real link.
203
+ #
204
+ # Ask GitHub instead. `closedByPullRequestsReferences` is its own resolution of
205
+ # which PRs close this issue — it returns [] for 41 and [396] for 393, both
206
+ # correct. Then add branch-segment matching as a second signal, because a PR can
207
+ # exist before anyone writes a closing keyword.
208
+ probe_pr() {
209
+ echo "\$ gh issue view $n --json closedByPullRequestsReferences,url" >&2
210
+ # URLs, not bare numbers. A closing reference may live in another repository
211
+ # (`Closes owner/repo#N` is legal, which is why the node carries `repository`),
212
+ # and a bare number would collide with an unrelated local PR of the same number
213
+ # and silently inherit its state. A URL is globally unique, so the lookup below
214
+ # cannot mismatch. The issue's own URL rides along as the first field to name
215
+ # the repo the search window covers — same call, no extra round-trip.
216
+ #
217
+ # Both `gh` calls in this probe capture stderr to this one file rather than
218
+ # folding it in with `2>&1`: `linked`/`pr_json` above need stdout alone,
219
+ # undisturbed by any stderr noise a successful call still emits. It used to be
220
+ # a fixed /tmp/.inflight.$$ — guessable from the PID, and `>` follows a
221
+ # symlink, so anything on the host that pre-plants that path pointing at a
222
+ # file this user can write gets it truncated the instant stderr lands there
223
+ # (#91, measured: a 37-byte victim file left at 14 bytes). mktemp's
224
+ # unpredictable name closes the guess; the trap closes the other half — no
225
+ # cleanup ran for an interrupt landing between the redirect and the `rm -f`
226
+ # that only ever followed a call that finished.
227
+ #
228
+ # Created ONCE and never unlinked mid-run. The intermediate `rm -f`s that used
229
+ # to stand between the two calls handed the whole guess back: they freed a path
230
+ # that is known by then, and the next `2>"$errfile"` re-created it at the
231
+ # shell's umask instead of mktemp's — measured 0600 before, 0644 after — with a
232
+ # symlink-following `>` doing the re-creating. The second call truncates the
233
+ # same inode instead, so the path never leaves this process's hands, and the
234
+ # trap is the single cleanup path. (The cost is narrow and deliberate: if the
235
+ # second redirect itself fails, the readback below can report the first call's
236
+ # stderr. A double fault, against a window open on every ordinary run.)
237
+ if ! errfile=$(mktemp); then
238
+ # Probe-local, so it is recorded like any other probe that could not look.
239
+ # `die` here would abandon probes 2 and 3, which need neither `gh` nor this
240
+ # file — measured: a ticket visibly taken by a remote branch AND a worktree
241
+ # exited 2 with an empty payload and no hits.
242
+ add_unknown "pr" "could not create a temporary file to capture gh's stderr, so #$n's PR links are unknown"
243
+ return 1
244
+ fi
245
+ # Removal is the EXIT trap's, installed once at the top of this file — see the
246
+ # note there on why a second `trap … EXIT` here would silently disarm it.
247
+
248
+ # One readback for both `gh` calls below, so a third capture site inherits the
249
+ # fallback rather than having to remember to copy it. Empty is not "gh said
250
+ # nothing" — it is indistinguishable from the capture itself failing
251
+ # (unwritable /tmp, a full filesystem), which still fails closed but used to
252
+ # leave the operator with nothing after the colon.
253
+ gh_cause() {
254
+ err=$(cat "$errfile" 2>/dev/null || true)
255
+ [ -n "$err" ] || err="cause unavailable"
256
+ }
257
+
258
+ if ! linked=$(gh issue view "$n" --json closedByPullRequestsReferences,url --jq \
259
+ '[.url] + [.closedByPullRequestsReferences[].url] | join(",")' 2>"$errfile"); then
260
+ gh_cause
261
+ # "No such issue" and "GitHub is unreachable" are different facts and must not
262
+ # share a message. An unattended fleet reading a network blip as "that ticket
263
+ # does not exist" would drop real work on the floor.
264
+ # GitHub's text is "Could not resolve to an issue or pull request with the
265
+ # number of N" — issues and PRs share one number space, so the wording covers
266
+ # both and the match must not assume a capital I.
267
+ #
268
+ # Match the whole phrase, not a bare "Could not resolve": GitHub uses the same
269
+ # opening for repository-level failures (renamed or deleted repo, revoked
270
+ # access, a token that lost `repo` scope), and reporting those as "issue #N
271
+ # does not exist" sends the reader after the wrong thing. Exit is 2 either way.
272
+ case "$err" in
273
+ *"Could not resolve to an "[Ii]"ssue"*|*"NOT_FOUND"*)
274
+ # Terminal, not accumulated: a nonexistent issue is not a probe that
275
+ # could not look, it is the premise every probe depends on being false.
276
+ # Nothing has been established, so this stays a hard die like the
277
+ # precondition checks above it — the other two probes would have
278
+ # nothing meaningful to search for either.
279
+ die "issue #$n does not exist in this repository" ;;
280
+ *)
281
+ # Unlike the branch above, this IS a probe that could not look — a
282
+ # network blip, an auth failure, a renamed repository. Record it and
283
+ # let probes 2 and 3 still run rather than discarding whatever they
284
+ # might find.
285
+ add_unknown "pr" "gh issue view $n failed, so #$n's PR links are unknown: $(printf '%s' "$err" | tr '\n' ' ')"
286
+ return 1 ;;
287
+ esac
288
+ fi
289
+
290
+ echo "\$ gh pr list --state all --search $n --json number,state,headRefName,url" >&2
291
+ # Keep the cause, through the same `gh_cause` the `gh issue view` call above
292
+ # uses. Discarding it makes rate-limited, unauthenticated and offline read
293
+ # alike, and all three land on an operator who then has nothing to act on.
294
+ if ! pr_json=$(gh pr list --state all --search "$n" --limit 100 \
295
+ --json number,state,headRefName,url 2>"$errfile"); then
296
+ gh_cause
297
+ add_unknown "pr" "gh pr list failed, so whether #$n is taken is unknown: $(printf '%s' "$err" | tr '\n' ' ')"
298
+ return 1
299
+ fi
300
+
301
+ pr=$(printf '%s' "$pr_json" | NUM="$n" LINKED="$linked" python3 -c '
302
+ import json, os, re, sys
303
+ n = os.environ["NUM"]
304
+ seg = re.compile(r"(^|[/-])" + re.escape(n) + r"([-/]|$)")
305
+ prs = json.load(sys.stdin)
306
+ # Only an OPEN PR is in-flight. A merged PR means the work is done; a closed,
307
+ # unmerged PR means it was abandoned. Either would otherwise make a finished
308
+ # or dead ticket read as taken forever.
309
+ #
310
+ # That applies to BOTH signals, but only the branch half can read the state off
311
+ # its own source. `gh issue view --json closedByPullRequestsReferences` projects
312
+ # only {id, number, repository, url} — measured; the underlying GraphQL nodes are
313
+ # PullRequest and do carry `state`, reachable via `gh api graphql`, but that is a
314
+ # third round-trip. The `gh pr list` window is already fetched and already carries
315
+ # state, so the linked half looks itself up there. Hence one dict, two filters.
316
+ #
317
+ # Keyed by URL, not number: a linked PR can belong to another repository, where
318
+ # its number means nothing here and would collide with a local PR.
319
+ state = {p["url"]: p.get("state") for p in prs}
320
+ out = []
321
+ linked = os.environ["LINKED"].split(",")
322
+ here = "/".join(linked[0].split("/")[3:5]) # owner/repo of the issue
323
+ for url in filter(None, linked[1:]):
324
+ # A PR linked through the Development sidebar need not carry "#N" text
325
+ # anywhere, so the full-text window can miss it; so can a repo with more than
326
+ # the 100 matches asked for, and so does every PR in another repository,
327
+ # which the window never covers. An unknown state stays a hit and says "?"
328
+ # rather than freeing the ticket: a wrong "taken" costs one skipped ticket, a
329
+ # wrong "free" puts two agents on the same one. `or` rather than a dict
330
+ # default, because a present-but-null state is unknown too.
331
+ s = state.get(url) or "?"
332
+ if s not in ("MERGED", "CLOSED"):
333
+ repo, num = "/".join(url.split("/")[3:5]), url.rsplit("/", 1)[-1]
334
+ # Name the repo only when it is not this one, so a foreign hit is
335
+ # diagnosable instead of reading as a local number that does not exist.
336
+ out.append("#%s %s (linked)" % (num, s) if repo == here
337
+ else "%s#%s %s (linked)" % (repo, num, s))
338
+ out += ["#%s %s (branch)" % (p["number"], p["state"]) for p in prs
339
+ if seg.search(p.get("headRefName") or "") and p.get("state") == "OPEN"]
340
+ print(", ".join(out))') || { add_unknown "pr" "could not filter PR search results for #$n"; return 1; }
341
+
342
+ # The fallback is not dead code. No *input* can reach it — the guarded python3
343
+ # above already parses this same `$pr_json` and records an unknown on anything
344
+ # malformed — but this is a second, separate process, so it can fail where the
345
+ # first succeeded: a fork failure under process-table pressure is exactly what
346
+ # a parallel fleet approaches by construction. Left unguarded the failure is
347
+ # simply silent — `probe_pr` is invoked as `probe_pr || :`, which exempts its
348
+ # whole body from `set -e`, and a failed command substitution assigns the empty
349
+ # string rather than leaving `$raw` unset, so `set -u` never fires either.
350
+ # Measured: the tally then prints the hole, `( full-text match(es) considered)`.
351
+ #
352
+ # `raw="?"` and NOT `add_unknown "pr"; return 1`, which is what stood here and
353
+ # was wrong (#96). This count feeds nothing but the two diagnostics below: the
354
+ # PR answer is `$pr`, which the guarded filter above already established, so a
355
+ # tally that could not run leaves that answer entirely intact. Returning here
356
+ # discarded an already-sufficient hit over a cosmetic number — measured exit 2
357
+ # with `hits:[]` while `evidence.pr` read `#12 OPEN (linked)`. A stage that
358
+ # cannot change the answer must not be able to retract it.
359
+ raw=$(printf '%s' "$pr_json" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)))') \
360
+ || raw="?"
361
+ if [ -n "$pr" ]; then
362
+ echo " PRs for #$n: $pr ($raw full-text match(es) considered)" >&2
363
+ add_hit "pr"
364
+ else
365
+ echo " no PR is about #$n ($raw full-text match(es) were all incidental)" >&2
366
+ fi
367
+ }
368
+ # `|| :` is what makes this probe's own failure non-fatal to the run: `set -e`
369
+ # would otherwise treat `probe_pr` returning 1 as fatal exactly the way a bare
370
+ # failing command is, which is precisely the abort this whole change removes.
371
+ #
372
+ # ADDING A COMMAND TO probe_pr: `set -e` does not reach a command run DIRECTLY
373
+ # in the body. POSIX exempts a function's whole execution from `-e` while its
374
+ # status is what an `||` is testing, so the `set -eu` up top aborts on nothing
375
+ # at that level — measured in that shape under /bin/sh, /bin/dash and
376
+ # /bin/bash. A command substitution in the body is a DIFFERENT shape and does
377
+ # not inherit that result: it is a subshell, and only /bin/bash carries the
378
+ # exemption into one. Under /bin/sh and /bin/dash `-e` stays live in there, so
379
+ # a command added inside a `$( … )` is skipped, the capture silently
380
+ # truncates, and the substitution's own `exit` is replaced by the failing
381
+ # command's status — it never reaches the guard this rule asks for. `-u` is
382
+ # exempted at neither level and still aborts, but that abort is no backstop
383
+ # either: under the EXIT trap installed above it exits 0 with no payload — the
384
+ # free verdict — wherever /bin/sh is bash, as it is here, and under /bin/bash;
385
+ # /bin/dash exits 2.
386
+ # A command that feeds a verdict field therefore carries its own
387
+ # `|| { add_unknown "pr" "…"; return 1; }`. Unguarded, its failure leaves the
388
+ # empty result a genuinely free ticket leaves, gets reported as a definite
389
+ # absence, and frees a ticket that is taken — a free verdict puts a second
390
+ # agent on the ticket where a taken one only skips it. A command that cannot
391
+ # change the verdict is the opposite case and must record no unknown, the shape
392
+ # `probe_pr`'s `raw="?"` count already has.
393
+ probe_pr || :
394
+
395
+ # Probe 2 — a remote branch carrying the number as its own path segment.
396
+ probe_remote() {
397
+ echo "\$ git ls-remote --heads origin" >&2
398
+ # The lookup runs on its own, never inside the filter below. A pipeline reports
399
+ # its LAST command's status, so an `ls-remote` that exited 128 used to arrive
400
+ # here as zero matching lines, which is precisely what a clean ticket produces.
401
+ #
402
+ # The two conditions are different answers and must stay apart: "looked, found
403
+ # nothing" leaves the ticket free; "could not look" is what exit 2 is for.
404
+ # Nothing here needs GitHub to be down: an unavailable SSH key or agent will do
405
+ # it, and `gh` authenticates over HTTPS independently, so probe 1 answers fine
406
+ # while this one cannot.
407
+ #
408
+ # stderr is left on stderr rather than folded into the value. That matters less
409
+ # here than in release-ticket.sh's `git ls-remote --heads` pushed-branch lookup,
410
+ # which tests $remote raw, so a folded-in host-key notice really would read as a
411
+ # branch, whereas the awk below reduces such a line to a word no numeric segment
412
+ # can match. git's own wording is more use on the terminal anyway.
413
+ #
414
+ # This is the one network call in the script (probe 1 goes through `gh`, probe
415
+ # 3 never leaves disk), and unattended it must neither prompt nor hang (#92).
416
+ #
417
+ # The knobs that suppress the prompt and the watchdog that bounds the call both
418
+ # live in net.sh now, which every unattended `git` network call in the fleet
419
+ # routes through (#347); its header holds the reasoning and the measurements.
420
+ # What stays here is what is true of THIS call: its budget, and how a killed
421
+ # call is reported.
422
+ #
423
+ # The budget. Above what the ssh options can spend before they give up on their
424
+ # own — ConnectTimeout plus the ServerAlive pair's whole run — so this never
425
+ # preempts a bound that would have produced git's own diagnostic, and short
426
+ # enough that a stalled probe does not hold a fleet slot the way #92 describes.
427
+ # `ls-remote` moves refs and no objects, so this is generous for the work.
428
+ #
429
+ # `INFLIGHT_LS_REMOTE_TIMEOUT` is this call's own override. It can only ever
430
+ # SHORTEN, and the rule with its edge cases is net_budget's, in net.sh.
431
+ ls_budget=$(net_budget 30 "${INFLIGHT_LS_REMOTE_TIMEOUT:-}")
432
+ # A file this probe WANTS, not one it needs. Probe 2 is the one probe that
433
+ # answers when mktemp is broken — #185 fixed that deliberately and
434
+ # inflight.test.mjs pins it — so a failed mktemp costs the sharper wording
435
+ # below, never the verdict. The old exit-status inference is what the wording
436
+ # falls back to there.
437
+ wdfile=$(mktemp) || wdfile=""
438
+ ls_rc=0
439
+ heads=$(net_git "$wdfile" "$ls_budget" ls-remote --heads origin) || ls_rc=$?
440
+ wdnote=""
441
+ if [ "$ls_rc" -ne 0 ]; then
442
+ if [ -n "$wdfile" ]; then
443
+ wdnote=$(net_wdnote "$wdfile")
444
+ elif net_stalled "$ls_rc"; then
445
+ # No marker to read, so the signal number is all there is — the weaker test
446
+ # this branch used before the marker existed, kept only for the path where
447
+ # mktemp failed. It cannot tell our SIGTERM from anyone else's, but
448
+ # reporting a real stall as a refusal is the worse of the two errors. That
449
+ # rule is net_stalled's and net.sh is where it is written down, including
450
+ # why 137 counts as well as 143 — net_kill_tree escalates to SIGKILL and
451
+ # git can lose the race. Spelling it out a second time here is how the two
452
+ # copies come to disagree about which signals mean killed.
453
+ wdnote="fired"
454
+ fi
455
+ # A killed fetch and a refused one are different facts and get different
456
+ # words. Before this bound existed the only failure surface here was reached
457
+ # when `ls-remote` RETURNED, so a probe that never returned reached no label
458
+ # at all and a stall was indistinguishable from a slow link to the caller.
459
+ #
460
+ # $wdfile is what separates them. Reading "the watchdog fired" off an exit
461
+ # status of 143 inferred it from a signal number this script does not own:
462
+ # measured, a fetch SIGTERM'd from OUTSIDE at 4s under the default budget was
463
+ # reported as `did not finish within 30s`, naming a budget only 4s of wall
464
+ # clock had run against. The marker is written by the watchdog and by nothing
465
+ # else, so it answers what the exit status was being asked to guess — and it
466
+ # keeps answering now that net_kill_tree escalates to SIGKILL and git can just as
467
+ # well come back 137.
468
+ kt_note=""
469
+ case $wdnote in
470
+ *degraded*) kt_note=", though the process table could not be read, so a transport helper may still be running" ;;
471
+ esac
472
+ case $wdnote in
473
+ *fired*) add_unknown "remote" "git ls-remote did not finish within ${ls_budget}s and was killed${kt_note}, so whether #$n has a remote branch is unknown" ;;
474
+ *) add_unknown "remote" "git ls-remote failed, so whether #$n has a remote branch is unknown" ;;
475
+ esac
476
+ return 1
477
+ fi
478
+ # One awk, not `awk | sed | grep | paste`. A pipeline hides every status but its
479
+ # last, and the `|| true` that used to close this one discarded that too, so a
480
+ # stage that could not run produced the same empty result a free ticket
481
+ # produces. Collapsed, the status is the filter's own and the guard can read it —
482
+ # and three fewer forks is three fewer ways to fail, a fork failure under
483
+ # process-table pressure being what a parallel fleet approaches by construction.
484
+ #
485
+ # `grep` is what made that delicate: it exits 1 for "looked, found nothing",
486
+ # which is legitimate and must never become exit 2. awk needs no such case
487
+ # separated out — the programs here contain no `exit`, so they return 0 whether
488
+ # or not anything matched, and every non-zero status is a real failure.
489
+ remote=$(printf '%s\n' "$heads" | LC_ALL=C awk -v n="$n" '
490
+ { ref = $2; sub("^refs/heads/", "", ref)
491
+ if (ref ~ "(^|[/-])" n "([-/]|$)") { out = out sep ref; sep = "," } }
492
+ END { printf "%s", out }') ||
493
+ { add_unknown "remote" "could not filter the remote branches for #$n"; return 1; }
494
+ if [ -n "$remote" ]; then
495
+ echo " remote branches: $remote" >&2
496
+ add_hit "remote-branch"
497
+ else
498
+ echo " no remote branch for #$n" >&2
499
+ fi
500
+ }
501
+ # ADDING A COMMAND TO probe_remote: `set -e` does not reach a command run
502
+ # DIRECTLY in the body. POSIX exempts a function's whole execution from `-e`
503
+ # while its status is what an `||` is testing, so the `set -eu` up top aborts
504
+ # on nothing at that level — measured in that shape under /bin/sh, /bin/dash
505
+ # and /bin/bash. A command substitution in the body is a DIFFERENT shape and
506
+ # does not inherit that result: it is a subshell, and only /bin/bash carries
507
+ # the exemption into one. Under /bin/sh and /bin/dash `-e` stays live in
508
+ # there, so a command added inside a `$( … )` is skipped, the capture silently
509
+ # truncates, and the substitution's own `exit` is replaced by the failing
510
+ # command's status — it never reaches the guard this rule asks for. `-u` is
511
+ # exempted at neither level and still aborts, but that abort is no backstop
512
+ # either: under the EXIT trap installed above it exits 0 with no payload — the
513
+ # free verdict — wherever /bin/sh is bash, as it is here, and under /bin/bash;
514
+ # /bin/dash exits 2.
515
+ # A command that feeds a verdict field therefore carries its own
516
+ # `|| { add_unknown "remote" "…"; return 1; }`. Unguarded, its failure leaves
517
+ # the empty result a genuinely free ticket leaves, gets reported as a definite
518
+ # absence, and frees a ticket that is taken — a free verdict puts a second
519
+ # agent on the ticket where a taken one only skips it. A command that cannot
520
+ # change the verdict is the opposite case and must record no unknown, the shape
521
+ # `probe_pr`'s `raw="?"` count already has.
522
+ probe_remote || :
523
+
524
+ # Probe 3 — a local worktree or branch.
525
+ #
526
+ # Same guard shape as probe 2, and it catches the same class: a lookup that
527
+ # could not run at all (git missing, a fork failure, an unreadable packed-refs,
528
+ # which exits 128). That is the floor, not the whole answer: git's own
529
+ # degraded reads exit 0 with output silently missing, which no exit-status
530
+ # guard can see. Measured (#95): `chmod 000` on refs/heads or on the worktree
531
+ # admin dir, and both lookups below report nothing, at rc 0, for a ticket that
532
+ # has a live branch or worktree — the same wrong "free" #76 exists to rule out,
533
+ # one probe down. Establish each storage was readable before trusting an empty
534
+ # result from it — the same rule release-ticket.sh's `-r`/`-x` guard on
535
+ # `$wtroot` already applies to its own worktree-registry read (#84) — absence
536
+ # must be established, never inferred.
537
+ #
538
+ # Ceiling, left open on purpose: a single loose ref git skips as corrupt
539
+ # (`warning: ignoring broken ref refs/heads/x`, still rc 0) passes a
540
+ # directory-level read+execute test — the directory is fine, one file inside
541
+ # it is not — so it stays undetected. Only counting refs against a source
542
+ # independent of git's own read would catch that, roughly doubling this
543
+ # probe's cost, for a fault that usually breaks much else first; out of scope
544
+ # for #95.
545
+ probe_local() {
546
+ common=$(git rev-parse --path-format=absolute --git-common-dir) ||
547
+ { add_unknown "local" "cannot resolve the git common directory"; return 1; }
548
+
549
+ refsdir="$common/refs/heads"
550
+ # Absent is fine and answers nothing here: `git init` creates this directory,
551
+ # but an unusual ref backend (e.g. reftable) may not, and that is storage this
552
+ # check does not reach either way.
553
+ if [ -e "$refsdir" ]; then
554
+ # Two tests, and neither covers the other's case — measured, both directions.
555
+ #
556
+ # The builtin pair below tests only the top of refs/heads, and NO fleet branch
557
+ # lives there: claim-ticket.sh builds `branch="$type/$issue-$slug"`, so the
558
+ # loose ref is `refs/heads/fix/95-…` and the directory that goes unreadable is
559
+ # `refs/heads/fix`, one level down. `chmod 000` there leaves refs/heads itself
560
+ # at 755, the pair passes, and `for-each-ref` drops the branch at rc 0 with
561
+ # nothing on stderr — the wrong "free" this whole change exists to stop,
562
+ # surviving inside its own fix. Distinct from the broken-ref ceiling below:
563
+ # there git warns, here it is silent.
564
+ #
565
+ # So `find` walks the subdirectories. It does not replace the pair, because
566
+ # BSD `find` — the one `sh` resolves on macOS, /usr/bin/find — never evaluates
567
+ # the expression for a starting point it cannot open: `refs/heads` at 000 or
568
+ # 400 yields a stderr error and NOTHING on stdout, exactly as a healthy tree
569
+ # does. (`bfs`, which may shadow it on an interactive PATH, does print it. A
570
+ # guard that reads correct under one and blind under the other is not a
571
+ # guard.) The pair covers the starting point, find covers below it.
572
+ [ -r "$refsdir" ] && [ -x "$refsdir" ] ||
573
+ { add_unknown "local" "refs directory $refsdir could not be read — whether #$n has a local branch is unknown"; return 1; }
574
+ # `-exec test` rather than find's own `-readable`/`-executable`, which are GNU
575
+ # extensions absent from BSD find. `-type d` alone is not enough either: a
576
+ # subdirectory at 400 is readable enough for find to enter and exit 0 while
577
+ # `for-each-ref` still drops the branch, so the permission has to be tested
578
+ # rather than inferred from find's status alone — find exits 1 on the very
579
+ # permission-denied descent that IS the detection, so a hit in `$bad`
580
+ # alongside a nonzero status is the finding, not a crash.
581
+ #
582
+ # find's status still has to be read, though — just not off the pipeline
583
+ # that used to end in `head -1`. This script sets no `pipefail`, so `$?`
584
+ # after `cmd | head -1` reports only `head`'s, and `head` exits 0 whether
585
+ # find printed a permission-denied hit or never ran at all (missing binary,
586
+ # a failed exec, any other swallowed crash) — both leave `$bad` empty, both
587
+ # used to read as a clean tree (#1448, reproduced by shimming `find` on
588
+ # PATH to `exit 127`). find's own status is read off the bare command
589
+ # substitution instead, with nothing piped after it, so nothing that runs
590
+ # after it can stand in for it again.
591
+ #
592
+ # `head`'s own status is kept too, not discarded — a `head` that cannot run
593
+ # (crashed, missing) is the same class of failure, and was the one failure
594
+ # this guard could already see before #1448 (pinned below at "a
595
+ # refs-subdirectory walk whose `head` cannot run is unknown, never free").
596
+ # Reading both separately,
597
+ # rather than trusting whichever one the pipeline's single status happens to
598
+ # expose, is what closes the first gap without reopening the second.
599
+ find_rc=0
600
+ find_out=$(find "$refsdir" -type d ! \( -exec test -r {} \; -a -exec test -x {} \; \) -print 2>/dev/null) ||
601
+ find_rc=$?
602
+ head_rc=0
603
+ bad=$(printf '%s\n' "$find_out" | head -1) || head_rc=$?
604
+ if { [ -z "$bad" ] && [ "$find_rc" -ne 0 ]; } || [ "$head_rc" -ne 0 ]; then
605
+ add_unknown "local" "could not test the refs directories under $refsdir, so whether #$n has a local branch is unknown"
606
+ return 1
607
+ fi
608
+ [ -z "$bad" ] ||
609
+ { add_unknown "local" "refs directory $bad could not be read — whether #$n has a local branch is unknown"; return 1; }
610
+ fi
611
+ # %(refname) and a strip, never %(refname:short): the short form is
612
+ # ambiguity-aware, and where a TAG shares a branch's name it stops shortening
613
+ # and emits `heads/<name>` instead (measured, git 2.50.1 Apple Git-155). That
614
+ # string names no ref — `git branch -D heads/<name>` answers "branch not
615
+ # found" — so the `local branches:` line and the localBranch evidence below
616
+ # both hand an operator a name they cannot paste into a git command.
617
+ # %(refname) is always refs/heads/<name>, so the strip yields the bare name for
618
+ # every branch, ambiguous or not. #634 fixed the same spelling in reap.sh.
619
+ #
620
+ # Here the enumeration fix stands ALONE, and that is a finding about THIS
621
+ # script, not a conclusion carried over from that one. What made the fix unsafe
622
+ # by itself in reap.sh is that it goes on to consume the enumerated name AS A
623
+ # REV (`git cherry "$base" "$b"`), and git resolves an ambiguous rev by
624
+ # preferring refs/tags/ over refs/heads/ — so restoring the bare name made the
625
+ # merge probe answer about the TAG and authorized -D on an unmerged branch
626
+ # (measured, PR #914, which qualifies that one site `refs/heads/$b` for exactly
627
+ # this reason). Every site consuming this value here was enumerated and
628
+ # classified instead:
629
+ #
630
+ # the awk below string match, on the name as reported
631
+ # `[ -n "$local_b" ]`, twice emptiness only
632
+ # `[ -z "$local_b" ]` emptiness only
633
+ # the `local branches:` echo print
634
+ # `add_evidence localBranch` print, through jstr
635
+ #
636
+ # Not one hands the value to git, and this script's other git calls — `rev-parse
637
+ # --git-dir`, `rev-parse --git-common-dir`, `ls-remote --heads origin`,
638
+ # `worktree list --porcelain -z` — take no ref argument built from it. Nor is
639
+ # there a `refs/heads/$b` key to rebuild the way reap.sh's worktree lookup has:
640
+ # probe 3's worktree half matches the LISTING's own paths by basename, never a
641
+ # name from this enumeration. `$local_b` is a comma-joined list besides, so it
642
+ # could not be a rev even by accident. Nothing to qualify. #915
643
+ if ! refs=$(git for-each-ref --format='%(refname)' refs/heads); then
644
+ add_unknown "local" "git for-each-ref failed, so whether #$n has a local branch is unknown"
645
+ return 1
646
+ fi
647
+ # One awk, for the reason probe 2's filter is one: a refname is the whole line,
648
+ # so the strip and the match are both on $0. Stripping BEFORE the match keeps
649
+ # the matched string and the reported string the same one — the two orders
650
+ # select identically anyway, since the prefix carries no digit for an all-digit
651
+ # `n` to match and supplies a `/` exactly where `^` would otherwise apply.
652
+ local_b=$(printf '%s\n' "$refs" | LC_ALL=C awk -v n="$n" '
653
+ { sub(/^refs\/heads\//, "") }
654
+ $0 ~ "(^|[/-])" n "([-/]|$)" { out = out sep $0; sep = "," }
655
+ END { printf "%s", out }') ||
656
+ { add_unknown "local" "could not filter the local branches for #$n"; return 1; }
657
+
658
+ # Commit the branch half here, where it is established — NOT at the end of the
659
+ # probe with the worktree half (#96). Every stage between here and there can
660
+ # fail and `return 1`: the registry read and count, `git worktree list`, the
661
+ # listed-versus-registered compare, the worktree filter. Recording the hit down
662
+ # there meant any one of them threw away a branch that already proves the
663
+ # ticket taken — measured exit 2 with `hits:[]` and `unknown:["local"]` while
664
+ # `evidence.localBranch` named `fix/77-slug` in the same payload.
665
+ #
666
+ # The two halves are independent answers to independent questions. A branch
667
+ # found is found whether or not the worktree registry can be read, and the
668
+ # probe reports the half it answered plus an unknown for the half it could not.
669
+ if [ -n "$local_b" ]; then
670
+ echo " local branches: $local_b" >&2
671
+ add_hit "local"
672
+ fi
673
+
674
+ # The worktree registry's check is a different shape from the one above, on
675
+ # purpose. It began as release-ticket.sh's own fix for this defect (#84) rather
676
+ # than a second invented convention — but the two copies diverged from there
677
+ # and have converged on most of that ground, but not all of it — see the
678
+ # recount below for what still differs. Three of the four items that
679
+ # landed here first — the stray-directory skip, the awk counter and the
680
+ # direction split — were ported to that copy by #395; the recount was the last
681
+ # of the four, ported by #694. That copy's skip reading only `ls`'s output,
682
+ # not its exit STATUS, was a further divergence — #697 closed it: both
683
+ # copies' skip now reads the exit status.
684
+ #
685
+ # Porting the recount did not converge the two copies on it at once, though:
686
+ # this script's recount re-took `registered` alone (`count_registry`), while
687
+ # release-ticket.sh's copy of the SAME recount re-took `registered` AND
688
+ # `linked` together from #1408 on, because re-taking `registered` by itself
689
+ # leaves `linked` pinned to the first listing and can misname a benign
690
+ # concurrent-worktree race as a fault. #1421 closed that divergence here: both
691
+ # copies now re-take the pair, this one through the `count_linked` below. The
692
+ # mechanism under it is still each script's own — that copy reads the listing
693
+ # through worktree.sh's `wt_listing`, this one through the single EXIT trap's
694
+ # `$wtfile` — a difference in plumbing, same as before. What is no longer true
695
+ # is that the recount ITSELF is: #1424 bounds release-ticket.sh's copy at up
696
+ # to two recount passes (`recount_tries`) to close a residual third-mutation
697
+ # race window that this script's own still-single-pass recount does not
698
+ # close.
699
+ #
700
+ # A directory-level read+execute test alone is not enough
701
+ # here: naming a registry entry needs read+execute on the PARENT only, so a
702
+ # `gitdir` file chmod'd 000 INSIDE one entry passes every test on the entry
703
+ # itself while `worktree list --porcelain` still drops it, at rc 0 (measured,
704
+ # #84). Count registry entries on disk against what git reported instead —
705
+ # that catches a silent drop whichever file inside the entry was unreadable.
706
+ wtroot="$common/worktrees"
707
+ # A function because the count is taken twice — see the recount below. Absent
708
+ # entirely is fine and answers nothing here: a repo that never had a linked
709
+ # worktree has no registry directory at all, and that emptiness is real, not a
710
+ # permission problem.
711
+ count_registry() {
712
+ registered=0
713
+ [ -e "$wtroot" ] || return 0
714
+ [ -r "$wtroot" ] && [ -x "$wtroot" ] ||
715
+ { add_unknown "local" "worktree registry $wtroot could not be read — whether #$n has a worktree is unknown"; return 1; }
716
+ for entry in "$wtroot"/*; do
717
+ [ -d "$entry" ] || continue
718
+ # Skip only an EMPTY directory. That is an operator's stray `mkdir`, which
719
+ # git ignores — and counting one fails this probe closed forever, on every
720
+ # ticket in the repo, over something git is right to ignore (measured: git
721
+ # lists 2, a bare `-d` count said 3). A stray FILE was already skipped by
722
+ # the `-d` above; a stray directory was not.
723
+ #
724
+ # Emptiness, NOT the absence of a `gitdir` file: git drops an entry whose
725
+ # `gitdir` was deleted, so keying the skip on that file over-skips into the
726
+ # wrong "free" spelled out below (measured: rc 0, `taken=false`). A corrupt
727
+ # entry still holds git's own files — commondir, HEAD, index, logs, refs —
728
+ # so emptiness separates it from a stray and the missing `gitdir` does not.
729
+ #
730
+ # `ls`'s STATUS, not just its output: an entry we could not LIST is not an
731
+ # empty one, and `2>/dev/null` hides the difference. An entry chmod'd 000
732
+ # (unsearchable) OR 0111 (searchable, so an `-x` test passes it, but not
733
+ # readable) fails EACCES and prints exactly what a stray `mkdir` prints.
734
+ # Over-skip on the missing `gitdir` or on the output alone, and git has
735
+ # dropped the entry too, so the counts AGREE (measured: 2 listed, then 1,
736
+ # and an output-only skip counts 0 to match), no mismatch fires, and the
737
+ # probe answers `taken=false` for a ticket whose checkout is still on disk.
738
+ # Could not read it, so we cannot tell → count it and let the mismatch
739
+ # below fire. #697
740
+ if contents=$(ls -A "$entry" 2>/dev/null) && [ -z "$contents" ]; then continue; fi
741
+ registered=$((registered + 1))
742
+ done
743
+ return 0
744
+ }
745
+ count_registry || return 1
746
+
747
+ # Match on the worktree's basename, not its full path — matching the whole
748
+ # absolute path would false-hit on any checkout whose directory happens to
749
+ # contain the ticket number as an earlier path segment (e.g. a home dir or
750
+ # a sibling directory named with digits), matching every ticket.
751
+ #
752
+ # `--porcelain -z`, into a temp file rather than a command substitution. The
753
+ # plain porcelain terminates every attribute with a newline, and a worktree
754
+ # path may legally contain one (APFS and ext4 both allow it), so one record
755
+ # splits into two. Measured on the plain form (#185): `…/wt/fix-66-a<LF>b`
756
+ # reported `worktree` truncated at `…/fix-66-a`, a path not on disk; and
757
+ # `…/wt/plain<LF>fix-33-slug` left the number on the orphaned second line,
758
+ # where the `^worktree ` filter never looked, so #33 came back `taken=false` at
759
+ # exit 0 with its checkout live — the one answer this script must never invent.
760
+ # A temp file because `-z`'s separator is NUL and no shell variable can hold
761
+ # one, and because it keeps the lookup's status readable on its own, apart from
762
+ # the reader's below: a pipeline would report only the last stage's, so a `git`
763
+ # that could not run at all would read as an empty listing, a wrong "free".
764
+ if ! wtfile=$(mktemp); then
765
+ # Probe-local for the reason probe 1's is: `die` here would abandon a verdict
766
+ # probes 1 and 2 may already have established.
767
+ add_unknown "local" "could not create a temporary file to hold the worktree list, so whether #$n has a worktree is unknown"
768
+ return 1
769
+ fi
770
+ # A function, not inline, because the recount below needs this whole pair —
771
+ # git's own read of the listing and the count derived from it — re-taken
772
+ # TOGETHER rather than one of them re-assigned on its own. `worktrees` and
773
+ # `linked` are this function's OUTPUT, exactly as `registered` is
774
+ # `count_registry`'s — `listed` is scratch the count derives `linked` from and
775
+ # the `-ge 1` guard below checks, never read outside this function, matching
776
+ # release-ticket.sh's own `count_linked`, whose comment (line 383) likewise
777
+ # names only `linked` and `wt_list`/`wt_err`. Mirrors that same extraction over
778
+ # the same pair for the same recount (#1408). #1421
779
+ #
780
+ # The `mktemp` stays ABOVE this function rather than moving inside it, where
781
+ # release-ticket.sh's `wt_listing` creates and removes one of its own: the temp
782
+ # files here are the ONE EXIT trap's at the top of this file, and it holds a
783
+ # single slot per file, so a second `mktemp` in here would overwrite `$wtfile`
784
+ # and leak the first path with nothing said. The re-take truncates the same
785
+ # inode instead — the reason probe 1's second `2>"$errfile"` does, spelled out
786
+ # there.
787
+ #
788
+ # `return 1` inside returns from THIS function now, not from `probe_local`, so
789
+ # every call site carries its own `|| return 1` exactly as `count_registry`'s
790
+ # do. Without it a listing that could not be read would be recorded by
791
+ # `add_unknown` and then walked straight past, and the probe would answer
792
+ # `taken=false` off a listing it never had — the one answer this script must
793
+ # never invent.
794
+ count_linked() {
795
+ # Two operands, one status: the redirect is new here (the base ran this as a
796
+ # command substitution, which had nothing to write to), so a `git` that could
797
+ # not run and a `$wtfile` that could not be written are indistinguishable at
798
+ # this `if`. The message names both rather than blaming git for a write it never
799
+ # reached — the shell prints its own "Permission denied" naming the path when it
800
+ # is the redirect, which is the half a reader can tell apart.
801
+ if ! git worktree list --porcelain -z >"$wtfile"; then
802
+ add_unknown "local" "git worktree list failed, or its output could not be written to $wtfile, so whether #$n has a worktree is unknown"
803
+ return 1
804
+ fi
805
+ # NOT `awk -v RS='\0'`. That is a gawk/BWK extension, and the awk this script
806
+ # actually runs on macOS — /usr/bin/awk, BWK awk 20200816 — does not merely
807
+ # ignore it: it stops dead at the first NUL and reports ONE record for a
808
+ # listing of any length. Measured, all three spellings, `-v RS='\0'`,
809
+ # `-v RS='\000'` and `BEGIN{RS="\0"}`, every one of them `count=1`. No awk
810
+ # program here can hold a NUL byte, so the swap has to happen before awk sees
811
+ # the stream at all.
812
+ #
813
+ # One `tr` pass does it: NUL becomes the newline awk already splits on, and a
814
+ # newline inside a path becomes \001. `tr` translates simultaneously from one
815
+ # table, so the two mappings cannot feed each other the way two piped stages
816
+ # would. Both awks below then read the listing unchanged.
817
+ #
818
+ # Ceiling, deliberate: jstr renders that \001 as a space rather than as `\n`,
819
+ # so a path containing a newline is reported WHOLE but with the newline
820
+ # neutralised — the treatment every C0 byte WITHOUT a JSON short form gets. Not
821
+ # the tab in `…/fix-88-a<TAB>b`: \011 is one of the five RFC 8259 gives a short
822
+ # form, jstr's `sed` escapes it to `\t` before this `tr` stage runs at all, and
823
+ # jrewritten's delete set skips it — so a tab round-trips byte-identical and
824
+ # reports `worktreeRewritten: false`, which is what the probe-3 tab case pins.
825
+ # Swapping the byte back would restore `\n` here at the cost of corrupting the
826
+ # opposite case — a path that really contains \001 — for a diagnostic field
827
+ # whose verdict is already correct either way. One failure mode is better than
828
+ # two.
829
+ if ! worktrees=$(LC_ALL=C tr '\n\000' '\001\n' <"$wtfile"); then
830
+ add_unknown "local" "could not read the worktree list for #$n"
831
+ return 1
832
+ fi
833
+ # The main worktree is always listed first and has no registry entry of its
834
+ # own, hence the -1.
835
+ #
836
+ # awk, not `grep -c … || true`, for exactly the reason probe 2's filter above
837
+ # is one awk. `grep -c` exits 1 on zero matches — legitimate, and `set -e`
838
+ # would read it as fatal — so a `|| true` has to absorb it, and that same
839
+ # `|| true` absorbs a grep that could not RUN AT ALL. Then the count is the
840
+ # empty string, `$((listed - 1))` is -1, and the mismatch report below blames
841
+ # `git worktree list` for a count no listing can produce. awk needs no such
842
+ # case separated out: the program contains no `exit`, so it returns 0 whether
843
+ # or not anything matched and every non-zero status is a real failure.
844
+ listed=$(printf '%s\n' "$worktrees" | LC_ALL=C awk '/^worktree /{c++} END{print c+0}') ||
845
+ { add_unknown "local" "could not count the worktrees git listed for #$n"; return 1; }
846
+ # The guard above closes only the route where awk could not RUN. An empty but
847
+ # SUCCESSFUL listing reaches the same -1: awk exits 0 printing `0`, the guard
848
+ # cannot fire, and the mismatch report below blames `git worktree list` for the
849
+ # very count that guard exists to keep out of an operator's face. One comparison
850
+ # closes it for every branch below at once, the recount included. `-ge 1`, not
851
+ # `-gt 1`: `listed=1` is the main checkout alone, `linked=0`, the ordinary repo
852
+ # with no linked worktree — a guard that refused that would make every probe in
853
+ # a clean repo unknown. Real `git worktree list --porcelain` always prints the
854
+ # main worktree, so reaching this needs a broken or shimmed git; the refusal
855
+ # direction was already right, only the number was nonsense. #699
856
+ [ "$listed" -ge 1 ] ||
857
+ { add_unknown "local" "git listed no worktrees at all for #$n — not even the main checkout, so the listing cannot be trusted"; return 1; }
858
+ linked=$((listed - 1))
859
+ }
860
+ count_linked || return 1
861
+ # Recount before refusing. The two reads happen at different instants, and the
862
+ # gap is not theoretical: measured at ~10ms (two independent methods agreeing —
863
+ # the fork+exec of git, which is almost the whole cost of `worktree list`, and
864
+ # the observed hit rate under churn). A sibling agent's `git worktree add` or
865
+ # `remove` landing in it makes the counts disagree with nothing wrong, which in
866
+ # THIS fleet is routine rather than exotic: measured 1.99% of probes aborting
867
+ # spuriously at λ = 2 mutations/s, 56.6% under saturation.
868
+ #
869
+ # One recount closes it rather than moving it: a mutation landing between the
870
+ # FIRST count and git's listing is already reflected in that listing, so the
871
+ # second count agrees with it — the invariant the ORIGINAL pair above relies
872
+ # on. Escaping still needs a SECOND mutation inside the recount's own window.
873
+ # The two rates #694 measured for recounting at all — 1.99% → 0.00% at
874
+ # λ = 2/s, 56.6% → 1.29% saturated — were taken on the registered-only
875
+ # recount this replaces, so that 1.29% residual bounds what narrowing the
876
+ # window below can still leave rather than describing it; it was not
877
+ # re-measured after that change. A real dropped entry is a standing state,
878
+ # not a moment, so it survives the recount and still refuses (verified: #84's
879
+ # unreadable `gitdir` still aborts).
880
+ #
881
+ # BOTH counts, not `registered` alone, which is what that invariant costs.
882
+ # Re-taking the registry by itself leaves `linked` pinned to the FIRST
883
+ # listing, so a second sibling mutation landing after that listing returned
884
+ # but before the recount re-scans the registry moves one count and not the
885
+ # other. Reproduced in both directions, and they fail differently. Two
886
+ # `git worktree add`s straddling the listing call FLIP the disagreement:
887
+ # `linked -gt registered` on the first pair becomes `linked -lt registered`
888
+ # on the recount, reported as "git listed 1 worktrees for 2 registry entries
889
+ # … the listing is incomplete" — a corruption report for two ordinary adds.
890
+ # A remove then an add makes it PERSIST instead: the registry count comes
891
+ # back to the same 1 for a different entry while `linked` stays at the 0 it
892
+ # read before the add, and the same message fires at 0 against 1. Neither run
893
+ # had anything wrong with it.
894
+ # Re-taking `registered` and `linked` together, in the same order the pair
895
+ # above takes them, hands the RECOUNT pair the invariant too: the window an
896
+ # escape needs is the narrow gap these two calls open between themselves, not
897
+ # the whole span back to the first listing. Both directions pinned in
898
+ # inflight.test.mjs. Mirrors release-ticket.sh's copy of this recount, which
899
+ # #1408 fixed the same way. #1421
900
+ #
901
+ # The retake pair above is still two reads, not one, and the gap it opens
902
+ # between ITSELF — after `count_registry` has already re-scanned but before
903
+ # `count_linked` re-lists — is narrower than the window this recount closes,
904
+ # not zero. A mutation landing there still escapes: `registered` is re-taken
905
+ # first, so an ADD landing in this gap is missed by the registry scan that
906
+ # already ran and IS seen by the git listing still to come — `linked -gt
907
+ # registered`, "the registry read missed entries git can see" — while a
908
+ # REMOVE the same way lands `linked -lt registered`, "the listing is
909
+ # incomplete", indistinguishable from the fault that message exists to name
910
+ # even though nothing here is actually wrong. Pinned in inflight.test.mjs.
911
+ # Reordering to `count_linked && count_registry` does not remove this
912
+ # residual, it only moves the ADD case's false report onto the
913
+ # `linked -lt registered` branch instead — the direction the comment below
914
+ # calls out by name as sending an operator hunting a permissions fault that
915
+ # is not there. `count_registry` first, `count_linked` second, mirrors
916
+ # release-ticket.sh's own recount ordering (count_registry before
917
+ # count_linked) — kept fixed for the reason that copy's own comment gives:
918
+ # not because a different order would be wrong, but so the reasoning above
919
+ # stays about one order instead of two.
920
+ #
921
+ # `&&`, not `;`, between the two: `count_registry` reports an unreadable
922
+ # registry through `add_unknown` and a non-zero return, and under `;` the
923
+ # group's status would be `count_linked`'s alone, so this probe would walk
924
+ # past a refusal it had already recorded. Measured, that is belt-and-braces
925
+ # and not a behaviour difference: every state that fails `count_registry`'s
926
+ # `[ -r ] && [ -x ]` guard also stops git enumerating $wtroot, so `linked`
927
+ # collapses to 0 alongside `registered` and the comparison below matches
928
+ # either way — checked at mode 000 landed inside this very window, under both
929
+ # spellings, and the registry message is the only one reported by both. The
930
+ # `&&` stays because the status of a count that refused is not
931
+ # `count_linked`'s to overwrite, not because a case turns on it today.
932
+ [ "$linked" -eq "$registered" ] || { count_registry && count_linked; } || return 1
933
+ # Name the direction actually observed. The two disagreements have opposite
934
+ # causes and send the reader to opposite places, so one message cannot serve
935
+ # both: FEWER listed than registered is git silently dropping an entry it could
936
+ # not read, which is the fault this whole check exists to catch. MORE listed
937
+ # than registered is the opposite — the on-disk count is the stale read, a
938
+ # sibling agent's `git worktree add` having landed between the two, which in a
939
+ # parallel fleet is routine rather than exotic. Calling that "the listing is
940
+ # incomplete" sends an operator hunting a permissions fault that is not there.
941
+ if [ "$linked" -lt "$registered" ]; then
942
+ add_unknown "local" "git listed $linked worktrees for $registered registry entries in $wtroot — the listing is incomplete, so no absence it reports can be trusted"
943
+ return 1
944
+ elif [ "$linked" -gt "$registered" ]; then
945
+ add_unknown "local" "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"
946
+ return 1
947
+ fi
948
+
949
+ # substr($0,10), never $2, exactly as release-ticket.sh's own substr($0,10) awks
950
+ # read the same field: the porcelain prints the path raw, so a checkout under a
951
+ # directory with a space in it — plain enough on macOS — truncates at the space
952
+ # and the ticket stops matching. That is a wrong "free", the one answer this
953
+ # script must never invent.
954
+ #
955
+ # The basename is taken in the same pass, by dropping everything through the
956
+ # last `/`. It used to be a `basename` subshell per line, which had this defect
957
+ # one level down: a failed fork there yields an empty first field and a silent
958
+ # non-match, and `$(…)` discards the status that would have said so.
959
+ #
960
+ # `\001` counts as a separator for the MATCH, and for the match only. The `tr`
961
+ # above turned every newline inside a path into `\001`, and `\001` is not in
962
+ # `([-/]|$)` — so `…/wt/fix-33<LF>slug` arrives as `fix-33\001slug`, the number
963
+ # stops matching, and a live checkout reads FREE. Measured on real repos with
964
+ # real linked worktrees: plain porcelain `taken=true` rc 1, `--porcelain -z`
965
+ # without this `gsub` `taken=false` rc 0 with `unknown: []` — the probe answers,
966
+ # so nothing upstream catches it. Mapping the byte to `/` in `b` restores that
967
+ # leaf and `…/wt/fix<LF>33-slug`, which the plain form never matched either.
968
+ # `b` is the throwaway copy: `p` is untouched, so the evidence this probe
969
+ # reports — and `worktreeRewritten` with it — still carries the raw bytes.
970
+ wt=$(printf '%s\n' "$worktrees" | LC_ALL=C awk -v n="$n" '
971
+ /^worktree / { p = substr($0,10); b = p; sub(".*/", "", b); gsub(/\001/, "/", b)
972
+ if (b ~ "(^|[/-])" n "([-/]|$)") { out = out sep p; sep = "," } }
973
+ END { printf "%s", out }') ||
974
+ { add_unknown "local" "could not filter the worktree list for #$n"; return 1; }
975
+ if [ -n "$wt" ]; then
976
+ printf ' worktrees: %s\n' "$wt" >&2
977
+ # `hits` is a set of probe names, not a tally, and both halves of this probe
978
+ # answer under the one name — so record it only if the branch half above did
979
+ # not already.
980
+ [ -n "$local_b" ] || add_hit "local"
981
+ elif [ -z "$local_b" ]; then
982
+ echo " no local branch or worktree for #$n" >&2
983
+ fi
984
+ }
985
+ # ADDING A COMMAND TO probe_local: `set -e` does not reach a command run
986
+ # DIRECTLY in the body. POSIX exempts a function's whole execution from `-e`
987
+ # while its status is what an `||` is testing, so the `set -eu` up top aborts
988
+ # on nothing at that level — measured in that shape under /bin/sh, /bin/dash
989
+ # and /bin/bash. A command substitution in the body is a DIFFERENT shape and
990
+ # does not inherit that result: it is a subshell, and only /bin/bash carries
991
+ # the exemption into one. Under /bin/sh and /bin/dash `-e` stays live in
992
+ # there, so a command added inside a `$( … )` is skipped, the capture silently
993
+ # truncates, and the substitution's own `exit` is replaced by the failing
994
+ # command's status — it never reaches the guard this rule asks for. `-u` is
995
+ # exempted at neither level and still aborts, but that abort is no backstop
996
+ # either: under the EXIT trap installed above it exits 0 with no payload — the
997
+ # free verdict — wherever /bin/sh is bash, as it is here, and under /bin/bash;
998
+ # /bin/dash exits 2.
999
+ # A command that feeds a verdict field therefore carries its own
1000
+ # `|| { add_unknown "local" "…"; return 1; }`. Unguarded, its failure leaves
1001
+ # the empty result a genuinely free ticket leaves, gets reported as a definite
1002
+ # absence, and frees a ticket that is taken — a free verdict puts a second
1003
+ # agent on the ticket where a taken one only skips it. A command that cannot
1004
+ # change the verdict is the opposite case and must record no unknown, the shape
1005
+ # `probe_pr`'s `raw="?"` count already has.
1006
+ probe_local || :
1007
+
1008
+ if [ -n "$hits" ]; then
1009
+ # A hit outranks an unknown: the disjunction is monotone, so one sufficient
1010
+ # "yes" answers the question regardless of what any other probe could not
1011
+ # determine. This is the accumulate half of the fix — it is checked first,
1012
+ # unconditionally, however many probes above returned 1.
1013
+ taken=true
1014
+ rc=1
1015
+ elif [ -n "$unknown" ]; then
1016
+ taken=false
1017
+ rc=2
1018
+ else
1019
+ taken=false
1020
+ rc=0
1021
+ fi
1022
+ echo "$NAME: #$n taken=$taken" >&2
1023
+
1024
+ # Every evidence string goes through `jstr` from json.sh. Three of the four are
1025
+ # names chosen elsewhere: git accepts a `"` in a ref, so a branch — local or
1026
+ # remote — carries one in; a worktree path is a filename, so it carries in `\`
1027
+ # as well, which git's ref rules reject. Raw, either emits a payload no JSON
1028
+ # parser accepts. The rule list and its ordering live in json.sh, once, rather
1029
+ # than here and in release-ticket.sh and in no-undo-audit.sh (#119).
1030
+ #
1031
+ # The other three interpolations are not strings and are not wrapped: `$n` is
1032
+ # refused unless it is all digits AND unpadded (the guard's `0?*` arm), which is
1033
+ # what makes it a JSON number and not merely numeric — RFC 8259 forbids a
1034
+ # leading zero, so `007` never reaches this printf (#121); `$taken` is this
1035
+ # script's own true/false, `$hits` only the fixed literals `add_hit` is given.
1036
+ # `$pr` is wrapped with the rest — GitHub's own repo, number and state
1037
+ # vocabulary cannot currently produce a quote, so it is uniformity against a
1038
+ # later edit rather than a reachable vector today.
1039
+
1040
+ # A `$(...)` in printf's ARGUMENT list sits outside the `|| die` on the printf
1041
+ # itself: a substitution that fails contributes an EMPTY argument and printf
1042
+ # still exits 0 — and an unquoted `%s` slot then emits `"...Rewritten":,`,
1043
+ # malformed JSON at exit 0. Assigned first, each one is a simple command whose
1044
+ # status this function can read.
1045
+ #
1046
+ # `die` is NOT the answer here (#120), unlike everywhere else in this script.
1047
+ # The verdict — $taken, $hits, $rc — is already correct by this point; a
1048
+ # formatter that broke AFTER a real answer was established must not convert
1049
+ # that answer into "unanswerable". So a field jstr or jrewritten could not
1050
+ # render becomes JSON `null` — not `""`, which already means "this probe
1051
+ # looked and found nothing" — and the run continues to the payload it earned,
1052
+ # at the verdict's own exit code. A failed `sed` inside `jstr` used to escape
1053
+ # this branch entirely and reach `""` unannounced; json.sh reads each stage's
1054
+ # own status, so it arrives here as a non-zero return like any other (#119).
1055
+ #
1056
+ # The message names the escaper, not just the field, because the two fail
1057
+ # independently: jstr can render a string perfectly while jrewritten cannot
1058
+ # say whether any byte was replaced (break `tr -d` alone and that is exactly
1059
+ # what happens). Naming only the field sends a debugger to whichever of the
1060
+ # two it guesses.
1061
+ #
1062
+ # Accumulates into $evidence rather than handing back a pair per field — the
1063
+ # trailing-comma-then-trim idiom `add_hit` and `add_unknown` already use above
1064
+ # — so each field name is spelled once instead of three times. $ev/$rw/$why
1065
+ # are scratch: not `local` because /bin/sh has no such builtin, and nothing
1066
+ # reads them outside this function.
1067
+ evidence=""
1068
+ add_evidence() {
1069
+ why=""
1070
+ if ! ev=$(jstr "$2"); then
1071
+ why=jstr
1072
+ elif ! rw=$(jrewritten "$2"); then
1073
+ why=jrewritten
1074
+ else
1075
+ ev="\"$ev\""
1076
+ fi
1077
+ if [ -n "$why" ]; then
1078
+ ev=null
1079
+ rw=null
1080
+ echo "$NAME: could not render the $1 evidence for #$n as JSON ($why) — reported as null" >&2
1081
+ fi
1082
+ evidence="${evidence}\"$1\":$ev,\"$1Rewritten\":$rw,"
1083
+ }
1084
+ add_evidence pr "$pr"
1085
+ add_evidence remote "$remote"
1086
+ add_evidence localBranch "$local_b"
1087
+ add_evidence worktree "$wt"
1088
+
1089
+ # Guarded because this runs OUTSIDE the three probe functions, where `set -e` is
1090
+ # still live and a failed write exits 1 — and the contract reads 1 as "taken", a
1091
+ # closed or full stdout rendered as a decision. `sh inflight.sh <N> >&-`
1092
+ # reproduces it. (The probe bodies cannot rely on that: each is invoked as
1093
+ # `probe_X || :`, which exempts the whole body from `set -e`, so every fallible
1094
+ # command in one carries its own guard.) The EXIT trap installed once at the top
1095
+ # of this file is the other site outside that exemption, and carries the same
1096
+ # guard for the same reason — see the `|| printf` on it.
1097
+ #
1098
+ # The evidence slot is an unquoted `%s`, unlike every other string slot in this
1099
+ # printf, and it now carries the object's keys as well as its values:
1100
+ # `add_evidence` above emits each value already wrapped in its own quotes or as
1101
+ # the bare word `null`, so the format string must not wrap it again. Same
1102
+ # reason `hits` and `unknown` are unquoted, and the same `${…%,}` trim.
1103
+ printf '{"issue":%s,"taken":%s,"hits":[%s],"unknown":[%s],"evidence":{%s}}\n' \
1104
+ "$n" "$taken" "${hits%,}" "${unknown%,}" "${evidence%,}" \
1105
+ || die "could not write the verdict for #$n"
1106
+ exit "$rc"