@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,2984 @@
1
+ // Regression gate for inflight.sh, the probe that decides whether a ticket is
2
+ // already being worked on:
3
+ // `node --test plugin/scripts/inflight.test.mjs`.
4
+ //
5
+ // The load-bearing cases are the `linked:` rows. `linked` comes from
6
+ // `gh issue view --json closedByPullRequestsReferences`, which projects only
7
+ // `{id, number, repository, url}` — measured. (The underlying GraphQL nodes are
8
+ // PullRequest and do carry `state`; reaching it costs a third round-trip, so the
9
+ // script reads state off the `gh pr list` window it already fetches.) A state
10
+ // the window cannot supply has to stay a hit rather than silently free a ticket.
11
+ //
12
+ // `gh` is stubbed on PATH; `git`, `python3` and `jq` are real. The stub pipes
13
+ // canned JSON through the real `jq` so the script's own `--jq` expression is
14
+ // under test rather than hard-coded into the fixture. Note that this makes the
15
+ // suite need one binary the script does not: `gh --jq` is an embedded engine, so
16
+ // inflight.sh shells out to no `jq` at all, and a host without it fails this
17
+ // suite while the script itself works fine.
18
+
19
+ import { test } from "node:test";
20
+ import assert from "node:assert/strict";
21
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
22
+ import { mkdtempSync, mkdirSync, writeFileSync, chmodSync, appendFileSync, readFileSync, readdirSync, existsSync, copyFileSync, rmSync } from "node:fs";
23
+ import { tmpdir } from "node:os";
24
+ import { join, dirname } from "node:path";
25
+ import { createServer } from "node:net";
26
+ import { stripComments } from "./strip-comments.mjs";
27
+ import { slowTransport, SSH_URL } from "./slow-transport.mjs";
28
+
29
+ const SCRIPT = join(import.meta.dirname, "inflight.sh");
30
+ const THIS_FILE = import.meta.filename;
31
+
32
+ // The stub shells out to jq. Without it every `gh issue view` would fail and
33
+ // the suite would report exit 2 everywhere — which reads as a real red but
34
+ // proves nothing. Fail loudly instead of passing vacuously.
35
+ try {
36
+ execFileSync("jq", ["--version"], { stdio: "ignore" });
37
+ } catch {
38
+ throw new Error("jq is required to stub `gh --jq`; install it before running this suite");
39
+ }
40
+
41
+ const GH_STUB = `#!/bin/sh
42
+ # Stands in for the two \`gh\` calls inflight.sh makes. Anything else is a bug
43
+ # in the test, not a case to absorb quietly.
44
+ sub="$1 $2"; shift 2
45
+ expr=
46
+ while [ $# -gt 0 ]; do
47
+ case "$1" in --jq) expr=$2; shift 2 ;; *) shift ;; esac
48
+ done
49
+ case "$sub" in
50
+ "issue view")
51
+ # Set-ness, not non-emptiness, so ONE dial covers the whole range: an empty
52
+ # GH_ISSUE_ERR is a failure with NOTHING on stderr, which is also what the
53
+ # redirect itself failing looks like (unwritable /tmp, a full filesystem) —
54
+ # gh never got to print anything, and #91's fix is what stands between that
55
+ # and a blank tail on the message add_unknown builds.
56
+ if [ -n "\${GH_ISSUE_ERR+set}" ]; then printf '%s' "$GH_ISSUE_ERR" >&2; exit 1; fi
57
+ printf '%s' "$GH_ISSUE_JSON" | jq -r "$expr" ;;
58
+ "pr list")
59
+ # The same dial for probe 1's SECOND gh call. This branch had no failure
60
+ # mode at all, so nothing in this file could drive \`gh pr list\` to fail
61
+ # and the half of #91's fix landing here was unpinned — deleting it left
62
+ # the whole suite green (measured).
63
+ if [ -n "\${GH_PR_ERR+set}" ]; then printf '%s' "$GH_PR_ERR" >&2; exit 1; fi
64
+ printf '%s' "$GH_PR_JSON" ;;
65
+ *)
66
+ echo "stub gh: unexpected invocation: $sub" >&2; exit 127 ;;
67
+ esac
68
+ `;
69
+
70
+ const IDENT = {
71
+ GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@example.invalid",
72
+ GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@example.invalid",
73
+ };
74
+
75
+ // Resolved once, and resolved through a shell so it is the same awk the script
76
+ // would have found. The `awkFailWhenProgramHas` shim shadows `awk` on PATH and
77
+ // hands off to the real one for every invocation it is not breaking; calling
78
+ // `awk` from inside the shim would find the shim.
79
+ const REAL_AWK = execFileSync("/bin/sh", ["-c", "command -v awk"], { encoding: "utf8" }).trim();
80
+ const REAL_TR = execFileSync("/bin/sh", ["-c", "command -v tr"], { encoding: "utf8" }).trim();
81
+ // Same reason again, for probe 1's two python3 calls. They are addressed apart
82
+ // by program text the way the awk shim addresses its three filters: the filter
83
+ // call and the counting call parse the same `$pr_json` in the same probe, and
84
+ // which one breaks is the whole difference between "the PR answer is unknown"
85
+ // and "the diagnostic tally is unknown".
86
+ const REAL_PYTHON3 = execFileSync("/bin/sh", ["-c", "command -v python3"], { encoding: "utf8" }).trim();
87
+ // Same reason, for any case that shims `git` itself: the shim has to hand
88
+ // off to the real binary, and calling `git` from inside it would find the shim.
89
+ const REAL_GIT = execFileSync("/bin/sh", ["-c", "command -v git"], { encoding: "utf8" }).trim();
90
+ // Same reason once more, for the one case that shims `head`. Probe 3's refs
91
+ // walk is the only `head` in inflight.sh and json.sh both, so the shim needs no
92
+ // program-text key — but it still has to hand off to the real binary, and
93
+ // calling `head` from inside it would find itself.
94
+ const REAL_HEAD = execFileSync("/bin/sh", ["-c", "command -v head"], { encoding: "utf8" }).trim();
95
+
96
+ /**
97
+ * Writes a `git` shim into `bin`, `body` first, falling through to the real
98
+ * binary. Same shape as release-ticket.test.mjs's `gitShim` — factored out
99
+ * here for the same reason: hand-rolling shebang + `exec REAL_GIT` + a
100
+ * separate `chmodSync` at every site that shims `git` is the duplication,
101
+ * not the shim itself.
102
+ */
103
+ function gitShim(bin, body) {
104
+ writeFileSync(join(bin, "git"), `#!/bin/sh\n${body}\nexec '${REAL_GIT}' "$@"\n`);
105
+ chmodSync(join(bin, "git"), 0o755);
106
+ }
107
+
108
+ // Every chmod-denial fixture below rests on the mode being ENFORCED, and root
109
+ // ignores it: it reads a 0o000 directory and removes a 0o555 one just fine.
110
+ // Under euid 0 those fixtures would not test a weaker thing, they would test a
111
+ // different one — going green under the mutation they exist to catch, exactly
112
+ // the reasoning release-ticket.test.mjs's own `EUID0` carries (#184). Named
113
+ // once rather than inlined at each site, same as there.
114
+ const EUID0 = process.geteuid?.() === 0;
115
+ const NO_DENIAL = "chmod denies nothing under euid 0";
116
+
117
+ /**
118
+ * A branch in the bare origin, built from an empty tree straight in that repo.
119
+ *
120
+ * Deliberately not `push`ed from the local clone: pushing would leave a local
121
+ * branch of the same name behind, probe 3 would hit it too, and a probe-2 case
122
+ * would pass on probe 3's evidence.
123
+ */
124
+ function remoteBranch(bare, name) {
125
+ const g = (args, input) => execFileSync("git", ["-C", bare, ...args],
126
+ { input, encoding: "utf8", env: { ...process.env, ...IDENT } }).trim();
127
+ const commit = g(["commit-tree", g(["hash-object", "-t", "tree", "-w", "--stdin"], ""), "-m", "x"]);
128
+ g(["update-ref", `refs/heads/${name}`, commit]);
129
+ }
130
+
131
+ /**
132
+ * A git repo with `gh` stubbed on PATH.
133
+ *
134
+ * The repo lives in a fixed-name subdirectory, never in the mkdtemp dir itself:
135
+ * probe 3 matches worktrees on basename, and a random mkdtemp suffix that
136
+ * happened to be the ticket number would make every case read as taken.
137
+ *
138
+ * `origin` defaults to a real bare repo because probe 2 now exits 2 when it
139
+ * cannot read one — so a case that means to exercise anything else has to be
140
+ * able to answer probe 2 first. "unreachable" and "none" opt into the two
141
+ * failures that used to be reported as "no remote branch".
142
+ */
143
+ function fixture(t, n, { linked = [], prs = [], issueErr = null, prErr = null, origin = "bare",
144
+ remoteBranches = [], detachedWorktreeUnder = null, worktreeLeaf = null,
145
+ awkFailWhenProgramHas = null,
146
+ trFailWhenArgsHave = null, python3FailWhenProgramHas = null }) {
147
+ const root = mkdtempSync(join(tmpdir(), "inflight-"));
148
+ // Restore the search bits before deleting, rather than trusting each
149
+ // fixture's own inline restore to have run. A fixture that chmods a
150
+ // directory unsearchable and then fails BEFORE restoring it leaves `rm -rf`
151
+ // unable to remove it as a non-root user, and the temp dir leaks with
152
+ // nothing said (release-ticket.test.mjs's `repo()` measured the same class,
153
+ // #184). spawnSync, not execFileSync: a chmod that fails must not become a
154
+ // second error masking the first.
155
+ t.after(() => {
156
+ spawnSync("chmod", ["-R", "u+rwX", root]);
157
+ execFileSync("rm", ["-rf", root]);
158
+ });
159
+
160
+ const bin = join(root, "bin");
161
+ mkdirSync(bin);
162
+ writeFileSync(join(bin, "gh"), GH_STUB);
163
+ chmodSync(join(bin, "gh"), 0o755);
164
+
165
+ // A filter that could not run at all. Written only when a case asks for it,
166
+ // so every other case forks the real awk directly.
167
+ //
168
+ // Selected by a substring of the awk program, never by counting invocations:
169
+ // a count cannot address one filter. The worktree filter used to be two awks
170
+ // in one pipeline, and a pipeline starts its stages concurrently, so both
171
+ // read the same counter before either wrote it — measured, they were both
172
+ // "the second awk" and no invocation was ever the third. A case built on that
173
+ // count broke nothing and passed the script a clean bill of health.
174
+ //
175
+ // Exits 1, deliberately, rather than some louder status: 1 is precisely what
176
+ // the removed `grep … | paste -sd, - || true` shape existed to swallow. A lone
177
+ // awk never returns 1 for "matched nothing" — these programs contain no
178
+ // `exit`, so they return 0 whether or not anything matched, which is what
179
+ // makes any non-zero status readable as a failure.
180
+ if (awkFailWhenProgramHas !== null) {
181
+ writeFileSync(join(bin, "awk"), `#!/bin/sh
182
+ case "$*" in *'${awkFailWhenProgramHas}'*) exit 1 ;; esac
183
+ exec '${REAL_AWK}' "$@"
184
+ `);
185
+ chmodSync(join(bin, "awk"), 0o755);
186
+ }
187
+
188
+ // The same shim shape for `tr`. `-d` addresses jrewritten and nothing else:
189
+ // the other `tr` calls in the script are `tr '\n' ' '` inside `add_unknown`
190
+ // messages — which deliberately do NOT die, that is the whole point of that
191
+ // helper — probe 3's `tr '\n\000' '\001\n'`, addressed by `\000` and by
192
+ // nothing else in the census, and jstr's own, a translation with no flags at
193
+ // all. But jstr's does share jrewritten's character class, `\013\016-\037`,
194
+ // so THAT substring reaches both at once: it is the selector for "neither
195
+ // escaper can run", while `-d` is the selector for "only jrewritten cannot".
196
+ //
197
+ // Both selectors surface as the escaper's own exit status, but not for the
198
+ // same reason, and only one of the two is free. jstr's `tr` is the last
199
+ // stage of its own `sed | tr` pipe, so the pipeline status IS tr's. jrewritten's
200
+ // is not: its last command is an always-0 AND-OR list, and the failure
201
+ // reaches the caller only because `inflight.sh` returns explicitly on it
202
+ // (`|| return 1`). Without that, bash and zsh hand back a confident `true`
203
+ // — see the both-shells test below, which is what pins it.
204
+ // (jstr's `sed` stage was masked the same way and is not any more: #119 moved
205
+ // it into json.sh behind its own capture and `|| return 1`, and json.test.mjs
206
+ // pins it there.)
207
+ if (trFailWhenArgsHave !== null) {
208
+ writeFileSync(join(bin, "tr"), `#!/bin/sh
209
+ case "$*" in *'${trFailWhenArgsHave}'*) exit 1 ;; esac
210
+ exec '${REAL_TR}' "$@"
211
+ `);
212
+ chmodSync(join(bin, "tr"), 0o755);
213
+ }
214
+
215
+ // The same shim shape for `python3`, selected by program text. Probe 1 forks
216
+ // it twice over the same `$pr_json` — once to filter the PRs into the answer,
217
+ // once to count the raw window for a diagnostic — and only a substring can
218
+ // tell those two apart. A count of invocations cannot: the two calls are the
219
+ // reason the fork-failure guard exists at all, and addressing "the second
220
+ // python3" pins a case to an ordering rather than to a stage.
221
+ //
222
+ // Exits 1 for the reason the awk shim does: it stands in for a fork that
223
+ // could not happen, not for a program that ran and disagreed.
224
+ if (python3FailWhenProgramHas !== null) {
225
+ writeFileSync(join(bin, "python3"), `#!/bin/sh
226
+ case "$*" in *'${python3FailWhenProgramHas}'*) exit 1 ;; esac
227
+ exec '${REAL_PYTHON3}' "$@"
228
+ `);
229
+ chmodSync(join(bin, "python3"), 0o755);
230
+ }
231
+
232
+ const repo = join(root, "repo");
233
+ mkdirSync(repo);
234
+ execFileSync("git", ["-c", "init.defaultBranch=main", "init", "-q", repo]);
235
+
236
+ if (origin === "bare") {
237
+ const bare = join(root, "remote.git");
238
+ execFileSync("git", ["init", "-q", "--bare", bare]);
239
+ execFileSync("git", ["-C", repo, "remote", "add", "origin", bare]);
240
+ for (const b of remoteBranches) remoteBranch(bare, b);
241
+ } else if (origin === "unreachable") {
242
+ execFileSync("git", ["-C", repo, "remote", "add", "origin", join(root, "definitely-not-a-repo")]);
243
+ } // "none": no origin configured at all.
244
+
245
+ // Detached on purpose. `worktree add -b` would leave a local branch carrying
246
+ // the same number, and probe 3's branch half would answer for its worktree
247
+ // half — the same "passing for the wrong reason" the bare origin above avoids.
248
+ if (detachedWorktreeUnder !== null) {
249
+ const g = (...args) => execFileSync("git", ["-C", repo, ...args],
250
+ { env: { ...process.env, ...IDENT } });
251
+ g("commit", "-q", "--allow-empty", "-m", "x");
252
+ mkdirSync(join(root, detachedWorktreeUnder), { recursive: true });
253
+ // `worktreeLeaf` names the last path segment outright, for the cases whose
254
+ // whole subject is a byte inside it — a tab, a newline. `??`, not `||`, so
255
+ // a leaf may legally be "" if some case ever wants one; and the default
256
+ // stays the matching `fix-<n>-slug` every other case relies on.
257
+ const leaf = worktreeLeaf ?? `fix-${n}-slug`;
258
+ g("worktree", "add", "-q", "--detach", join(root, detachedWorktreeUnder, leaf), "HEAD");
259
+ }
260
+
261
+ const env = {
262
+ ...process.env,
263
+ PATH: `${bin}:${process.env.PATH}`,
264
+ // A local path can still prompt (a stale credential helper, a host key on
265
+ // an inherited insteadOf rule). An unattended probe that blocks forever is
266
+ // worse than either answer, and a suite that hangs reports nothing at all.
267
+ GIT_TERMINAL_PROMPT: "0",
268
+ // The developer's own git config must not reach these cases, the way
269
+ // release-ticket.test.mjs's GIT_CONFIG_GLOBAL/GIT_CONFIG_SYSTEM already
270
+ // shut it out. Probe 2 only became a hard dependency of this file with the
271
+ // fail-closed guard — before it, a broken origin was swallowed and no
272
+ // config could reach it. Now `protocol.file.allow=never` (documented
273
+ // hardening after CVE-2022-39253) reddens most of the file, and a global
274
+ // `[remote "origin"] url` is worse than red: `remote.<name>.url` is
275
+ // multi-valued, the global entry wins, and "no matching branch" passes
276
+ // while pointed at somebody else's repository.
277
+ GIT_CONFIG_GLOBAL: "/dev/null",
278
+ GIT_CONFIG_SYSTEM: "/dev/null",
279
+ GH_ISSUE_JSON: JSON.stringify({
280
+ url: `https://github.com/${REPO}/issues/${n}`,
281
+ closedByPullRequestsReferences: linked.map((l) =>
282
+ typeof l === "number"
283
+ ? { number: l, url: prUrl(l) }
284
+ : { number: l.number, url: prUrl(l.number, l.repo) }),
285
+ }),
286
+ GH_PR_JSON: JSON.stringify(prs),
287
+ };
288
+ // Inherited git vars outrank `cwd`, so an ambient GIT_DIR silently retargets
289
+ // probe 3 at whatever repo it names — and if that directory is named for the
290
+ // ticket, the reds are shape-identical to the real bug. GH_ISSUE_ERR leaks the
291
+ // same way. Plausible here: a git hook, `rebase --exec`, `bisect run`.
292
+ delete env.GIT_DIR;
293
+ delete env.GIT_WORK_TREE;
294
+ delete env.GH_ISSUE_ERR;
295
+ delete env.GH_PR_ERR;
296
+ // `!== null`, not truthiness: "" is a case in its own right — gh failed and
297
+ // said nothing — not the absence of one.
298
+ if (issueErr !== null) env.GH_ISSUE_ERR = issueErr;
299
+ if (prErr !== null) env.GH_PR_ERR = prErr;
300
+ return { repo, env, bin };
301
+ }
302
+
303
+ test("fixture()'s teardown deletes a root a case left unsearchable (#184, #660)", (t) => {
304
+ if (EUID0) return t.skip(NO_DENIAL);
305
+ // Mirrors release-ticket.test.mjs's own pin for the same class ("repo()'s
306
+ // teardown deletes a root a fixture left unsearchable (#184)"). The shape
307
+ // cannot be reproduced by letting a test body throw: node reports only the
308
+ // body's error and drops the teardown's own ENOTEMPTY on the floor
309
+ // (measured) — the temp dir leaks with nothing said, which is exactly the
310
+ // silence this fix exists to close. `t.after` reaches the runner only
311
+ // through `t`, so a stand-in collects it here, where its effect is
312
+ // assertable directly. Without the `chmod -R u+rwX` before `rm -rf`, the
313
+ // removal below leaves `root` behind and this case is the one that goes red.
314
+ const afters = [];
315
+ const { repo } = fixture({ after: (fn) => afters.push(fn) }, 8, {});
316
+ const root = dirname(repo);
317
+ // Belt and braces: the stand-in's teardown is what is under test, so it must
318
+ // not also be this case's only cleanup.
319
+ t.after(() => {
320
+ spawnSync("chmod", ["-R", "u+rwX", root]);
321
+ rmSync(root, { recursive: true, force: true });
322
+ });
323
+
324
+ chmodSync(join(repo, ".git"), 0o000);
325
+ for (const after of afters) after();
326
+ assert.equal(existsSync(root), false, "the temp root must not survive an unrestored chmod");
327
+ });
328
+
329
+ function inflight(n, opts, t) {
330
+ const { repo, env } = fixture(t, n, opts);
331
+ const r = spawnSync("sh", [SCRIPT, String(n)], { cwd: repo, env, encoding: "utf8" });
332
+ return {
333
+ code: r.status,
334
+ stderr: r.stderr,
335
+ json: r.stdout.trim() ? JSON.parse(r.stdout) : null,
336
+ };
337
+ }
338
+
339
+ const REPO = "feigi/claude-config";
340
+ const prUrl = (number, repo = REPO) => `https://github.com/${repo}/pull/${number}`;
341
+ const pr = (number, state, headRefName, repo = REPO) =>
342
+ ({ number, state, headRefName, url: prUrl(number, repo) });
343
+
344
+ // --- linked: every state this script can end up attributing to an entry.
345
+ // GitHub's PullRequestState has three (OPEN, CLOSED, MERGED); "?" is this
346
+ // script's own marker for a state the search window could not supply.
347
+
348
+ // The reported bug, in the shape it was measured in: issue #8 is closed by
349
+ // MERGED #20, and read as taken=true forever.
350
+ test("linked: a MERGED PR is finished work, not in-flight", (t) => {
351
+ const r = inflight(8, { linked: [20], prs: [pr(20, "MERGED", "fix/other-thing")] }, t);
352
+ assert.equal(r.code, 0);
353
+ assert.equal(r.json.taken, false);
354
+ assert.equal(r.json.evidence.pr, "");
355
+ });
356
+
357
+ test("linked: a CLOSED, unmerged PR is abandoned work, not in-flight", (t) => {
358
+ const r = inflight(8, { linked: [20], prs: [pr(20, "CLOSED", "fix/other-thing")] }, t);
359
+ assert.equal(r.code, 0);
360
+ assert.equal(r.json.taken, false);
361
+ assert.equal(r.json.evidence.pr, "");
362
+ });
363
+
364
+ test("linked: an OPEN PR is in-flight, and the evidence names its state", (t) => {
365
+ const r = inflight(7, { linked: [12], prs: [pr(12, "OPEN", "fix/other-thing")] }, t);
366
+ assert.equal(r.code, 1);
367
+ assert.equal(r.json.taken, true);
368
+ assert.equal(r.json.evidence.pr, "#12 OPEN (linked)");
369
+ });
370
+
371
+ // A PR linked through the Development sidebar carries no `#N` text, so the
372
+ // full-text window can miss it — as can a repo with more than 100 matches.
373
+ // Unknown must stay a hit: a false "taken" costs a skipped ticket, a false
374
+ // "free" costs two agents on one ticket.
375
+ test("linked: a PR outside the search window stays a hit, with the state marked unknown", (t) => {
376
+ const r = inflight(7, { linked: [12], prs: [] }, t);
377
+ assert.equal(r.code, 1);
378
+ assert.equal(r.json.taken, true);
379
+ assert.equal(r.json.evidence.pr, "#12 ? (linked)");
380
+ });
381
+
382
+ // A present-but-null state is as unknown as an absent one. `.get(url, "?")`
383
+ // would return None here and print it, contradicting the promise of "?".
384
+ test("linked: a null state reads as unknown, not as the literal None", (t) => {
385
+ const r = inflight(8, { linked: [20], prs: [pr(20, null, "unrelated")] }, t);
386
+ assert.equal(r.code, 1);
387
+ assert.equal(r.json.evidence.pr, "#20 ? (linked)");
388
+ });
389
+
390
+ // More than one closing reference is ordinary — two PRs, one ticket — and every
391
+ // other case here passes 0 or 1, so this is the only one that iterates. It does
392
+ // not pin the `join(",")`/`split(",")` contract: a wrong separator collapses the
393
+ // list to a single element and yields the same exit 0 this asserts. The rows
394
+ // above cover that, because the issue's own URL is field 0 and losing it takes
395
+ // every linked row with it.
396
+ test("linked: two MERGED PRs are both finished, not in-flight", (t) => {
397
+ const r = inflight(7, { linked: [12, 13], prs: [pr(12, "MERGED", "a"), pr(13, "MERGED", "b")] }, t);
398
+ assert.equal(r.code, 0);
399
+ assert.equal(r.json.evidence.pr, "");
400
+ });
401
+
402
+ // `Closes owner/repo#N` from a fork is legal, which is why the node carries
403
+ // `repository`. Its number is meaningless here: keyed by number it would inherit
404
+ // the state of the unrelated local #5 and be filtered out, freeing a taken
405
+ // ticket. Keyed by URL it cannot collide, so it stays an unknown-state hit.
406
+ test("linked: a PR in another repo does not inherit a local PR's state", (t) => {
407
+ const r = inflight(77, {
408
+ linked: [{ number: 5, repo: "other/fork" }],
409
+ prs: [pr(5, "MERGED", "unrelated")],
410
+ }, t);
411
+ assert.equal(r.code, 1);
412
+ assert.equal(r.json.taken, true);
413
+ assert.equal(r.json.evidence.pr, "other/fork#5 ? (linked)");
414
+ });
415
+
416
+ // --- both signals, and the branch half that already worked.
417
+
418
+ test("both probes hitting the same PR still report both, each with its state", (t) => {
419
+ const r = inflight(33, { linked: [40], prs: [pr(40, "OPEN", "fix/33-probe")] }, t);
420
+ assert.equal(r.code, 1);
421
+ assert.equal(r.json.evidence.pr, "#40 OPEN (linked), #40 OPEN (branch)");
422
+ });
423
+
424
+ test("branch: a MERGED branch-matched PR is still filtered out", (t) => {
425
+ const r = inflight(33, { linked: [], prs: [pr(40, "MERGED", "fix/33-probe")] }, t);
426
+ assert.equal(r.code, 0);
427
+ assert.equal(r.json.taken, false);
428
+ });
429
+
430
+ test("branch: an OPEN branch-matched PR is still a hit", (t) => {
431
+ const r = inflight(33, { linked: [], prs: [pr(40, "OPEN", "fix/33-probe")] }, t);
432
+ assert.equal(r.code, 1);
433
+ assert.equal(r.json.evidence.pr, "#40 OPEN (branch)");
434
+ });
435
+
436
+ // The count is the unfiltered size of the search window, not the hit count —
437
+ // it is what tells a reader the search was noisy rather than the ticket busy.
438
+ test("the considered-count reports every full-text match, filtered or not", (t) => {
439
+ const r = inflight(8, { linked: [], prs: [pr(1, "MERGED", "a"), pr(2, "OPEN", "b"), pr(3, "CLOSED", "c")] }, t);
440
+ assert.match(r.stderr, /\(3 full-text match\(es\) were all incidental\)/);
441
+ });
442
+
443
+ // --- probe 2, the remote-branch lookup.
444
+ //
445
+ // `git ls-remote` used to run inside the filtering pipeline, and a pipeline
446
+ // reports its LAST command's status — `paste`, which always succeeds. So the
447
+ // lookup's exit 128 never reached the script at all, and `2>/dev/null` dropped
448
+ // the reason with it. What arrived was zero matching lines, which is exactly
449
+ // what a clean ticket produces. Dropping the trailing `|| true` alone would not
450
+ // have changed that: `|| true` was never the thing swallowing it.
451
+ //
452
+ // The two directions are separate answers and both are pinned below: `grep`
453
+ // exiting 1 is "looked, found nothing" and must stay a free ticket; a failed
454
+ // `ls-remote` is "could not look" and must reach exit 2. A fix that collapses
455
+ // them the other way makes every clean ticket unanswerable.
456
+
457
+ test("probe 2: an unreachable origin is an unknown answer, never a 'no remote branch'", (t) => {
458
+ // The direction that matters: a wrong "taken" costs one skipped ticket, a
459
+ // wrong "free" puts two agents on the same one.
460
+ const r = inflight(8, { origin: "unreachable" }, t);
461
+ assert.equal(r.code, 2, "unanswerable is exit 2, not the exit 0 that means free");
462
+ assert.match(r.stderr, /whether #8 has a remote branch is unknown/);
463
+ assert.doesNotMatch(r.stderr, /no remote branch/);
464
+ // #96: exit 2 from a probe failure now carries a payload — "unanswered"
465
+ // stopped meaning "no verdict to parse" once probes stopped aborting the run.
466
+ assert.deepEqual(r.json.hits, [], "nothing else ran that could have found a hit here");
467
+ assert.deepEqual(r.json.unknown, ["remote"]);
468
+ });
469
+
470
+ // Not a synthetic non-zero exit: this is the plain "no origin configured" a
471
+ // fresh clone-less checkout has, and it took the same silent path.
472
+ test("probe 2: an origin that is not configured at all is unknown, not free", (t) => {
473
+ const r = inflight(8, { origin: "none" }, t);
474
+ assert.equal(r.code, 2);
475
+ assert.match(r.stderr, /whether #8 has a remote branch is unknown/);
476
+ assert.deepEqual(r.json.hits, []);
477
+ assert.deepEqual(r.json.unknown, ["remote"]);
478
+ });
479
+
480
+ // The opposite direction. This one passed before the fix too, which is the
481
+ // point — it fails only if the fix over-reaches and turns `grep`'s no-match
482
+ // exit 1 into a death, making every clean ticket unanswerable.
483
+ test("probe 2: a reachable origin with no matching branch still reports free", (t) => {
484
+ const r = inflight(8, { remoteBranches: ["main", "fix/other-thing"] }, t);
485
+ assert.equal(r.code, 0);
486
+ assert.equal(r.json.taken, false);
487
+ assert.equal(r.json.evidence.remote, "");
488
+ // The disclosure bit for a field that legitimately found nothing. jrewritten
489
+ // short-circuits on empty input without forking `tr`, and the value it
490
+ // returns for that case is asserted nowhere else: every other *Rewritten
491
+ // assertion in this file sits on a non-empty field. So flipping the
492
+ // short-circuit's own `printf false` to `printf true` passes all 61 other
493
+ // tests — measured — and ships `"remoteRewritten":true` about a string no
494
+ // escaper ever looked at, which is #120's lie in a different slot.
495
+ assert.equal(r.json.evidence.remoteRewritten, false);
496
+ assert.match(r.stderr, /no remote branch for #8/);
497
+ });
498
+
499
+ test("probe 2: a reachable origin with a matching branch still reports taken", (t) => {
500
+ const r = inflight(33, { remoteBranches: ["main", "fix/33-probe"] }, t);
501
+ assert.equal(r.code, 1);
502
+ assert.equal(r.json.taken, true);
503
+ assert.equal(r.json.evidence.remote, "fix/33-probe");
504
+ assert.deepEqual(r.json.hits, ["remote-branch"], "probe 2 alone, not probe 3 answering for it");
505
+ });
506
+
507
+ // --- probe 3, the worktree lookup.
508
+ //
509
+ // `worktree list --porcelain` prints the path raw, so reading it as awk's $2
510
+ // truncates at the first space and the ticket stops matching — a wrong "free",
511
+ // the same answer probe 2 was just stopped from inventing. The pair below is
512
+ // one fixture differing in one character, so a red names the space and nothing
513
+ // else. release-ticket.sh's own awks already read this field as substr($0,10).
514
+
515
+ test("probe 3: a worktree under a path with a space is still found", (t) => {
516
+ const r = inflight(77, { detachedWorktreeUnder: "some dir" }, t);
517
+ assert.equal(r.code, 1, "a worktree that exists must never read as free");
518
+ assert.equal(r.json.taken, true);
519
+ assert.match(r.json.evidence.worktree, /some dir\/fix-77-slug$/);
520
+ assert.deepEqual(r.json.hits, ["local"]);
521
+ });
522
+
523
+ test("probe 3: the same worktree without a space in the path, as the control", (t) => {
524
+ const r = inflight(77, { detachedWorktreeUnder: "nospace" }, t);
525
+ assert.equal(r.code, 1);
526
+ assert.match(r.json.evidence.worktree, /nospace\/fix-77-slug$/);
527
+ });
528
+
529
+ // --- probe 3, bytes inside the path that the LISTING's own framing can eat.
530
+ //
531
+ // The space above is eaten by awk's field splitting, one level up from these:
532
+ // these four are eaten by the record framing itself, before any field exists.
533
+ // `--porcelain` terminates each attribute with a newline, so a path containing
534
+ // one splits into two records; `--porcelain -z` terminates with NUL, which no
535
+ // path may contain, so it cannot (#185, and #89's last unmet criterion).
536
+ //
537
+ // The tab is here because it is the same class and was fixed one stage away:
538
+ // PR #174 dropped a `-F'\t'` join that cut the path at the tab it had just
539
+ // joined on, and nothing pinned the repair — the existing \001 control-byte
540
+ // case does not reach a tab, so an edit re-introducing a tab-sensitive split
541
+ // would re-truncate the evidence with the suite still green (#122, absorbed
542
+ // into #89). The `-z` rewrite re-parses this listing anyway, so both pins land
543
+ // together rather than leaving one of the pair defended by nothing.
544
+ //
545
+ // Verified red first, each against the plain-porcelain form (git 2.50.1):
546
+ // fix-66-a<LF>b -> evidence ".../fix-66-a", a path not on disk
547
+ // plain<LF>fix-33-slug -> taken=false, hits=[], exit 0, checkout live
548
+ // fix-88-a<TAB>b -> already whole; green before and after, by design
549
+ // plain<LF>worktree /x -> exit 2, "the registry read missed entries"
550
+ //
551
+ // One case in this block is red against the OTHER form instead, and says so in
552
+ // its own comment: `fix-22<LF>slug` passes under the plain porcelain (rc 1) and
553
+ // fails under `--porcelain -z` read without the matcher's `\001` mapping (rc 0,
554
+ // a live checkout reported free). Its sibling `plain<LF>fix-33-slug` is the
555
+ // mirror image. A suite carrying only one of the pair is green over whichever
556
+ // spelling the other one holds — which is how it shipped that way once.
557
+
558
+ test("probe 3: a newline in the worktree path does not truncate the evidence", (t) => {
559
+ // The milder half: the number is on the FIRST line, so the verdict was
560
+ // already right and only the reported path was cut. Wrong all the same — an
561
+ // operator handed ".../fix-66-a" finds nothing there.
562
+ const r = inflight(66, { detachedWorktreeUnder: "wt", worktreeLeaf: "fix-66-a\nb" }, t);
563
+ assert.equal(r.code, 1);
564
+ assert.equal(r.json.taken, true);
565
+ // A space, not a newline: jstr neutralises every C0 byte without a JSON
566
+ // short form, and the swap that gets this listing past awk has already made
567
+ // it \001. Whole is the claim being pinned here, not byte-identical — the
568
+ // `b` is what the truncation dropped.
569
+ assert.match(r.json.evidence.worktree, /\/wt\/fix-66-a b$/,
570
+ "the whole leaf arrives, not the part before the newline");
571
+ assert.equal(r.json.evidence.worktreeRewritten, true,
572
+ "and the caller is told the bytes were replaced, so it cannot take this for a real path");
573
+ });
574
+
575
+ test("probe 3: a worktree whose number falls AFTER a newline is taken, never free", (t) => {
576
+ // The severe half, and the reason #185 outranks its own truncation sibling:
577
+ // the number lands on the ORPHANED second record, where the `^worktree `
578
+ // filter never looks, so the probe reported a live checkout as free. Exit 0
579
+ // is what puts two implementers on one ticket — the one answer this script
580
+ // must never invent.
581
+ const r = inflight(33, { detachedWorktreeUnder: "wt", worktreeLeaf: "plain\nfix-33-slug" }, t);
582
+ assert.equal(r.code, 1, "a worktree that exists must never read as free");
583
+ assert.equal(r.json.taken, true);
584
+ assert.deepEqual(r.json.hits, ["local"]);
585
+ assert.match(r.json.evidence.worktree, /\/wt\/plain fix-33-slug$/);
586
+ });
587
+
588
+ test("probe 3: a newline immediately after the number is taken, never free", (t) => {
589
+ // The pair to the case above, failing in the OPPOSITE direction — which is
590
+ // why neither covers the other, and why a `-z` rewrite carrying only the
591
+ // sibling shipped green over this one.
592
+ //
593
+ // `plain<LF>fix-33-slug` breaks when the record SPLITS: the number lands on
594
+ // the orphaned second line, where `^worktree ` never looks. This leaf breaks
595
+ // when the record is WHOLE: `tr` has turned the embedded newline into \001,
596
+ // and \001 is not in the matcher's separator class `([-/]|$)`, so
597
+ // `fix-22\001slug` stops matching 22 and a live checkout reads free at exit 0
598
+ // with `unknown: []` — the probe answering, not refusing, so nothing upstream
599
+ // catches it. Measured on real repos with real linked worktrees: plain
600
+ // porcelain rc 1, `--porcelain -z` without the matcher's `gsub` rc 0.
601
+ //
602
+ // The number sits between real `-` bytes in every other case here, which is
603
+ // exactly why every other case is blind to this one.
604
+ const r = inflight(22, { detachedWorktreeUnder: "wt", worktreeLeaf: "fix-22\nslug" }, t);
605
+ assert.equal(r.code, 1, `a worktree that exists must never read as free: ${r.stderr}`);
606
+ assert.equal(r.json.taken, true);
607
+ assert.deepEqual(r.json.hits, ["local"]);
608
+ assert.deepEqual(r.json.unknown, [], "and taken by answering, not by failing to look");
609
+ assert.match(r.json.evidence.worktree, /\/wt\/fix-22 slug$/);
610
+ assert.equal(r.json.evidence.worktreeRewritten, true,
611
+ "the caller is told the bytes were replaced, so it cannot take this for a real path");
612
+ });
613
+
614
+ test("probe 3: a TAB in the worktree path is delivered whole, and losslessly", (t) => {
615
+ // PR #174's repair, pinned at last. Distinct from the newline pair above in
616
+ // its result as well as its cause: \011 is one of the five C0 bytes RFC 8259
617
+ // gives a short form, so jstr escapes it as `\t` rather than replacing it,
618
+ // and `jrewritten`'s `tr -d` set skips it. The path survives byte-identical.
619
+ const r = inflight(88, { detachedWorktreeUnder: "wt", worktreeLeaf: "fix-88-a\tb" }, t);
620
+ assert.equal(r.code, 1);
621
+ assert.equal(r.json.taken, true);
622
+ assert.match(r.json.evidence.worktree, /\/wt\/fix-88-a\tb$/,
623
+ "the real tab, round-tripped through JSON — not a space and not a truncation");
624
+ assert.equal(r.json.evidence.worktreeRewritten, false,
625
+ "nothing was replaced, so the path may be taken literally");
626
+ });
627
+
628
+ test("probe 3: a newline followed by a second 'worktree ' line does not fake a registry mismatch", (t) => {
629
+ // The same root cause pointed at the COUNT rather than the filter, and it
630
+ // fails the opposite way: the orphaned record begins with `worktree `, so the
631
+ // count saw one listing too many, `linked > registered` fired, and the probe
632
+ // refused — exit 2, "the registry read missed entries git can see". A wrong
633
+ // refusal starves the queue as surely as a wrong "free" collides on it, and
634
+ // this one is self-inflicted by the parser rather than by any real fault.
635
+ // No `/` anywhere in the leaf, deliberately: `join` would read one as a
636
+ // directory boundary and the basename the filter matches on would become
637
+ // whatever followed it, which is a different case wearing this one's name.
638
+ const r = inflight(44, {
639
+ detachedWorktreeUnder: "wt", worktreeLeaf: "a\nworktree fix-44-slug",
640
+ }, t);
641
+ assert.equal(r.code, 1, `a path that merely looks like a record is not a mismatch: ${r.stderr}`);
642
+ assert.equal(r.json.taken, true);
643
+ assert.deepEqual(r.json.unknown, [], "the probe answered rather than refusing");
644
+ assert.doesNotMatch(r.stderr, /registry entries/);
645
+ });
646
+
647
+ test("probe 3: an ordinary worktree list still reports a genuinely free ticket as free", (t) => {
648
+ // The accept case, and it is not covered by the "never had a linked
649
+ // worktree" case further down: this repo HAS one, git lists it, the count
650
+ // matches and the filter simply does not match the number. That is the path
651
+ // a stricter record separator can break without breaking any reject case —
652
+ // a parser that reads one record as zero, or that lets `tr`'s status pass
653
+ // unexamined, answers "taken" for every free ticket in the repo and the
654
+ // fleet quietly stops claiming work. Green before #185 and after, by intent.
655
+ const r = inflight(55, { detachedWorktreeUnder: "wt", worktreeLeaf: "fix-99-ordinary" }, t);
656
+ assert.equal(r.code, 0, `a free ticket must stay free: ${r.stderr}`);
657
+ assert.equal(r.json.taken, false);
658
+ assert.deepEqual(r.json.hits, []);
659
+ assert.deepEqual(r.json.unknown, [], "and free by answering, not by failing to look");
660
+ assert.equal(r.json.evidence.worktree, "");
661
+ });
662
+
663
+ test("probe 3: a backslash in the worktree path reaches the operator's listing whole", (t) => {
664
+ // ` worktrees: $wt` is this script's only stderr report of a path, and it
665
+ // ran through `echo`, which expands escapes in its operand: a `\c` truncated
666
+ // the line at `back`, swallowed its newline, and left the next line collided
667
+ // onto the remains — the operator handed a path that does not exist (#484).
668
+ //
669
+ // `\c`, never `\s`: an unknown escape passes through `echo` unharmed, so a
670
+ // `back\slash` fixture reads as coverage and catches nothing. The assertion
671
+ // takes the whole leaf WITH its newline for the same reason — the truncated
672
+ // head is exactly what survives the defect, so a substring match on it would
673
+ // pass against the bug.
674
+ //
675
+ // The pair to this is printf-die-sweep.test.mjs, which pins one line per
676
+ // script; this file owns inflight.sh's, because the fixture apparatus for a
677
+ // linked worktree already lives here.
678
+ const r = inflight(66, { detachedWorktreeUnder: "wt", worktreeLeaf: "fix-66-back\\clue" }, t);
679
+ assert.equal(r.code, 1, `a worktree that exists must never read as free: ${r.stderr}`);
680
+ assert.equal(r.json.taken, true);
681
+ assert.match(
682
+ r.stderr,
683
+ /\n {4}worktrees: \S*\/wt\/fix-66-back\\clue\n/,
684
+ `the path must arrive verbatim and newline-terminated; got ${JSON.stringify(r.stderr)}`,
685
+ );
686
+ });
687
+
688
+ test("probe 3: a translation that cannot run refuses, rather than reading an empty listing as free", (t) => {
689
+ // The guard on the `tr` that makes the NUL-delimited listing readable by awk.
690
+ // Probe 3's other two status checks — the count and the filter — each have a
691
+ // case; this one shipped with none, and replacing its `add_unknown …; return
692
+ // 1` with a silent `return 0` left the whole suite green (measured).
693
+ //
694
+ // What it stands for is a fork that could not happen rather than a program
695
+ // that ran and disagreed: `tr` exits non-zero having printed nothing, `$(…)`
696
+ // yields the empty string, and an empty listing matches no worktree — so
697
+ // without the guard this repo's live `fix-77-slug` checkout reports FREE at
698
+ // exit 0, the one answer this script must never invent.
699
+ //
700
+ // `\000` addresses this call and no other: the two `tr '\n' ' '` calls inside
701
+ // `add_unknown`'s messages carry no NUL, jstr's selector is
702
+ // `\001-\007\013\016-\037` and jrewritten's is `-d` plus that same set.
703
+ const r = inflight(77, { detachedWorktreeUnder: "wt", trFailWhenArgsHave: "\\000" }, t);
704
+ assert.equal(r.code, 2, `a listing that could not be read is unknown, never free: ${r.stderr}`);
705
+ assert.equal(r.json.taken, false);
706
+ assert.deepEqual(r.json.hits, [], "nothing was established — this is not a hit");
707
+ assert.deepEqual(r.json.unknown, ["local"], "refused, rather than answering off an empty string");
708
+ assert.match(r.stderr, /could not read the worktree list for #77/);
709
+ assert.equal(r.json.evidence.worktree, "");
710
+ });
711
+
712
+ // --- probe 3, degraded reads (#95).
713
+ //
714
+ // `for-each-ref` and `worktree list --porcelain` both exit 0 while silently
715
+ // dropping what they cannot read, so an exit-status guard never sees it. A
716
+ // live branch or worktree then reads as "no local branch or worktree" — the
717
+ // wrong "free" #76 exists to rule out, one probe down. Real chmod throughout;
718
+ // no way to fake a degraded git read other than triggering the real one.
719
+
720
+ test("probe 3: an unreadable refs directory is unknown, never a free ticket", (t) => {
721
+ if (EUID0) return t.skip(NO_DENIAL);
722
+ // The issue's own repro: a live branch, `chmod 000 .git/refs/heads`, and the
723
+ // pre-fix script answers `taken=false`.
724
+ const { repo, env } = fixture(t, 55, {});
725
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
726
+ git(repo, env, "branch", "fix-55-real");
727
+ const refsdir = join(repo, ".git", "refs", "heads");
728
+
729
+ // 0o400 (read, no execute) is what tells the guard's `&&` from an `||`: with
730
+ // `||` a readable-but-not-searchable directory would satisfy `-r` alone and
731
+ // pass. 0o000 zeroes both bits at once and cannot make that distinction, but
732
+ // it is the realistic fault the issue measured, so both are checked.
733
+ for (const mode of [0o000, 0o400]) {
734
+ chmodSync(refsdir, mode);
735
+ const r = spawnSync("sh", [SCRIPT, "55"], { cwd: repo, env, encoding: "utf8" });
736
+ // Restored before the first assert, or a failure here leaves a fixture the
737
+ // suite's own cleanup cannot remove.
738
+ chmodSync(refsdir, 0o755);
739
+
740
+ const at = `mode 0o${mode.toString(8).padStart(3, "0")}`;
741
+ assert.equal(r.status, 2, at);
742
+ const json = JSON.parse(r.stdout);
743
+ assert.deepEqual(json.hits, [], `no probe found a hit, ${at}`);
744
+ assert.deepEqual(json.unknown, ["local"], `#96: exit 2 now carries a payload naming the probe, ${at}`);
745
+ assert.match(r.stderr, /refs directory .* could not be read/, at);
746
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/, at);
747
+ }
748
+ });
749
+
750
+ test("probe 3: an unreadable refs SUBdirectory is unknown too — every fleet branch is in one", (t) => {
751
+ if (EUID0) return t.skip(NO_DENIAL);
752
+ // The case above chmods the top of `refs/heads`, and no fleet branch lives
753
+ // there: `claim-ticket.sh` builds `branch="$type/$issue-$slug"`, so the real
754
+ // ref is `refs/heads/fix/95-…`, one level down. A guard that tests only the
755
+ // top directory leaves the entire realistic class open — `for-each-ref` then
756
+ // drops the branch at rc 0 with nothing on stderr, and #95's own wrong "free"
757
+ // survives its own fix.
758
+ const { repo, env } = fixture(t, 95, {});
759
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
760
+ git(repo, env, "branch", "fix/95-inflight-degraded-reads");
761
+ const typedir = join(repo, ".git", "refs", "heads", "fix");
762
+
763
+ // Both modes, for the reason the case above checks both: 0o000 is the
764
+ // realistic fault, 0o400 is the one that tells an `&&` from an `||`.
765
+ for (const mode of [0o000, 0o400]) {
766
+ chmodSync(typedir, mode);
767
+ const r = spawnSync("sh", [SCRIPT, "95"], { cwd: repo, env, encoding: "utf8" });
768
+ // Restored before the first assert, or a failure here leaves a fixture the
769
+ // suite's own cleanup cannot remove.
770
+ chmodSync(typedir, 0o755);
771
+
772
+ const at = `mode 0o${mode.toString(8).padStart(3, "0")}`;
773
+ assert.equal(r.status, 2, at);
774
+ const json = JSON.parse(r.stdout);
775
+ assert.deepEqual(json.hits, [], `no probe found a hit, ${at}`);
776
+ assert.deepEqual(json.unknown, ["local"], `#96: exit 2 now carries a payload naming the probe, ${at}`);
777
+ assert.match(r.stderr, /refs directory .* could not be read/, at);
778
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/, at);
779
+ }
780
+
781
+ // The control, and it is not optional: without it a fixture that never had a
782
+ // findable branch would produce the same exit 2 and the case above would pass
783
+ // while pinning nothing. Readable, the branch IS found — so the refusal above
784
+ // is git being unable to look, not there being nothing to see.
785
+ const ok = spawnSync("sh", [SCRIPT, "95"], { cwd: repo, env, encoding: "utf8" });
786
+ assert.equal(ok.status, 1, "readable: the branch is found and the ticket is taken");
787
+ assert.match(ok.stderr, /local branches: fix\/95-inflight-degraded-reads/);
788
+ });
789
+
790
+ test("probe 3: an unreadable worktree registry is unknown, never a free ticket", (t) => {
791
+ if (EUID0) return t.skip(NO_DENIAL);
792
+ // Same repro shape, aimed at `.git/worktrees` (git's own admin dir) instead
793
+ // of refs/heads — matches release-ticket.sh's worktree-registry check (#84).
794
+ const { repo, env } = fixture(t, 77, { detachedWorktreeUnder: "nospace" }, );
795
+ const wtroot = join(repo, ".git", "worktrees");
796
+
797
+ for (const mode of [0o000, 0o400]) {
798
+ chmodSync(wtroot, mode);
799
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
800
+ chmodSync(wtroot, 0o755);
801
+
802
+ const at = `mode 0o${mode.toString(8).padStart(3, "0")}`;
803
+ assert.equal(r.status, 2, at);
804
+ const json = JSON.parse(r.stdout);
805
+ assert.deepEqual(json.hits, [], `no probe found a hit, ${at}`);
806
+ assert.deepEqual(json.unknown, ["local"], `#96: exit 2 now carries a payload naming the probe, ${at}`);
807
+ assert.match(r.stderr, /worktree registry .* could not be read/, at);
808
+ }
809
+ });
810
+
811
+ test("probe 3: an entry git cannot read INSIDE is unknown too, not just an unreadable entry", (t) => {
812
+ if (EUID0) return t.skip(NO_DENIAL);
813
+ // #84 itself: naming a registry entry needs read+execute on the PARENT
814
+ // only, so the entry directory stays readable while the `gitdir` file git
815
+ // opens inside it does not. `worktree list --porcelain` drops it anyway, at
816
+ // rc 0 — caught here by the count, not by a permission test on the entry.
817
+ const { repo, env } = fixture(t, 77, { detachedWorktreeUnder: "nospace" });
818
+ const entries = readdirSync(join(repo, ".git", "worktrees"));
819
+ assert.equal(entries.length, 1, "fixture: exactly one linked worktree registered");
820
+ const gitdir = join(repo, ".git", "worktrees", entries[0], "gitdir");
821
+
822
+ chmodSync(gitdir, 0o000);
823
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
824
+ // Restored before the first assert — a later `worktree list` (including the
825
+ // suite's own cleanup) would otherwise still see this claim's worktree as
826
+ // dropped.
827
+ chmodSync(gitdir, 0o644);
828
+
829
+ assert.equal(r.status, 2);
830
+ const json = JSON.parse(r.stdout);
831
+ assert.deepEqual(json.hits, []);
832
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
833
+ assert.match(r.stderr, /git listed 0 worktrees for 1 registry entries/);
834
+ });
835
+
836
+ test("probe 3: a repo that never had a linked worktree is still answerable and free", (t) => {
837
+ // The trap a naive fix falls into: refusing whenever `.git/worktrees` is
838
+ // simply missing, conflating "never existed" with "exists but unreadable".
839
+ // A vanilla repo has no such directory at all, and that absence must stay
840
+ // free, not become a permanent exit 2 (#95).
841
+ const { repo, env } = fixture(t, 8, {});
842
+ assert.equal(existsSync(join(repo, ".git", "worktrees")), false,
843
+ "fixture: no worktree has ever been linked");
844
+
845
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
846
+ assert.equal(r.status, 0);
847
+ assert.equal(JSON.parse(r.stdout).taken, false);
848
+ });
849
+
850
+ test("probe 3: something that is not a registry entry is not counted as a dropped worktree", (t) => {
851
+ // The count above globs the registry directory, so it sees whatever is in
852
+ // there — and anything that is not a directory is not a worktree
853
+ // registration, matching release-ticket.sh's own fix for the same trap.
854
+ const { repo, env } = fixture(t, 8, {});
855
+ mkdirSync(join(repo, ".git", "worktrees"), { recursive: true });
856
+ writeFileSync(join(repo, ".git", "worktrees", "stray-note"), "not a worktree\n");
857
+
858
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
859
+ assert.equal(r.status, 0);
860
+ assert.equal(JSON.parse(r.stdout).taken, false);
861
+ });
862
+
863
+ test("probe 3: a stray DIRECTORY in the registry is not a worktree git failed to report", (t) => {
864
+ // The case above covers a stray *file*, which the `-d` test skipped anyway.
865
+ // A stray *directory* is the one that bites: git ignores it, a `-d`-only
866
+ // count sees it (measured: git lists 2 worktrees where the count said 3),
867
+ // and the mismatch then turns EVERY ticket in that repo into exit 2 until a
868
+ // human notices. One `mkdir` under `.git/worktrees` is all it takes.
869
+ const { repo, env } = fixture(t, 8, {});
870
+ mkdirSync(join(repo, ".git", "worktrees", "stray-dir"), { recursive: true });
871
+
872
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
873
+ assert.equal(r.status, 0);
874
+ assert.equal(JSON.parse(r.stdout).taken, false);
875
+ });
876
+
877
+ test("probe 3: an entry git cannot fully read is unknown, not a stray to skip (#697)", (t) => {
878
+ if (EUID0) return t.skip(NO_DENIAL);
879
+ // Two EACCES shapes, both landing on the same wrong "empty" answer if the
880
+ // skip reads only `ls`'s output. 0o000 is unsearchable, so nothing inside it
881
+ // — `gitdir` included — resolves at all. 0o111 is searchable, so an `-x`
882
+ // test passes it and `gitdir` still resolves, but the entry itself is not
883
+ // readable: `ls -A` fails EACCES and — its stderr discarded — prints exactly
884
+ // what an empty stray `mkdir` prints. Skip on the OUTPUT alone and either
885
+ // shape is let through as "not git's"; git drops both too (measured: 2
886
+ // listed, then 1), the counts AGREE, no mismatch fires, and the probe
887
+ // answers `taken=false` for a ticket whose checkout is still on disk.
888
+ for (const mode of [0o000, 0o111]) {
889
+ const { repo, env } = fixture(t, 77, { detachedWorktreeUnder: "nospace" });
890
+ const entries = readdirSync(join(repo, ".git", "worktrees"));
891
+ assert.equal(entries.length, 1, "fixture: exactly one linked worktree registered");
892
+ const entry = join(repo, ".git", "worktrees", entries[0]);
893
+ const gitdir = join(entry, "gitdir");
894
+
895
+ // 0o111 keeps the entry searchable, so `gitdir` inside it still resolves —
896
+ // blind it too, or this case degenerates into the 0o000 one.
897
+ if (mode === 0o111) chmodSync(gitdir, 0o000);
898
+ chmodSync(entry, mode);
899
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
900
+ // Restored innermost first, before the first assert, or the suite's own
901
+ // cleanup inherits it.
902
+ chmodSync(entry, 0o755);
903
+ if (mode === 0o111) chmodSync(gitdir, 0o644);
904
+
905
+ const at = `mode 0o${mode.toString(8).padStart(3, "0")}`;
906
+ assert.equal(r.status, 2, `${at}: an entry we could not read is unknown, never the exit 0 that means free`);
907
+ const json = JSON.parse(r.stdout);
908
+ assert.deepEqual(json.hits, [], at);
909
+ assert.deepEqual(json.unknown, ["local"], `#96: exit 2 now carries a payload naming the probe, ${at}`);
910
+ assert.match(r.stderr, /git listed 0 worktrees for 1 registry entries/, at);
911
+ }
912
+ });
913
+
914
+ test("probe 3: a registry entry whose gitdir is GONE is unknown, not a stray to skip", (t) => {
915
+ // Why the skip tests EMPTINESS and not the absence of `gitdir`. Git drops an
916
+ // entry whose `gitdir` file was deleted, so keying the skip on that file
917
+ // lets a corrupt entry through as "not git's" and the ticket reads FREE
918
+ // while its checkout may still be on disk — the wrong "free" this probe
919
+ // exists to rule out, reintroduced one layer in. An operator's stray `mkdir`
920
+ // is empty; even a corrupt entry still holds git's own files (commondir,
921
+ // HEAD, index, logs, refs), and that is the difference the count can see.
922
+ const { repo, env } = fixture(t, 77, { detachedWorktreeUnder: "nospace" });
923
+ const entries = readdirSync(join(repo, ".git", "worktrees"));
924
+ assert.equal(entries.length, 1, "fixture: exactly one linked worktree registered");
925
+ execFileSync("rm", [join(repo, ".git", "worktrees", entries[0], "gitdir")]);
926
+
927
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
928
+ assert.equal(r.status, 2, "a dropped entry is unknown, never the exit 0 that means free");
929
+ const json = JSON.parse(r.stdout);
930
+ assert.deepEqual(json.hits, []);
931
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
932
+ assert.match(r.stderr, /git listed 0 worktrees for 1 registry entries/);
933
+ });
934
+
935
+ test("probe 3: git listing MORE than the registry reports THAT, not an incomplete listing", (t) => {
936
+ // The mismatch has two directions with opposite causes, and one message
937
+ // cannot serve both. Fewer listed than registered is git dropping an entry
938
+ // it could not read. More listed than registered is the reverse — the
939
+ // on-disk count is the stale read, which is what a sibling agent's
940
+ // `git worktree add` landing between the two produces, routine in a parallel
941
+ // fleet. Reporting that as "the listing is incomplete" sends the operator
942
+ // after a permissions fault that does not exist.
943
+ //
944
+ // Shimmed rather than raced: git derives its listing FROM the registry, so
945
+ // the only way it outruns the count is that interleaving, and a shim pins
946
+ // the resulting message deterministically instead of hoping to hit a window.
947
+ const { repo, env, bin } = fixture(t, 8, {});
948
+ // Selector and payload both track the `-z` listing (#185). A shim keyed on
949
+ // the old argument string stops matching silently and the phantom is never
950
+ // appended, which is a green for a case that measured nothing — the same
951
+ // trap `registryRaceShim`'s `fired` sentinel exists to catch.
952
+ gitShim(bin, `case "$*" in
953
+ "worktree list --porcelain -z")
954
+ '${REAL_GIT}' "$@"
955
+ printf 'worktree /tmp/phantom-worktree\\000HEAD ${"0".repeat(40)}\\000detached\\000\\000'
956
+ exit 0 ;;
957
+ esac`);
958
+
959
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
960
+ assert.equal(r.status, 2);
961
+ const json = JSON.parse(r.stdout);
962
+ assert.deepEqual(json.hits, []);
963
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
964
+ assert.match(r.stderr, /git listed 1 worktrees but only 0 registry entries were counted/);
965
+ assert.doesNotMatch(r.stderr, /the listing is incomplete/);
966
+ });
967
+
968
+ test("probe 3: an EMPTY but successful listing refuses without ever printing -1 worktrees (#699)", (t) => {
969
+ // The counter's `|| return 1` closes only the awk that could not RUN. An awk
970
+ // that ran over nothing exits 0 printing `0`, that guard cannot fire, and
971
+ // `$((0 - 1))` walks into the mismatch report as "git listed -1 worktrees" —
972
+ // the count no listing can produce, which is the very tally the guard exists
973
+ // to keep off an operator's screen.
974
+ //
975
+ // Shimmed at the listing, not at awk: it is awk SUCCEEDING that makes this
976
+ // route distinct from the `awkFailWhenProgramHas` case. Real
977
+ // `git worktree list --porcelain` always prints the main checkout, so no
978
+ // unshimmed repo reaches here.
979
+ //
980
+ // The opposite boundary — `listed=1`, `linked=0`, the main checkout alone —
981
+ // needs no case of its own: every `fixture(t, n, {})` in this file has
982
+ // exactly that shape, so a guard written `-gt 1` reds most of the suite
983
+ // (measured).
984
+ const { repo, env, bin } = fixture(t, 8, {});
985
+ gitShim(bin, `case "$*" in
986
+ "worktree list --porcelain -z") exit 0 ;;
987
+ esac`);
988
+
989
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
990
+ assert.equal(r.status, 2, "a listing that cannot be trusted is unknown, never the exit 0 that means free");
991
+ const json = JSON.parse(r.stdout);
992
+ assert.deepEqual(json.hits, []);
993
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
994
+ assert.match(r.stderr, /git listed no worktrees at all for #8/);
995
+ assert.match(r.stderr, /not even the main checkout/);
996
+ assert.doesNotMatch(r.stderr, /-1 worktrees/,
997
+ "the whole point: no branch below may report a negative tally");
998
+ assert.doesNotMatch(r.stderr, /the listing is incomplete/,
999
+ "and not the mismatch message either — nothing was compared");
1000
+ });
1001
+
1002
+ /**
1003
+ * Shims `git` so that `mutation` runs on the ONE call that reads the worktree
1004
+ * registry, then hands off to the real binary.
1005
+ *
1006
+ * Shimmed rather than slept: this is the window between inflight.sh's own
1007
+ * on-disk count and git's read of the same registry, measured at ~10ms, and a
1008
+ * test that tries to hit it with a sleep is a flake generator. Firing on the
1009
+ * call itself lands the mutation inside the window every time.
1010
+ *
1011
+ * The sentinel keeps it to one shot — the suite's own cleanup shells out to
1012
+ * git too, and a shim that mutated on every listing would never converge.
1013
+ * Returned so a case can assert it actually fired: a shim that silently stops
1014
+ * matching turns this into a test of nothing. A second sentinel,
1015
+ * `<fired>.failed`, is stamped if `mutation` itself exits nonzero — firing is
1016
+ * necessary but not sufficient evidence a real race was exercised: a mutation
1017
+ * that fails after its target path already exists (or after some other
1018
+ * partial effect) can still leave that on-disk trace behind with the
1019
+ * registry never actually touched, so a case must assert this sentinel's
1020
+ * absence alongside any on-disk witness, never the witness alone.
1021
+ */
1022
+ function registryRaceShim(bin, mutation) {
1023
+ const fired = join(bin, "race-fired");
1024
+ gitShim(bin, `case "$*" in
1025
+ "worktree list --porcelain -z")
1026
+ if [ ! -e '${fired}' ]; then
1027
+ : > '${fired}'
1028
+ ${mutation} || : > '${fired}.failed'
1029
+ fi ;;
1030
+ esac`);
1031
+ return fired;
1032
+ }
1033
+
1034
+ test("probe 3: a sibling worktree ADD between the two reads is absorbed, not an abort", (t) => {
1035
+ // The count and the listing are two reads at two instants, and a sibling
1036
+ // agent's `git worktree add` landing between them makes them disagree with
1037
+ // nothing wrong. Measured on this fleet's own shape: 1.99% of probes abort
1038
+ // spuriously at 2 mutations/s, 56.6% under saturation. Only a disagreement
1039
+ // that survives a re-read is evidence of a dropped entry, so one recount
1040
+ // absorbs this while leaving the real fault (pinned above) still refusing.
1041
+ const { repo, env, bin } = fixture(t, 8, {});
1042
+ // A basename with no digits in it: probe 3 matches worktrees on basename, and
1043
+ // a sibling that happened to carry the ticket number would answer "taken"
1044
+ // here for a reason that has nothing to do with the race.
1045
+ const sibling = join(repo, "..", "sibling-work");
1046
+ const fired = registryRaceShim(bin,
1047
+ `'${REAL_GIT}' worktree add -q --detach '${sibling}' HEAD >/dev/null 2>&1`);
1048
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1049
+
1050
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
1051
+ assert.ok(existsSync(fired), "the shim fired: the mutation really landed in the window");
1052
+ assert.equal(existsSync(`${fired}.failed`), false,
1053
+ "the shim's add actually exited zero, otherwise no real race was exercised");
1054
+ assert.equal(existsSync(sibling), true,
1055
+ "the shim's mutation actually added the sibling worktree, otherwise no real race was exercised");
1056
+ assert.equal(r.status, 0, `a concurrent add is not an unanswerable probe: ${r.stderr}`);
1057
+ assert.doesNotMatch(r.stderr, /registry entries/, "no mismatch is reported at all");
1058
+ assert.equal(JSON.parse(r.stdout).taken, false);
1059
+ });
1060
+
1061
+ test("probe 3: a sibling worktree REMOVE between the two reads is absorbed, not an abort", (t) => {
1062
+ // The other direction, and it is the one that looks like the real fault:
1063
+ // git lists FEWER than the count, which is exactly the shape of an entry git
1064
+ // dropped because it could not read it. The recount is what tells a worktree
1065
+ // that is gone from one that is merely unreadable — the former stops being
1066
+ // registered, the latter stays.
1067
+ const { repo, env, bin } = fixture(t, 8, { detachedWorktreeUnder: "nospace" });
1068
+ const wt = join(repo, "..", "nospace", "fix-8-slug");
1069
+ const fired = registryRaceShim(bin,
1070
+ `'${REAL_GIT}' worktree remove --force '${wt}' >/dev/null 2>&1`);
1071
+
1072
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
1073
+ assert.ok(existsSync(fired), "the shim fired: the mutation really landed in the window");
1074
+ assert.equal(existsSync(`${fired}.failed`), false,
1075
+ "the shim's remove actually exited zero, otherwise no real race was exercised");
1076
+ // Unlike the ADD case above, a broken remove here was never silent: the
1077
+ // pre-existing `r.status` check below already reds on it, because a
1078
+ // worktree the shim failed to remove still reports `taken: true`. This
1079
+ // assertion is a better diagnostic (names the actual cause), not new
1080
+ // coverage — don't "simplify" it away as symmetric boilerplate with ADD.
1081
+ assert.equal(existsSync(wt), false,
1082
+ "the shim's mutation actually removed the worktree it targeted, otherwise no real race was exercised");
1083
+ assert.equal(r.status, 0, `a concurrent remove is not an unanswerable probe: ${r.stderr}`);
1084
+ assert.doesNotMatch(r.stderr, /registry entries/, "no mismatch is reported at all");
1085
+ assert.equal(JSON.parse(r.stdout).taken, false);
1086
+ });
1087
+
1088
+ /**
1089
+ * Like `registryRaceShim` above, but for the RECOUNT's own window rather than
1090
+ * the original count/listing gap: `before` runs ahead of the real
1091
+ * `worktree list --porcelain -z` call, exactly as `registryRaceShim`'s
1092
+ * mutation does, and `after` runs once that call has returned but before
1093
+ * anything downstream re-scans the registry — the gap the recount itself
1094
+ * opens while only `registered`, and not `linked`, is re-taken. #1421
1095
+ *
1096
+ * One shot, gated the same way and for the same reason `registryRaceShim` is:
1097
+ * the suite's own cleanup shells out to git too, and a shim that kept firing
1098
+ * would never let the run converge. Mirrors release-ticket.test.mjs's
1099
+ * `twoMutationShim`, which covers the same window in that script's copy of
1100
+ * this recount (#1408).
1101
+ */
1102
+ function twoMutationShim(bin, before, after) {
1103
+ const fired = join(bin, "two-mutation-fired");
1104
+ gitShim(bin, `case "$*" in
1105
+ "worktree list --porcelain -z")
1106
+ if [ ! -e '${fired}' ]; then
1107
+ : > '${fired}'
1108
+ ${before}
1109
+ '${REAL_GIT}' "$@"
1110
+ rc=$?
1111
+ ${after}
1112
+ exit $rc
1113
+ fi ;;
1114
+ esac`);
1115
+ return fired;
1116
+ }
1117
+
1118
+ test("probe 3: a SECOND mutation inside the recount's own window is absorbed too, add then add (#1421)", (t) => {
1119
+ // The defect this closes: re-taking `registered` alone on the recount leaves
1120
+ // `linked` pinned to the FIRST listing. A second sibling `git worktree add`
1121
+ // landing after that listing returned but before the recount re-scanned the
1122
+ // registry inflated `registered` by itself, so the counts disagreed by one
1123
+ // MORE than they started — and `linked -lt registered` fired "the listing is
1124
+ // incomplete", a corruption report, for what is really two ordinary
1125
+ // concurrent adds. Re-taking both counts together settles them on the same
1126
+ // state and neither branch fires at all.
1127
+ //
1128
+ // Basenames with no digits in them, for the reason the single-mutation case
1129
+ // above uses one: probe 3 matches worktrees on basename, and a sibling
1130
+ // carrying the ticket number would answer "taken" for a reason that has
1131
+ // nothing to do with the race.
1132
+ const { repo, env, bin } = fixture(t, 8, {});
1133
+ const siblingA = join(repo, "..", "sibling-a");
1134
+ const siblingB = join(repo, "..", "sibling-b");
1135
+ const fired = twoMutationShim(bin,
1136
+ `'${REAL_GIT}' worktree add -q --detach '${siblingA}' HEAD >/dev/null 2>&1`,
1137
+ `'${REAL_GIT}' worktree add -q --detach '${siblingB}' HEAD >/dev/null 2>&1`);
1138
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1139
+
1140
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
1141
+ assert.ok(existsSync(fired), "the shim fired: both mutations really landed");
1142
+ assert.equal(existsSync(siblingA), true,
1143
+ "fixture: the first add really landed before git's listing");
1144
+ assert.equal(existsSync(siblingB), true,
1145
+ "fixture: the second add really landed inside the recount's window");
1146
+ assert.equal(r.status, 0, `two concurrent adds are not an unanswerable probe: ${r.stderr}`);
1147
+ assert.doesNotMatch(r.stderr, /the listing is incomplete/,
1148
+ "the wrong direction must never be reported for two benign adds");
1149
+ assert.doesNotMatch(r.stderr, /registry entries/,
1150
+ "no mismatch is reported at all — the recount absorbed both");
1151
+ assert.equal(JSON.parse(r.stdout).taken, false);
1152
+ });
1153
+
1154
+ test("probe 3: a SECOND mutation inside the recount's own window is absorbed too, remove then add (#1421)", (t) => {
1155
+ // The same window, the opposite-looking mutation first: a pre-existing
1156
+ // sibling REMOVED before git's listing runs, then TWO different siblings
1157
+ // ADDED inside the recount's own window. The removal alone is what the
1158
+ // single-mutation case above already absorbs; what this adds is that the
1159
+ // recount's re-read of the registry now SEES both adds, so a recount
1160
+ // that refreshed only `registered` came back disagreeing in the
1161
+ // fewer-listed-than-registered direction — the one shape that reads as an
1162
+ // entry git dropped because it could not read it.
1163
+ //
1164
+ // TWO adds, not one, deliberately: one add nets the registry count back to
1165
+ // the same 1 it held before the remove, so a mutant that drops
1166
+ // `count_registry` from the retake and leaves `registered` pinned to its
1167
+ // FIRST-pass value (also 1, taken before the remove) would compare against
1168
+ // that coincidentally-equal number and pass for the wrong reason — measured
1169
+ // (`{ count_linked; }` in place of `{ count_registry && count_linked; }`:
1170
+ // this case stayed green while the "add then add" case above correctly
1171
+ // went red). A second add breaks the coincidence: `registered`'s first-pass
1172
+ // value (1) can no longer match `linked`'s post-mutation count (2) unless
1173
+ // the retake actually re-takes `registered` too.
1174
+ const { repo, env, bin } = fixture(t, 8, { detachedWorktreeUnder: "nospace" });
1175
+ const wt = join(repo, "..", "nospace", "fix-8-slug");
1176
+ const siblingB = join(repo, "..", "sibling-b");
1177
+ const siblingC = join(repo, "..", "sibling-c");
1178
+ const fired = twoMutationShim(bin,
1179
+ `'${REAL_GIT}' worktree remove --force '${wt}' >/dev/null 2>&1`,
1180
+ `'${REAL_GIT}' worktree add -q --detach '${siblingB}' HEAD >/dev/null 2>&1 && ` +
1181
+ `'${REAL_GIT}' worktree add -q --detach '${siblingC}' HEAD >/dev/null 2>&1`);
1182
+
1183
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
1184
+ assert.ok(existsSync(fired), "the shim fired: both mutations really landed");
1185
+ assert.equal(existsSync(wt), false,
1186
+ "fixture: the remove really landed before git's listing");
1187
+ assert.equal(existsSync(siblingB), true,
1188
+ "fixture: the first add really landed inside the recount's window");
1189
+ assert.equal(existsSync(siblingC), true,
1190
+ "fixture: the second add really landed inside the recount's window");
1191
+ assert.equal(r.status, 0, `a concurrent remove then add is not an unanswerable probe: ${r.stderr}`);
1192
+ assert.doesNotMatch(r.stderr, /the listing is incomplete/,
1193
+ "the dropped-entry message must never be reported for a benign remove/add pair");
1194
+ assert.doesNotMatch(r.stderr, /registry entries/,
1195
+ "no mismatch is reported at all — the recount absorbed both");
1196
+ assert.equal(JSON.parse(r.stdout).taken, false);
1197
+ });
1198
+
1199
+ /**
1200
+ * Targets the retake PAIR's own window, not either window above: those two
1201
+ * calls (`{ count_registry && count_linked; }`, inflight.sh:884) are still
1202
+ * two reads, not one, and the narrow gap they open BETWEEN themselves — after
1203
+ * the retake's `count_registry` has already re-scanned the registry, before
1204
+ * its `count_linked` re-lists — is the one this recount narrows but cannot
1205
+ * close. `first` fires ahead of the FIRST `worktree list --porcelain -z`
1206
+ * call, to manufacture the mismatch that makes the recount run at all;
1207
+ * `second` fires ahead of the SECOND call — the retake's own — landing
1208
+ * exactly in that residual window. #1421
1209
+ *
1210
+ * One shot per slot, for the reason `registryRaceShim`'s is: a shim that kept
1211
+ * firing on every later listing (the suite's own cleanup shells out to git
1212
+ * too) would never let the run converge.
1213
+ */
1214
+ function retakeGapShim(bin, first, second) {
1215
+ const seen = join(bin, "retake-gap-seen");
1216
+ const fired = join(bin, "retake-gap-fired");
1217
+ gitShim(bin, `case "$*" in
1218
+ "worktree list --porcelain -z")
1219
+ if [ -e '${seen}' ]; then
1220
+ ${second}
1221
+ : > '${fired}'
1222
+ else
1223
+ : > '${seen}'
1224
+ ${first}
1225
+ fi ;;
1226
+ esac`);
1227
+ return fired;
1228
+ }
1229
+
1230
+ test("probe 3: a mutation inside the RETAKE PAIR's own window still escapes it, add then add (#1421)", (t) => {
1231
+ // What the two tests above do NOT cover: both drive their second mutation
1232
+ // through `twoMutationShim`, which is one-shot and so only ever brackets
1233
+ // the FIRST `worktree list --porcelain -z` call — the retake's own second
1234
+ // call runs untouched in both of those cases. This fixture instead lands a
1235
+ // mutation on that SECOND call, i.e. inside the gap the retake pair opens
1236
+ // between its own `count_registry` and `count_linked` (inflight.sh:884).
1237
+ // That gap is real and untested until now: `registered` is re-taken first,
1238
+ // so a sibling add landing after it but before `count_linked` re-lists is
1239
+ // missed by the registry scan that already ran and IS seen by the git
1240
+ // listing still to come, same shape as the ORIGINAL pair's escape this
1241
+ // whole recount exists to close — just narrower. Pinning it, not chasing
1242
+ // it: the recount closing every window a further recount could still miss
1243
+ // is not what #1421 claims.
1244
+ const { repo, env, bin } = fixture(t, 8, {});
1245
+ const siblingA = join(repo, "..", "sibling-a");
1246
+ const siblingB = join(repo, "..", "sibling-b");
1247
+ const fired = retakeGapShim(bin,
1248
+ `'${REAL_GIT}' worktree add -q --detach '${siblingA}' HEAD >/dev/null 2>&1`,
1249
+ `'${REAL_GIT}' worktree add -q --detach '${siblingB}' HEAD >/dev/null 2>&1`);
1250
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1251
+
1252
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
1253
+ assert.ok(existsSync(fired), "the shim fired: the second add landed inside the retake's own window");
1254
+ assert.equal(existsSync(siblingA), true, "fixture: the first add really landed before git's first listing");
1255
+ assert.equal(existsSync(siblingB), true, "fixture: the second add really landed inside the retake's own window");
1256
+ assert.equal(r.status, 2, "the retake pair cannot close a window inside itself");
1257
+ assert.match(r.stderr, /git listed 2 worktrees but only 1 registry entries were counted/,
1258
+ "MORE listed than registered: the retake's own git listing sees the second add before its own registry re-scan does");
1259
+ assert.doesNotMatch(r.stderr, /the listing is incomplete/,
1260
+ "a landed add must never surface under the dropped-entry message");
1261
+ assert.equal(JSON.parse(r.stdout).unknown[0], "local");
1262
+ });
1263
+
1264
+ // --- probe 3, the branch half's SPELLING (#915).
1265
+ //
1266
+ // `%(refname:short)` is ambiguity-aware: where a TAG shares a branch's name it
1267
+ // stops shortening and emits `heads/<name>` instead (measured here, git 2.50.1
1268
+ // Apple Git-155). Detection survives that, which is what makes this a
1269
+ // diagnostic defect rather than #634's destructive one — the filter regex
1270
+ // `(^|[/-])n([-/]|$)` matches the prefixed form just as well, so the hit is
1271
+ // still recorded and the verdict is still `taken`. What it costs is the two
1272
+ // places the value is REPORTED: an operator pasting the stderr name into a git
1273
+ // command gets `branch 'heads/…' not found`, and `evidence.localBranch` hands
1274
+ // the same unusable string to a machine consumer. Both sites are asserted
1275
+ // because they are two separate statements reading one variable — probe 3's
1276
+ // `echo` and the `add_evidence localBranch` at the foot of the script — and a
1277
+ // fix could reach one without the other.
1278
+ //
1279
+ // The suite had no ambiguous name anywhere before this, so the old spelling
1280
+ // passed it whole.
1281
+ test("probe 3: a local branch sharing a tag's name is reported under its bare name", (t) => {
1282
+ const { repo, env } = fixture(t, 915, {});
1283
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1284
+ git(repo, env, "branch", "fix/915-ambig");
1285
+ // The name collision IS the fixture. Without the tag, `%(refname:short)`
1286
+ // already yields the bare name and this case cannot tell the spellings apart.
1287
+ git(repo, env, "tag", "fix/915-ambig", "main");
1288
+
1289
+ const r = spawnSync("sh", [SCRIPT, "915"], { cwd: repo, env, encoding: "utf8" });
1290
+ const json = JSON.parse(r.stdout);
1291
+
1292
+ // Detection first: the ticket's own central claim is that the probe already
1293
+ // reaches the right verdict, so a strip that broke the match would be a
1294
+ // regression this case has to catch rather than absorb.
1295
+ assert.equal(r.status, 1, `the ticket is still taken: ${r.stderr}`);
1296
+ assert.deepEqual(json.hits, ["local"], "the branch half still records its hit");
1297
+
1298
+ assert.match(r.stderr, /local branches: fix\/915-ambig$/m,
1299
+ "the operator is named a branch git can act on, not `heads/fix/915-ambig`");
1300
+ assert.equal(json.evidence.localBranch, "fix/915-ambig",
1301
+ "and the payload carries the same bare name");
1302
+ });
1303
+
1304
+ // --- the evidence payload as JSON.
1305
+ //
1306
+ // Every probe copies a name somebody else chose straight into a JSON string
1307
+ // position, so the characters those names may legally carry decide whether the
1308
+ // payload parses. The three cases below are the three reachable vectors, one
1309
+ // per wrapped field that a name can reach: a local branch, a worktree path and
1310
+ // a remote branch. They are not one case written three times — git's ref rules
1311
+ // reject `\` but allow `"`, while a worktree path is a filename and allows
1312
+ // both, and the three arrive through different probes into different fields,
1313
+ // so dropping the escape from any one of them is caught by exactly one.
1314
+ // (`evidence.pr` is the fourth wrapped field and has no case, because it is
1315
+ // built only from a URL-derived owner/repo, a PR number and a state — none of
1316
+ // which can carry a quote.) None of them changes the verdict — the exit code
1317
+ // and `taken` are already right — next-ticket/SKILL.md reads the exit code as
1318
+ // the decision, and run-team/SKILL.md states "any hit = taken", which is the
1319
+ // same call by way of the hits rather than the code. So a red here is a
1320
+ // consumer that cannot read the evidence, not a ticket claimed twice.
1321
+ //
1322
+ // The first two are built by hand rather than through `fixture`'s options, the
1323
+ // way release-ticket.test.mjs's hostile-name payload cases build their own —
1324
+ // "a quote in the slug cannot produce a payload the caller fails to parse" and
1325
+ // the three below it: the names are the fixture.
1326
+
1327
+ // Takes the fixture's `env`, not `process.env`: that is the copy with GIT_DIR
1328
+ // and GIT_WORK_TREE deleted. Inherited, they outrank `-C`, so a suite run from
1329
+ // inside a git hook would create these deliberately hostile names in whatever
1330
+ // repo they name — and `git worktree prune` does not reclaim a stray branch.
1331
+ const git = (repo, env, ...args) => execFileSync("git", ["-C", repo, ...args],
1332
+ { encoding: "utf8", env: { ...env, ...IDENT } });
1333
+
1334
+ test("a quote in a local branch cannot produce a payload the caller fails to parse", (t) => {
1335
+ // Measured on the pre-fix script: exit 1 with stdout breaking at char 100,
1336
+ // `"localBranch":"fix-42-say"hi"`.
1337
+ const { repo, env } = fixture(t, 42, {});
1338
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1339
+ git(repo, env, "branch", 'fix-42-say"hi');
1340
+
1341
+ const r = spawnSync("sh", [SCRIPT, "42"], { cwd: repo, env, encoding: "utf8" });
1342
+ const json = JSON.parse(r.stdout);
1343
+ assert.equal(json.evidence.localBranch, 'fix-42-say"hi', "and it round-trips, rather than being stripped");
1344
+ assert.equal(r.status, 1, "the verdict is unchanged — this was only ever the evidence");
1345
+ assert.equal(json.taken, true);
1346
+ });
1347
+
1348
+ test("a quote and a backslash in a worktree path cannot produce an unparseable payload", (t) => {
1349
+ // A path is not a ref: `\` is illegal in a branch name but fine in a
1350
+ // filename, and it is the character the escape has to double rather than
1351
+ // pass through. Detached for the reason `fixture` is — a branch carrying the
1352
+ // same number would let probe 3's branch half answer for its worktree half.
1353
+ const { repo, env } = fixture(t, 77, {});
1354
+ const name = 'fix-77-sa"y\\b';
1355
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1356
+ git(repo, env, "worktree", "add", "-q", "--detach", join(repo, ".worktrees", name), "HEAD");
1357
+
1358
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1359
+ const json = JSON.parse(r.stdout);
1360
+ // The tail, not the whole path: git reports a worktree by its resolved path,
1361
+ // and on macOS the temp dir arrives back as /private/var for a /var fixture —
1362
+ // which is why the probe-3 pair above anchors on the suffix too.
1363
+ assert.ok(json.evidence.worktree.endsWith(join(".worktrees", name)),
1364
+ `both characters must survive intact, got ${json.evidence.worktree}`);
1365
+ assert.equal(r.status, 1);
1366
+ assert.deepEqual(json.hits, ["local"]);
1367
+ });
1368
+
1369
+ test("a control character in a worktree path cannot produce an unparseable payload", (t) => {
1370
+ // What pins the `tr` stage; without it the two cases above stay green and a
1371
+ // raw C0 byte reaches the payload, which JSON forbids unescaped. Mirrors
1372
+ // release-ticket.test.mjs's "a control character in the worktree name cannot
1373
+ // produce an unparseable payload".
1374
+ //
1375
+ // \001 specifically, not \n: a newline used to be lost one stage earlier,
1376
+ // splitting the porcelain record before `jstr` could ever see it (#185). The
1377
+ // `--porcelain -z` read above now maps it to \001 before awk runs, so a
1378
+ // newline case arrives as this very byte and pins nothing this case does not
1379
+ // — the probe-3 cases near the top of this file cover the split itself. \t
1380
+ // once could not reach `jstr` either, but that was the `-F'\t'` split and the
1381
+ // `read -r` loop eating it, and both are gone — measured, a worktree named
1382
+ // `fix-88-a<TAB>b` used to arrive as the bare string `b`, its path cut at the
1383
+ // tab it was joined on, and now arrives whole with the tab ESCAPED as `\t`,
1384
+ // not neutralised: \011 is one of the five C0 bytes RFC 8259 gives a short
1385
+ // form, so unlike \001 it round-trips byte-identical (the probe-3 tab case
1386
+ // pins that, `worktreeRewritten: false`). \001 is the case that held before
1387
+ // that change and after it.
1388
+ //
1389
+ // Neutralised to a space rather than escaped — the byte does not round-trip,
1390
+ // and the assertion says so rather than pretending otherwise.
1391
+ const { repo, env } = fixture(t, 99, {});
1392
+ const name = "fix-99-c\u0001x";
1393
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1394
+ git(repo, env, "worktree", "add", "-q", "--detach", join(repo, ".worktrees", name), "HEAD");
1395
+
1396
+ const r = spawnSync("sh", [SCRIPT, "99"], { cwd: repo, env, encoding: "utf8" });
1397
+ const json = JSON.parse(r.stdout);
1398
+ assert.ok(json.evidence.worktree.endsWith(join(".worktrees", "fix-99-c x")),
1399
+ `the C0 byte must be neutralised, not passed through, got ${json.evidence.worktree}`);
1400
+ assert.equal(r.status, 1);
1401
+ assert.deepEqual(json.hits, ["local"]);
1402
+ });
1403
+
1404
+ test("a BS, a tab, a FF, a CR and a DEL in a worktree path round-trip rather than being scrubbed", (t) => {
1405
+ // Same vector as the \001 case above, but the bytes #146 gives a different
1406
+ // treatment to: BS, tab, FF and CR have JSON short forms (RFC 8259 \b \t \f
1407
+ // \r) and DEL (\177) is not a C0 byte at all, so — unlike \001 — none of the
1408
+ // five may reach the space-scrub, and the field must not be marked rewritten.
1409
+ // BS and FF are the two the first version of this fix scrubbed anyway, under
1410
+ // a comment claiming they had no short form.
1411
+ const { repo, env } = fixture(t, 88, {});
1412
+ const name = "fix-88-a\tb\rc\x7fd\be\ff";
1413
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1414
+ git(repo, env, "worktree", "add", "-q", "--detach", join(repo, ".worktrees", name), "HEAD");
1415
+
1416
+ const r = spawnSync("sh", [SCRIPT, "88"], { cwd: repo, env, encoding: "utf8" });
1417
+ const json = JSON.parse(r.stdout);
1418
+ assert.ok(json.evidence.worktree.endsWith(join(".worktrees", name)),
1419
+ `BS, tab, FF, CR and DEL must all survive intact, got ${json.evidence.worktree}`);
1420
+ assert.equal(json.evidence.worktreeRewritten, false, "escaped or preserved, not replaced");
1421
+ assert.equal(r.status, 1);
1422
+ assert.deepEqual(json.hits, ["local"]);
1423
+ });
1424
+
1425
+ test("a byte with no JSON short form in a worktree path is replaced and flagged rewritten", (t) => {
1426
+ // The \001 case above already pins the neutralising itself; this pins the
1427
+ // other half of #146 — that the payload discloses it, so a consumer reading
1428
+ // `evidence.worktree` back cannot mistake the neutralised string for the real
1429
+ // name on disk.
1430
+ // \013 (VT) rides along: it is the C0 byte that looks like it has a short
1431
+ // form and does not — RFC 8259 lists no \v — so narrowing the scrub set to
1432
+ // make room for \b and \f must not take VT out with them.
1433
+ const { repo, env } = fixture(t, 66, {});
1434
+ const name = "fix-66-c\x02x\x0by";
1435
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1436
+ git(repo, env, "worktree", "add", "-q", "--detach", join(repo, ".worktrees", name), "HEAD");
1437
+
1438
+ const r = spawnSync("sh", [SCRIPT, "66"], { cwd: repo, env, encoding: "utf8" });
1439
+ const json = JSON.parse(r.stdout);
1440
+ assert.ok(json.evidence.worktree.endsWith(join(".worktrees", name.replace("\x02", " ").replace("\x0b", " "))),
1441
+ `no short form for \\002 or \\013 — both still neutralised to a space, got ${json.evidence.worktree}`);
1442
+ assert.equal(json.evidence.worktreeRewritten, true, "and the payload must disclose that it was");
1443
+ assert.equal(r.status, 1);
1444
+ assert.deepEqual(json.hits, ["local"]);
1445
+ });
1446
+
1447
+ // A failed escaper must not retract an already-correct verdict (#120). The
1448
+ // bug it replaces: `$(jstr …)`/`$(jrewritten …)` sat in one long `&&` chain
1449
+ // ending `|| die`, so ANY of the eight calls failing threw the whole payload
1450
+ // away and reported exit 2 — turning a correctly-decided "taken" or "free"
1451
+ // into "unanswerable" over a formatter, not a decision.
1452
+ test("an escaper that cannot run nulls only its own field — the verdict and exit code are unchanged", (t) => {
1453
+ // Ticket 66 has a real local branch, so jstr and jrewritten are actually
1454
+ // invoked on non-empty content for `localBranch` — breaking `tr` on the
1455
+ // character class both share is a fork failure neither can mask (`tr` is
1456
+ // jrewritten's only command and the LAST stage of jstr's own `sed | tr`, so
1457
+ // its status is the pipeline's own). A field with nothing to say never
1458
+ // reaches `tr` at all (jstr/jrewritten short-circuit on empty input), so
1459
+ // `pr`/`remote`/`worktree` — all legitimately empty here — must stay `""`,
1460
+ // not `null`, while `localBranch` alone goes `null`.
1461
+ const bad = fixture(t, 66, { trFailWhenArgsHave: "\\013\\016-\\037" });
1462
+ git(bad.repo, bad.env, "commit", "-q", "--allow-empty", "-m", "x");
1463
+ git(bad.repo, bad.env, "branch", "fix-66-thing");
1464
+ const r = spawnSync("sh", [SCRIPT, "66"], { cwd: bad.repo, env: bad.env, encoding: "utf8" });
1465
+
1466
+ // Same ticket, same branch, no shim — the answer the run above must not
1467
+ // diverge from once the formatter is subtracted out.
1468
+ const good = fixture(t, 66, {});
1469
+ git(good.repo, good.env, "commit", "-q", "--allow-empty", "-m", "x");
1470
+ git(good.repo, good.env, "branch", "fix-66-thing");
1471
+ const rGood = spawnSync("sh", [SCRIPT, "66"], { cwd: good.repo, env: good.env, encoding: "utf8" });
1472
+
1473
+ assert.equal(r.status, rGood.status, "same exit code as the run where the escaper works");
1474
+ const json = JSON.parse(r.stdout);
1475
+ const jsonGood = JSON.parse(rGood.stdout);
1476
+ assert.equal(json.taken, jsonGood.taken);
1477
+ assert.deepEqual(json.hits, jsonGood.hits);
1478
+ assert.equal(json.evidence.localBranch, null, "the one field that actually needed escaping");
1479
+ assert.equal(json.evidence.localBranchRewritten, null);
1480
+ assert.equal(json.evidence.pr, "", "never touched the broken tr — stays the empty-probe value");
1481
+ assert.equal(json.evidence.remote, "");
1482
+ assert.equal(json.evidence.worktree, "");
1483
+ assert.match(r.stderr, /could not render the localBranch evidence.*as JSON/);
1484
+ });
1485
+
1486
+ // The positive counterpart: valid, unremarkable evidence — nothing for the
1487
+ // escaper to choke on — must still be accepted once the failure clears. Pins
1488
+ // that the null-on-failure path introduced above has no false-positive
1489
+ // twin that nulls a field the escaper never had trouble with.
1490
+ test("with a working escaper, ordinary evidence renders as a plain string, never null", (t) => {
1491
+ const { repo, env } = fixture(t, 66, {});
1492
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1493
+ git(repo, env, "branch", "fix-66-thing");
1494
+
1495
+ const r = spawnSync("sh", [SCRIPT, "66"], { cwd: repo, env, encoding: "utf8" });
1496
+ const json = JSON.parse(r.stdout);
1497
+ assert.equal(r.status, 1);
1498
+ assert.equal(json.evidence.localBranch, "fix-66-thing");
1499
+ assert.equal(json.evidence.localBranchRewritten, false);
1500
+ });
1501
+
1502
+ // The asymmetric half of the case above, and the only one that addresses
1503
+ // jrewritten ALONE: `-d` is a substring of `tr -d '\001-…'` and of nothing
1504
+ // else in the script, so jstr renders `fix-66-thing` perfectly and only the
1505
+ // rewritten-check breaks. Without this, the `if ev=$(jstr …) && rw=$(jrewritten …)`
1506
+ // conjunction is pinned on one operand only — measured, a mutant that drops
1507
+ // jrewritten out of the guard passed every test in this file as it stood
1508
+ // before these cases were added.
1509
+ //
1510
+ // Run under BOTH shells on purpose, and that is the load-bearing part, not
1511
+ // belt-and-braces. jrewritten's `tr` failure becomes its exit status only
1512
+ // because of its explicit `|| return 1` (see the comment on it); strip that
1513
+ // and the answer depends on which shell runs the script. `sh` cannot see the
1514
+ // difference on either platform this suite runs on — it is Apple's `/bin/sh`
1515
+ // on macOS and `dash` on CI's ubuntu, and both abort the function via `set -e`
1516
+ // whether or not the guard is there. `bash` is the one that can: measured,
1517
+ // bash 3.2.57 (macOS `/bin/bash`) and bash 5.3 both run past the failed `tr`
1518
+ // to the always-0 last line and report `localBranchRewritten: true` — a "bytes
1519
+ // were replaced" claim about a branch name holding no control bytes, with no
1520
+ // null and no stderr line at all. So a case that only ever spawns `sh` would
1521
+ // pin nothing here.
1522
+ for (const shell of ["sh", "bash"]) {
1523
+ test(`under ${shell}, an escaper that cannot test for rewritten bytes nulls its field rather than guessing`, (t) => {
1524
+ const { repo, env } = fixture(t, 66, { trFailWhenArgsHave: "-d" });
1525
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1526
+ git(repo, env, "branch", "fix-66-thing");
1527
+
1528
+ const r = spawnSync(shell, [SCRIPT, "66"], { cwd: repo, env, encoding: "utf8" });
1529
+ const json = JSON.parse(r.stdout);
1530
+ assert.equal(r.status, 1, "the verdict the three probes established, unchanged");
1531
+ assert.equal(json.taken, true);
1532
+ assert.deepEqual(json.hits, ["local"]);
1533
+ assert.equal(json.evidence.localBranchRewritten, null,
1534
+ "never `true`: nothing examined the bytes, so nothing may claim they were replaced");
1535
+ assert.equal(json.evidence.localBranch, null,
1536
+ "nulled with its own rewritten flag — a string whose rewritten status is unknown is not the original bytes");
1537
+ // Names the escaper, not just the field: jstr rendered `fix-66-thing`
1538
+ // perfectly here, so a message pointing at it would send a debugger to the
1539
+ // half that worked.
1540
+ assert.match(r.stderr, /could not render the localBranch evidence for #66 as JSON \(jrewritten\)/);
1541
+ });
1542
+ }
1543
+
1544
+ // The mirror: jstr's own `tr` broken while jrewritten's still runs. The two
1545
+ // invocations are distinguishable in `$*` even though they share a character
1546
+ // class — jstr's passes a second argument, so its argv ends `\037` + space,
1547
+ // while jrewritten's ends at `\037` (measured, via a tr that echoes `$*`):
1548
+ // jstr -> [\001-\007\013\016-\037 ]
1549
+ // jrewritten -> [-d \001-\007\013\016-\037]
1550
+ // so `\037 ` with the trailing space is a jstr-only selector, as `-d` is a
1551
+ // jrewritten-only one. Together the two pin the `&&`'s operands independently
1552
+ // — neither mutant that drops one call out of the guard survives both.
1553
+ //
1554
+ // One shell is enough here, unlike above: jstr's `tr` is the last stage of its
1555
+ // own pipe, so its failure IS the pipeline's status on every shell. (Its `sed`
1556
+ // stage no longer needs a shell split either — #119 gave it its own capture in
1557
+ // json.sh, pinned by json.test.mjs rather than here.)
1558
+ test("under sh, an escaper that cannot escape at all nulls its field rather than emitting a half-escaped string", (t) => {
1559
+ const { repo, env } = fixture(t, 66, { trFailWhenArgsHave: "\\037 " });
1560
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1561
+ git(repo, env, "branch", "fix-66-thing");
1562
+
1563
+ const r = spawnSync("sh", [SCRIPT, "66"], { cwd: repo, env, encoding: "utf8" });
1564
+ const json = JSON.parse(r.stdout);
1565
+ assert.equal(r.status, 1, "the verdict the three probes established, unchanged");
1566
+ assert.equal(json.taken, true);
1567
+ assert.deepEqual(json.hits, ["local"]);
1568
+ assert.equal(json.evidence.localBranch, null);
1569
+ assert.equal(json.evidence.localBranchRewritten, null,
1570
+ "nulled alongside its string: a rewritten flag about bytes no escaper could render says nothing");
1571
+ assert.equal(json.evidence.pr, "", "empty fields never reach the broken tr at all");
1572
+ // The other escaper named — the mirror of the case above, and the pair is
1573
+ // what makes the name worth printing at all.
1574
+ assert.match(r.stderr, /could not render the localBranch evidence for #66 as JSON \(jstr\)/);
1575
+ });
1576
+
1577
+ test("a quote in a remote branch cannot produce an unparseable payload", (t) => {
1578
+ // The third reachable vector, and the one the two cases above cannot reach:
1579
+ // the name is a ref like the local-branch case, but it arrives through probe
1580
+ // 2 and lands in a different field. Without this, dropping `jstr` from
1581
+ // `$remote` alone leaves the whole suite green — measured. This one goes
1582
+ // through `fixture`'s own `remoteBranches`, since a bare origin is exactly
1583
+ // what it builds and probe 2 has no path a hand-built name would exercise.
1584
+ const { repo, env } = fixture(t, 55, { remoteBranches: ['fix-55-re"mote'] });
1585
+
1586
+ const r = spawnSync("sh", [SCRIPT, "55"], { cwd: repo, env, encoding: "utf8" });
1587
+ const json = JSON.parse(r.stdout);
1588
+ assert.equal(json.evidence.remote, 'fix-55-re"mote', "and it round-trips, rather than being stripped");
1589
+ assert.equal(r.status, 1, "the verdict is unchanged — this was only ever the evidence");
1590
+ assert.deepEqual(json.hits, ["remote-branch"]);
1591
+ });
1592
+
1593
+ // --- error paths. These do not reach the jq expression at all: the stub exits on
1594
+ // GH_ISSUE_ERR before piping through it. What they pin is the `if ! linked=$(...)`
1595
+ // classifier, which this change edits to stop reporting repository-level failures
1596
+ // as a missing issue.
1597
+
1598
+ test("a nonexistent issue dies 2, distinctly from a network failure", (t) => {
1599
+ const err = "GraphQL: Could not resolve to an issue or pull request with the number of 999.";
1600
+ const r = inflight(999, { issueErr: err }, t);
1601
+ assert.equal(r.code, 2);
1602
+ assert.match(r.stderr, /issue #999 does not exist in this repository/);
1603
+ // The third payload-less exit 2, and the only one that fires from INSIDE a
1604
+ // probe — probe 1's own `gh issue view` has already run when this die is
1605
+ // reached. A missing issue is the premise all three probes rest on rather
1606
+ // than one probe's failure, so it abandons the run instead of recording an
1607
+ // unknown. Pinned here because the script's header enumerates the
1608
+ // payload-less causes, and nothing else in this file notices if this one
1609
+ // starts emitting a payload (measured: converting the die to
1610
+ // `add_unknown "pr"; return 1` left the whole suite green without this line).
1611
+ assert.equal(r.json, null, "no payload — nothing was established for one to hold");
1612
+ });
1613
+
1614
+ test("an unreachable GitHub dies 2 without claiming the issue is missing", (t) => {
1615
+ const r = inflight(8, { issueErr: "dial tcp: lookup api.github.com: no such host" }, t);
1616
+ assert.equal(r.code, 2);
1617
+ assert.match(r.stderr, /PR links are unknown/);
1618
+ assert.doesNotMatch(r.stderr, /does not exist/);
1619
+ });
1620
+
1621
+ // A renamed or deleted repo, revoked access and a token that lost `repo` scope
1622
+ // all open with "Could not resolve", so matching that alone sends the reader
1623
+ // after a missing ticket that is really a missing repository.
1624
+ test("a repository-level failure is not reported as a missing issue", (t) => {
1625
+ const err = "GraphQL: Could not resolve to a Repository with the name 'feigi/claude-config'.";
1626
+ const r = inflight(8, { issueErr: err }, t);
1627
+ assert.equal(r.code, 2);
1628
+ assert.match(r.stderr, /PR links are unknown/);
1629
+ assert.doesNotMatch(r.stderr, /does not exist/);
1630
+ });
1631
+
1632
+ // --- a filter stage that could not run at all.
1633
+ //
1634
+ // The lookups are guarded; the filtering of what they returned was not. Each
1635
+ // filter was a pipeline ending in `paste -sd, - || true`, and a pipeline
1636
+ // reports only its LAST command's status — which the `|| true` then discarded
1637
+ // too. So a stage that could not run produced an empty result, and an empty
1638
+ // result is exactly what a genuinely free ticket produces. The realistic
1639
+ // trigger is not a shimmed binary but a fork failure under process-table
1640
+ // pressure, which a parallel fleet approaches by construction — the argument
1641
+ // the script already makes for the `|| die` on its PR-counting call.
1642
+ //
1643
+ // Each case names its filter by a substring the filter's own awk program must
1644
+ // contain to do its job — the prefix the remote filter strips, the whole-line
1645
+ // match a short refname needs, the raw-path read the worktree filter takes. A
1646
+ // key that stops matching stops breaking anything, and the case reddens on the
1647
+ // exit code; it cannot pass green over an untouched filter. Nothing else can
1648
+ // emit the message each case asserts, so exit 2 plus that message is what
1649
+ // proves the intended filter is the one that failed.
1650
+ //
1651
+ // Each case keeps a real hit present, so "exit 2" is a fact about the filter
1652
+ // and not about there being nothing to find. The pre-fix numbers below were
1653
+ // measured per filter by breaking the stage that filter actually had, since no
1654
+ // filter then had an awk a substring could address on its own: the branch
1655
+ // filter had none, the worktree filter had two in one pipeline, and the remote
1656
+ // filter's lone `{print $2}` is also the worktree filter's second awk. So `sed`
1657
+ // for the remote filter, `grep` for the branch filter, `basename` for the
1658
+ // worktree one. Each was checked against the same fixture with that stage
1659
+ // intact, which answers taken, exit 1.
1660
+
1661
+ test("probe 2: a remote-branch filter that could not run is unknown, never free", (t) => {
1662
+ // Measured pre-fix with its `sed` broken: "no remote branch for #42",
1663
+ // taken=false, exit 0 — the wrong "free", with the branch on the remote.
1664
+ const r = inflight(42, {
1665
+ remoteBranches: ["main", "fix/42-thing"], awkFailWhenProgramHas: "refs/heads/",
1666
+ }, t);
1667
+ assert.equal(r.code, 2, "unanswerable is exit 2, not the exit 0 that means free");
1668
+ assert.match(r.stderr, /could not filter the remote branches for #42/);
1669
+ assert.doesNotMatch(r.stderr, /no remote branch/, "a stage that could not run never reports 'no'");
1670
+ assert.deepEqual(r.json.hits, []);
1671
+ assert.deepEqual(r.json.unknown, ["remote"], "#96: exit 2 now carries a payload naming the probe");
1672
+ });
1673
+
1674
+ test("probe 3: a local-branch filter that could not run is unknown, never free", (t) => {
1675
+ // Built by hand rather than through a `fixture` option: probe 3 reads the
1676
+ // repo it is run in, so the branch in that repo is the fixture.
1677
+ const { repo, env } = fixture(t, 42, { awkFailWhenProgramHas: "$0 ~" });
1678
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1679
+ git(repo, env, "branch", "fix/42-thing");
1680
+
1681
+ // Measured pre-fix with its `grep` broken: "no local branch or worktree",
1682
+ // taken=false, exit 0 — the wrong "free", with the branch checked out.
1683
+ const r = spawnSync("sh", [SCRIPT, "42"], { cwd: repo, env, encoding: "utf8" });
1684
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1685
+ assert.match(r.stderr, /could not filter the local branches for #42/);
1686
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/,
1687
+ "a stage that could not run never reports 'no'");
1688
+ const json = JSON.parse(r.stdout);
1689
+ assert.deepEqual(json.hits, []);
1690
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1691
+ });
1692
+
1693
+ // The LOOKUP that feeds the filter above, and the branch of probe 3 that #415
1694
+ // measured as untested: deleting its guard outright — the whole `if ! refs=$(…)`
1695
+ // conjunction, which is what an edit that simply forgets one looks like — left
1696
+ // this entire file green. That is the hazard `probe_local || :` opens. POSIX
1697
+ // exempts a function's whole execution from `set -e` while its status is what an
1698
+ // `||` is testing, so a failed `$(…)` neither aborts nor leaves `$refs` unset:
1699
+ // it assigns the empty string, which is indistinguishable from "this repo has no
1700
+ // branches", and the fall-through prints that as a definite absence. Measured
1701
+ // with the guard deleted: exit 0, `unknown:[]`, "no local branch or worktree for
1702
+ // #77" — for a ticket whose branch is sitting in `git branch --list`. The wrong
1703
+ // direction, since a free verdict puts a second agent on the ticket where a
1704
+ // taken one only skips it.
1705
+ //
1706
+ // This pins the guarded answer, so the mutant reddens here rather than shipping.
1707
+ // It does NOT forbid a probe stopping early on a hit it has already recorded:
1708
+ // nothing is established at this point in probe 3 — the branch half commits its
1709
+ // hit after this lookup, not before — so `hits: []` is the answer, not a rule
1710
+ // that a stopped probe must have none.
1711
+ test("probe 3: a branch LOOKUP that could not run is unknown, never free", (t) => {
1712
+ const { repo, env, bin } = fixture(t, 77, {});
1713
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1714
+ git(repo, env, "branch", "fix/77-slug");
1715
+
1716
+ // Addressed by the subcommand, never by an invocation count: this suite's own
1717
+ // helpers and cleanup shell out to git through this same PATH, so a counted
1718
+ // shim would fire on whichever call happened to be nth. `for-each-ref` is the
1719
+ // one stage of inflight.sh that runs it, so the subcommand names it alone.
1720
+ gitShim(bin, `case "$1" in for-each-ref) exit 1 ;; esac`);
1721
+
1722
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1723
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1724
+ assert.match(r.stderr, /git for-each-ref failed, so whether #77 has a local branch is unknown/);
1725
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/,
1726
+ "a lookup that could not run never reports 'no'");
1727
+ const json = JSON.parse(r.stdout);
1728
+ assert.deepEqual(json.hits, []);
1729
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1730
+ });
1731
+
1732
+ test("probe 3: a worktree filter that could not run is unknown, never free", (t) => {
1733
+ // Detached for the reason `fixture` is: a branch carrying the same number
1734
+ // would let probe 3's branch half answer for its worktree half, and this
1735
+ // case is about the worktree half alone.
1736
+ const { repo, env } = fixture(t, 77, { awkFailWhenProgramHas: "substr($0,10)" });
1737
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1738
+ git(repo, env, "worktree", "add", "-q", "--detach", join(repo, ".worktrees", "fix-77-slug"), "HEAD");
1739
+
1740
+ // Measured pre-fix with its per-line `basename` broken — the same defect one
1741
+ // level down, and the one that needs no shimmed binary to reach: "no local
1742
+ // branch or worktree for #77", taken=false, exit 0, worktree checked out.
1743
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1744
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1745
+ assert.match(r.stderr, /could not filter the worktree list for #77/);
1746
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/,
1747
+ "a stage that could not run never reports 'no'");
1748
+ const json = JSON.parse(r.stdout);
1749
+ assert.deepEqual(json.hits, []);
1750
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1751
+ });
1752
+
1753
+ test("probe 3: a worktree COUNT that could not run is unknown, never a bogus tally", (t) => {
1754
+ // The registry cross-check counts git's own listing, and that counter is a
1755
+ // stage like any other. It used to be `grep -c '^worktree ' || true`, and
1756
+ // that `|| true` was not optional: `grep -c` exits 1 on zero matches, which
1757
+ // is legitimate. But it absorbed a grep that could not RUN just as happily,
1758
+ // leaving the count empty, `$((listed - 1))` at -1, and the die blaming
1759
+ // `git worktree list` for a tally no listing can produce. One awk, whose
1760
+ // program contains no `exit`, needs no such case absorbed — so the status is
1761
+ // the counter's own and reads as the failure it is.
1762
+ const { repo, env } = fixture(t, 77, { awkFailWhenProgramHas: "{c++}",
1763
+ detachedWorktreeUnder: "nospace" });
1764
+
1765
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1766
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1767
+ assert.match(r.stderr, /could not count the worktrees git listed for #77/);
1768
+ assert.doesNotMatch(r.stderr, /-1 worktrees/,
1769
+ "a counter that could not run never reports a count at all");
1770
+ const json = JSON.parse(r.stdout);
1771
+ assert.deepEqual(json.hits, []);
1772
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1773
+ });
1774
+
1775
+ // --- probe 3's three remaining value-producing commands (#1019).
1776
+ //
1777
+ // The cases above pin a filter, a lookup and a counter. Three commands in this
1778
+ // probe still had no guard-removal-sensitive pin: the git-common-dir
1779
+ // resolution every path in the probe is built from, the `find` walk over the
1780
+ // refs subdirectories, and the porcelain worktree listing. Each guard was
1781
+ // deleted outright — what an edit that simply forgets one looks like — and this
1782
+ // file stayed green at 94/94, all three (measured).
1783
+ //
1784
+ // #415's hazard, unchanged: the probe runs as `probe_local || :`, which exempts
1785
+ // its whole body from `set -e`, so an unguarded failure here is silent rather
1786
+ // than loud. A failed `$(…)` assigns the empty string, and empty is exactly
1787
+ // what a genuinely free ticket produces. Two of the three then answer FREE
1788
+ // outright (measured below) — the wrong direction, since a free verdict puts a
1789
+ // second agent on the ticket where a taken one only skips it.
1790
+ //
1791
+ // Three cases, not one, and the reason is mechanical rather than stylistic:
1792
+ // each of these commands ends the probe with `return 1` when it fails, so the
1793
+ // earliest one broken is the only one that ever runs. A single case could
1794
+ // exercise the first and would carry two assertions that can never fail —
1795
+ // a pin on the file's own count of pins, not on the script. They also break
1796
+ // three different binaries (`git rev-parse`, `head`, `git worktree`) and assert
1797
+ // three different messages, so there is nothing for one case to share.
1798
+ //
1799
+ // Every selector names its command by the SUBCOMMAND in its first argument,
1800
+ // never by an invocation count: this suite's fixtures and cleanup shell out
1801
+ // through the same PATH, so a counted shim fires on whichever call happens to
1802
+ // be nth. Each shim is written AFTER its fixture is built, so no setup call is
1803
+ // in its way, and `fixture`'s teardown shells out to `chmod` and `rm`, not to
1804
+ // git. None of the three can pass green over a selector that went stale
1805
+ // either — unshimmed, each fixture is a plain free ticket at exit 0, so a key
1806
+ // that stops matching reddens on the exit code rather than going quiet.
1807
+
1808
+ test("probe 3: a git common directory that could not be resolved is unknown, never free", (t) => {
1809
+ const { repo, env, bin } = fixture(t, 77, {});
1810
+
1811
+ // The subcommand selects and the flag disambiguates, because `rev-parse`
1812
+ // alone names two calls in this script and the other one is the precondition
1813
+ // check at the top (`rev-parse --git-dir`). Breaking that dies "not inside a
1814
+ // git repository" before probe 3 is reached at all — a green for a case that
1815
+ // measured nothing.
1816
+ gitShim(bin, `case "$1" in rev-parse) case "$*" in *--git-common-dir*) exit 1 ;; esac ;; esac`);
1817
+
1818
+ // Measured with the guard deleted: exit 0, `taken:false`, `unknown:[]`, "no
1819
+ // local branch or worktree for #77". `$common` is empty, so `$common/refs/heads`
1820
+ // is `/refs/heads` and `$common/worktrees` is `/worktrees`; neither exists,
1821
+ // both the refs walk and the registry count skip as legitimately absent, and
1822
+ // the probe reports a definite "no" about storage it never located.
1823
+ //
1824
+ // A free ticket rather than one with a hit, unlike the filter cases above.
1825
+ // Those keep a hit present so that exit 2 is a fact about the filter and not
1826
+ // about there being nothing to find; here the same worry is answered by the
1827
+ // verdict itself, since a free ticket exits 0 and only a decline can reach 2.
1828
+ // A hit would also hide the finding: the branch half answers before any of
1829
+ // this matters, so the mutant would report taken and never show the wrong
1830
+ // "free" that is the whole hazard.
1831
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1832
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1833
+ assert.match(r.stderr, /cannot resolve the git common directory/);
1834
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/,
1835
+ "a probe that never located its own storage never reports 'no'");
1836
+ const json = JSON.parse(r.stdout);
1837
+ assert.deepEqual(json.hits, []);
1838
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1839
+ });
1840
+
1841
+ test("probe 3: a refs-subdirectory walk whose `head` cannot run is unknown, never free", (t) => {
1842
+ const { repo, env, bin } = fixture(t, 77, {});
1843
+
1844
+ // `head`, not `find`. The script runs `set -eu` with no `pipefail`, so
1845
+ // before #1448 `bad=$(find … | head -1)` carried HEAD's status alone;
1846
+ // find's was read off a separate, unpiped command substitution once #1448
1847
+ // fixed that (the next test pins the gap that left open — a `find` that
1848
+ // cannot run at all). This case is the other half: `head` itself failing,
1849
+ // which the fix keeps observing on its own via `head_rc` rather than
1850
+ // dropping now that find's status no longer has to stand in for it.
1851
+ //
1852
+ // Selected by the first argument for the reason the git shims are, and
1853
+ // `head -1` is the only `head` the script runs.
1854
+ writeFileSync(join(bin, "head"), `#!/bin/sh\ncase "$1" in -1) exit 1 ;; esac\nexec '${REAL_HEAD}' "$@"\n`);
1855
+ chmodSync(join(bin, "head"), 0o755);
1856
+
1857
+ // Measured with the guard deleted: exit 0, `taken:false`, `unknown:[]`, "no
1858
+ // local branch or worktree for #77". `$bad` takes the empty string the walk
1859
+ // never produced, the `[ -z "$bad" ]` test below reads that as "no unreadable
1860
+ // subdirectory was found", and the probe reports a definite absence about
1861
+ // refs it never established were readable.
1862
+ //
1863
+ // That `[ -z … ]` test is pinned by the two chmod cases above and cannot
1864
+ // cover this one: there the walk RAN and returned a finding, here it did not
1865
+ // run at all, and the two arrive at the same empty `$bad` from opposite
1866
+ // directions.
1867
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1868
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1869
+ assert.match(r.stderr,
1870
+ /could not test the refs directories under \S+\/refs\/heads, so whether #77 has a local branch is unknown/);
1871
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/,
1872
+ "a walk that could not run never reports 'no'");
1873
+ const json = JSON.parse(r.stdout);
1874
+ assert.deepEqual(json.hits, []);
1875
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1876
+ });
1877
+
1878
+ test("probe 3: a refs-subdirectory find that cannot run at all is unknown, never free", (t) => {
1879
+ const { repo, env, bin } = fixture(t, 77, {});
1880
+
1881
+ // `find` itself, not `head` — the previous case's shim. `exit 127` is the
1882
+ // shell's own code for "command not found", the shape a missing binary or a
1883
+ // PATH shadow actually takes, and the reproduction this ticket names (#1448).
1884
+ // Before the fix, `bad=$(find … | head -1)` carried only `head`'s status —
1885
+ // this script sets no `pipefail` — and `head` exits 0 reading an empty pipe
1886
+ // whether `find` printed a permission-denied hit or never ran at all, so a
1887
+ // crashed `find` and a clean tree left the same empty `$bad` and were
1888
+ // indistinguishable at the guard below.
1889
+ writeFileSync(join(bin, "find"), "#!/bin/sh\nexit 127\n");
1890
+ chmodSync(join(bin, "find"), 0o755);
1891
+
1892
+ // Measured before the fix: exit 0, `taken:false`, `unknown:[]`, "no local
1893
+ // branch or worktree for #77" — a `find` that never ran reported a definite
1894
+ // absence about refs it never actually walked.
1895
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1896
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1897
+ assert.match(r.stderr,
1898
+ /could not test the refs directories under \S+\/refs\/heads, so whether #77 has a local branch is unknown/);
1899
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/,
1900
+ "a walk that could not run never reports 'no'");
1901
+ const json = JSON.parse(r.stdout);
1902
+ assert.deepEqual(json.hits, []);
1903
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1904
+ });
1905
+
1906
+ test("probe 3: a worktree listing that could not run names its own cause, not a bogus count", (t) => {
1907
+ const { repo, env, bin } = fixture(t, 77, {});
1908
+
1909
+ // `worktree` names the script's only `git worktree` call, so the subcommand
1910
+ // alone is the key here — no flag needed, unlike the rev-parse case above.
1911
+ gitShim(bin, `case "$1" in worktree) exit 1 ;; esac`);
1912
+
1913
+ // The one of the three whose mutant does NOT reach a wrong verdict, and the
1914
+ // assertion is shaped to that. Measured with the guard deleted: still exit 2,
1915
+ // still `unknown:["local"]` — but "git listed no worktrees at all for #77 —
1916
+ // not even the main checkout, so the listing cannot be trusted". That is
1917
+ // #699's `[ "$listed" -ge 1 ]` backstop, counting a listing git never wrote,
1918
+ // and it sends a reader after a repository whose worktrees have vanished when
1919
+ // the fault is a git that could not run or a temp file that could not be
1920
+ // written. So the exit code cannot pin this guard and the message is the
1921
+ // whole of it — hence the explicit refusal of the backstop's wording below,
1922
+ // rather than leaning on a status both paths share.
1923
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
1924
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
1925
+ assert.match(r.stderr,
1926
+ /git worktree list failed, or its output could not be written to \S+, so whether #77 has a worktree is unknown/);
1927
+ assert.doesNotMatch(r.stderr, /listed no worktrees at all/,
1928
+ "the lookup that failed names itself; the downstream count never speaks for it");
1929
+ const json = JSON.parse(r.stdout);
1930
+ assert.deepEqual(json.hits, []);
1931
+ assert.deepEqual(json.unknown, ["local"], "#96: exit 2 now carries a payload naming the probe");
1932
+ });
1933
+
1934
+ // --- the substring guard, across all three filters at once.
1935
+ //
1936
+ // Green before the rewrite as well as after: it exists to stay green through
1937
+ // it. The matching is a path-segment regex, not a substring search, and a
1938
+ // rewrite that reaches for `index`, a bare `~ n`, or a dropped anchor turns
1939
+ // every ticket whose digits appear inside a longer number into a false hit —
1940
+ // which reads as taken and silently drops real work on the floor.
1941
+ //
1942
+ // Both anchors, because they guard opposite collisions and one fixture cannot
1943
+ // catch the other's loss: 341 is a SUFFIX collision, held off by the leading
1944
+ // `(^|[/-])`, and 410 is a PREFIX collision, held off by the trailing
1945
+ // `([-/]|$)`. Measured — with only 341 here, dropping the trailing anchor left
1946
+ // the whole suite green while 41 read as taken off 410 on all three probes.
1947
+ // Neither number is hypothetical in this repo: 17 vs 174, 13 vs 132, 4 vs 48.
1948
+ test("41 is not claimed by a remote branch, a local branch or a worktree named for 341 or 410", (t) => {
1949
+ const { repo, env } = fixture(t, 41, {
1950
+ remoteBranches: ["main", "fix/341-thing", "fix/410-thing"],
1951
+ });
1952
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
1953
+ for (const other of ["341", "410"]) {
1954
+ git(repo, env, "branch", `fix/${other}-thing`);
1955
+ git(repo, env, "worktree", "add", "-q", "--detach",
1956
+ join(repo, ".worktrees", `fix-${other}-slug`), "HEAD");
1957
+ }
1958
+
1959
+ const r = spawnSync("sh", [SCRIPT, "41"], { cwd: repo, env, encoding: "utf8" });
1960
+ const json = JSON.parse(r.stdout);
1961
+ assert.equal(r.status, 0);
1962
+ assert.equal(json.taken, false);
1963
+ assert.equal(json.evidence.remote, "", "341 or 410 on the remote is not 41");
1964
+ assert.equal(json.evidence.localBranch, "", "341 or 410 on a local branch is not 41");
1965
+ assert.equal(json.evidence.worktree, "", "341 or 410 in a worktree name is not 41");
1966
+ });
1967
+
1968
+ // --- a ref byte that is not valid UTF-8.
1969
+ //
1970
+ // Refs and paths are byte strings; nothing guarantees they decode as UTF-8. A
1971
+ // BWK awk in a UTF-8 locale aborts on a record it cannot convert to wide
1972
+ // characters — even a record it is only scanning past — so one such ref
1973
+ // anywhere on the remote takes EVERY ticket to exit 2, permanently, until
1974
+ // somebody deletes it. The collapse to a lone awk is what introduced that:
1975
+ // `grep` matched bytes and was unbothered. `LC_ALL=C` restores byte matching,
1976
+ // which is what a ref and a path are, and the regex is pure ASCII so nothing
1977
+ // is lost. Without it this case reports "could not filter the remote branches"
1978
+ // for a ticket that is plainly free.
1979
+ //
1980
+ // Written straight into `packed-refs`, a plain text file: no such filename is
1981
+ // ever created, so the filesystem never has to accept one, and the bytes still
1982
+ // reach probe 2 through `git ls-remote`.
1983
+ //
1984
+ // #614: this pins probe 2's own INLINE `LC_ALL=C awk` (inflight.sh, the filter
1985
+ // over `git ls-remote`'s output), not the script's file-global `export
1986
+ // LC_ALL=C`. The two are not the same pin, and this test cannot be widened
1987
+ // into a regression gate for the global one: the inline prefix sets `LC_ALL`
1988
+ // on that one command's environment unconditionally, so no ambient shell
1989
+ // state — an `AMBIENT_UTF8`-style env, or even the global export deleted
1990
+ // outright — ever reaches it. Measured directly: deleting inflight.sh's
1991
+ // `export LC_ALL=C` and rerunning this exact case with the global pin's
1992
+ // ambient-vs-explicit env shape both leave `taken:false` at exit 0 —
1993
+ // unmoved, because probe 2 never depended on either. inflight.sh's own header
1994
+ // comment records this for every awk call in the file, and #614's own count
1995
+ // of scripts still lacking a fixture for the global pin counts inflight.sh
1996
+ // among them, not among the covered ones.
1997
+ test("a ref that is not valid UTF-8 leaves an answerable ticket answerable", (t) => {
1998
+ const { repo, env } = fixture(t, 41, { remoteBranches: ["main"] });
1999
+ const bare = join(repo, "..", "remote.git");
2000
+ const main = execFileSync("git", ["-C", bare, "rev-parse", "refs/heads/main"],
2001
+ { encoding: "utf8" }).trim();
2002
+ appendFileSync(join(bare, "packed-refs"), Buffer.concat([
2003
+ Buffer.from(`${main} refs/heads/feat/caf`), Buffer.from([0xff]), Buffer.from("-nine\n")]));
2004
+
2005
+ const r = spawnSync("sh", [SCRIPT, "41"],
2006
+ { cwd: repo, env: { ...env, LC_ALL: "en_US.UTF-8" }, encoding: "utf8" });
2007
+ assert.equal(r.status, 0, `a free ticket stays free, got: ${r.stderr}`);
2008
+ assert.equal(JSON.parse(r.stdout).taken, false);
2009
+ });
2010
+
2011
+ // --- #92: probe 2 must never prompt and must not block indefinitely.
2012
+ //
2013
+ // Prompt suppression alone does not bound a hang: measured in the issue, a
2014
+ // stalled ssh transport blocks identically with and without
2015
+ // GIT_TERMINAL_PROMPT=0 (killed at 8s, rc 142 either way). So the case that
2016
+ // actually exercises the fix is a listener that accepts the TCP connection
2017
+ // and then says nothing back — the ssh banner exchange never completes.
2018
+ //
2019
+ // A real listener, not a shimmed binary: the fix bounds the CONNECTION, and
2020
+ // only a genuine stall proves that. It carries its own spawnSync timeout as a
2021
+ // backstop so a regression here reddens loudly instead of hanging the suite.
2022
+ test("probe 2: a transport that connects and then never answers still terminates, exit 2", async (t) => {
2023
+ const port = await silentListener(t);
2024
+
2025
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2026
+ git(repo, env, "remote", "add", "origin", `ssh://git@127.0.0.1:${port}/x/y.git`);
2027
+
2028
+ const started = Date.now();
2029
+ // 45s: comfortably above the ~10s ConnectTimeout the fix sets (measured
2030
+ // locally: "Connection timed out during banner exchange" at ~10.0s against
2031
+ // this exact fixture), but far short of leaving the suite to hang on a
2032
+ // regression that drops the bound entirely.
2033
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8", timeout: 45_000 });
2034
+
2035
+ assert.notEqual(r.signal, "SIGTERM",
2036
+ `spawnSync's own 45s backstop fired — the script's bound is gone: ${JSON.stringify(r)}`);
2037
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
2038
+ assert.match(r.stderr, /whether #8 has a remote branch is unknown/);
2039
+ assert.ok(Date.now() - started < 45_000, "must terminate on its own bound, not the test's backstop");
2040
+ });
2041
+
2042
+ // The stub the next three tests share: it logs its own argv and exits, so the
2043
+ // cases are deterministic and touch no network at all — what git actually
2044
+ // invokes is the assertion.
2045
+ // Named `ssh` and dropped into the fixture's `bin` when the tier under test is
2046
+ // one where the script picks the program itself — `bin` is first on PATH.
2047
+ const sshStub = (dir, name = "user-ssh-stub.sh") => {
2048
+ const log = join(dir, `${name}.log`);
2049
+ const stub = join(dir, name);
2050
+ writeFileSync(stub, `#!/bin/sh\nprintf '%s\\n' "$*" >> '${log}'\nexit 1\n`);
2051
+ chmodSync(stub, 0o755);
2052
+ return { stub, log };
2053
+ };
2054
+
2055
+ // Whole words, never a substring. `"ServerAliveCountMax=25".includes("ServerAliveCountMax=2")`
2056
+ // is true, so the `.includes` form this replaced passed a bound weakened 12.5x
2057
+ // — measured, with the whole file still green, the live-hang test included
2058
+ // (that one terminates on ConnectTimeout, so it never sees the ServerAlive
2059
+ // pair either). Splitting on whitespace is exactly right for the stub's
2060
+ // `printf '%s\n' "$*"`, which is argv joined by single spaces.
2061
+ // `userOpt` names the option standing in for the user's own command, and is
2062
+ // asserted by POSITION, not membership. That the bound options come LAST is the
2063
+ // whole mechanism probe 2's comment rests on — ssh takes the first value of a
2064
+ // repeated -o, so they are defaults only while the user's own options precede
2065
+ // them. Membership cannot see it: measured, moving the appended block ahead of
2066
+ // the user's command left every test here green, turning the comment into a lie
2067
+ // with the suite still fully passing.
2068
+ const assertBoundOptions = (log, userOpt) => {
2069
+ const words = readFileSync(log, "utf8").split(/\s+/);
2070
+ for (const opt of ["BatchMode=yes", "ConnectTimeout=10", "ServerAliveInterval=5", "ServerAliveCountMax=2"]) {
2071
+ assert.ok(words.includes(opt),
2072
+ `bound option missing from the invoked command: ${opt} — invoked as: ${words.join(" ")}`);
2073
+ }
2074
+ if (userOpt) {
2075
+ const user = words.indexOf(userOpt);
2076
+ assert.ok(user >= 0,
2077
+ `the user's own configured command must survive, not be replaced — invoked as: ${words.join(" ")}`);
2078
+ assert.ok(user < words.indexOf("ConnectTimeout=10"),
2079
+ `the bound options must be appended after the user's own command, or they override it instead of defaulting under it — invoked as: ${words.join(" ")}`);
2080
+ }
2081
+ return words;
2082
+ };
2083
+
2084
+ // The other half: a user's own configured ssh command is honoured, not
2085
+ // replaced. Three tests, one per tier of the fallback, because git's own
2086
+ // precedence is GIT_SSH_COMMAND > core.sshCommand > GIT_SSH and each tier is
2087
+ // reached only when the ones above it are unset — so one test can only ever
2088
+ // exercise one of them.
2089
+ //
2090
+ // `GIT_SSH_COMMAND` here stands in for a command a user already set (a custom
2091
+ // identity file, a proxy).
2092
+ test("probe 2: an existing GIT_SSH_COMMAND is honoured, with the bound options added on top", (t) => {
2093
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2094
+ git(repo, env, "remote", "add", "origin", "ssh://git@example.invalid/x/y.git");
2095
+
2096
+ const { stub, log } = sshStub(repo);
2097
+
2098
+ // A marker option stands in for whatever the user's own command carries —
2099
+ // its presence in the log proves the script appended rather than replaced.
2100
+ const r = spawnSync("sh", [SCRIPT, "8"],
2101
+ { cwd: repo, env: { ...env, GIT_SSH_COMMAND: `${stub} -o UserMarker=1` }, encoding: "utf8" });
2102
+ assert.equal(r.status, 2, "the stub always fails, so this is 'could not look', never free");
2103
+
2104
+ assertBoundOptions(log, "UserMarker=1");
2105
+ });
2106
+
2107
+ // The middle tier of the same fallback. Unlike GIT_SSH_COMMAND it is a git
2108
+ // config read, so a wrong key or a wrong scope would break it without breaking
2109
+ // the test above — and would ship silently, since setting GIT_SSH_COMMAND in
2110
+ // that test short-circuits `${GIT_SSH_COMMAND:-…}` before this tier is ever
2111
+ // consulted. Measured: deleting the `git config --get core.sshCommand` line
2112
+ // outright left the whole file green before this test existed.
2113
+ test("probe 2: a core.sshCommand is honoured, with the bound options added on top", (t) => {
2114
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2115
+ git(repo, env, "remote", "add", "origin", "ssh://git@example.invalid/x/y.git");
2116
+
2117
+ const { stub, log } = sshStub(repo);
2118
+ git(repo, env, "config", "core.sshCommand", `${stub} -o UserMarker=1`);
2119
+
2120
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
2121
+ assert.equal(r.status, 2, "the stub always fails, so this is 'could not look', never free");
2122
+
2123
+ assertBoundOptions(log, "UserMarker=1");
2124
+ });
2125
+
2126
+ // The last tier, and the one this probe regressed: git's precedence is
2127
+ // GIT_SSH_COMMAND > core.sshCommand > GIT_SSH, so setting GIT_SSH_COMMAND
2128
+ // unconditionally dropped a user's GIT_SSH wrapper — measured against the
2129
+ // pre-fix shape, the stub was invoked twice; with GIT_SSH_COMMAND set, never.
2130
+ // GIT_SSH names a program rather than a command line, so it carries no marker
2131
+ // option of its own: being invoked at all is the assertion.
2132
+ test("probe 2: a legacy GIT_SSH wrapper is honoured, with the bound options added on top", (t) => {
2133
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2134
+ git(repo, env, "remote", "add", "origin", "ssh://git@example.invalid/x/y.git");
2135
+
2136
+ const { stub, log } = sshStub(repo);
2137
+
2138
+ const r = spawnSync("sh", [SCRIPT, "8"],
2139
+ { cwd: repo, env: { ...env, GIT_SSH: stub }, encoding: "utf8" });
2140
+ assert.equal(r.status, 2, "the stub always fails, so this is 'could not look', never free");
2141
+
2142
+ assertBoundOptions(log);
2143
+ });
2144
+
2145
+ // The marker option the tier tests use has no counterpart in the appended tail,
2146
+ // so ordering is all they can observe. Here the user sets a key this probe also
2147
+ // sets, which is the case probe 2's comment is actually about: ssh takes the
2148
+ // FIRST value of a repeated -o, so the occurrence that applies must be the
2149
+ // user's value and not this probe's. Asserted on the invoked command rather
2150
+ // than on ssh's own resolution, which the stub never reaches — what the stub
2151
+ // records is the argv git builds, and that ordering is the only part of the
2152
+ // rule this script controls.
2153
+ test("probe 2: a user's own colliding -o comes first, so ssh resolves theirs", (t) => {
2154
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2155
+ git(repo, env, "remote", "add", "origin", "ssh://git@example.invalid/x/y.git");
2156
+
2157
+ const { stub, log } = sshStub(repo);
2158
+
2159
+ const r = spawnSync("sh", [SCRIPT, "8"],
2160
+ { cwd: repo, env: { ...env, GIT_SSH_COMMAND: `${stub} -o ConnectTimeout=45` }, encoding: "utf8" });
2161
+ assert.equal(r.status, 2, "the stub always fails, so this is 'could not look', never free");
2162
+
2163
+ const words = readFileSync(log, "utf8").split(/\s+/);
2164
+ assert.equal(words.find((w) => w.startsWith("ConnectTimeout=")), "ConnectTimeout=45",
2165
+ `the user's own ConnectTimeout must be the first one ssh sees, or this probe silently overrides a timeout they set on purpose — invoked as: ${words.join(" ")}`);
2166
+ });
2167
+
2168
+ // The two tiers where the script names the program itself rather than
2169
+ // inheriting one. Every test above supplies its own ssh command, so none of
2170
+ // them can see a regression that leaves the program EMPTY — git would then get
2171
+ // a command line starting with `-o` and die with "-o: command not found", and
2172
+ // the suite would stay green because "could not look" is exit 2 either way.
2173
+ //
2174
+ // Nothing configured at all: the last tier of the fallback.
2175
+ test("probe 2: with no ssh command configured, plain ssh carries the bound options", (t) => {
2176
+ const { repo, env, bin } = fixture(t, 8, { origin: "none" });
2177
+ git(repo, env, "remote", "add", "origin", "ssh://git@example.invalid/x/y.git");
2178
+
2179
+ const { log } = sshStub(bin, "ssh");
2180
+
2181
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
2182
+ assert.equal(r.status, 2, "the stub always fails, so this is 'could not look', never free");
2183
+
2184
+ assertBoundOptions(log);
2185
+ });
2186
+
2187
+ // core.sshCommand SET BUT EMPTY — the case the `-n` guard exists for, and the
2188
+ // one that makes this tier irreducible to a single `$(… || echo ssh)`
2189
+ // substitution: `git config --get` exits 0 with empty output for an empty
2190
+ // value, so an exit-status test reads "configured" and hands git no program.
2191
+ // Measured, that broken form passed the whole suite before this test existed.
2192
+ test("probe 2: an empty core.sshCommand falls back to plain ssh, not to an empty program", (t) => {
2193
+ const { repo, env, bin } = fixture(t, 8, { origin: "none" });
2194
+ git(repo, env, "remote", "add", "origin", "ssh://git@example.invalid/x/y.git");
2195
+ git(repo, env, "config", "core.sshCommand", "");
2196
+
2197
+ const { log } = sshStub(bin, "ssh");
2198
+
2199
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
2200
+ assert.equal(r.status, 2, "the stub always fails, so this is 'could not look', never free");
2201
+
2202
+ assertBoundOptions(log);
2203
+ });
2204
+
2205
+ // --- #96: accumulate rather than abort. A probe that cannot answer used to
2206
+ // `die` immediately, discarding a sufficient hit any other probe had already
2207
+ // found (or would still find) — the whole point of the three probes being a
2208
+ // monotone disjunction. Now each records itself unknown and the run
2209
+ // continues; hits still win outright, and exit 2 carries a payload naming
2210
+ // which probes could not look, so "exit 2" stops meaning "no stdout at all".
2211
+ //
2212
+ // Both directions of the hit-survives-a-later-failure pair are pinned below,
2213
+ // with probe 2 (remote, via the already-supported `origin: "unreachable"`)
2214
+ // as the probe that fails in each: probe 1 finding a hit before probe 2 dies,
2215
+ // and probe 3 finding one after. The other four orderings ((pr, local),
2216
+ // (remote, pr), (remote, local), (local, pr) as hit/fail pairs) are left
2217
+ // unpinned here on purpose — the fix is probe-agnostic by construction, the
2218
+ // same `probe_X || :` shape for all three with no branching on which probe is
2219
+ // which, so a fault that broke one ordering and not its symmetric twin would
2220
+ // have to live inside one probe's own body.
2221
+ //
2222
+ // Which is NOT the same as those bodies being covered, and an earlier version
2223
+ // of this comment claimed it was. Measured by mutation during #406's review:
2224
+ // replacing `add_unknown …; return 1` with a silent `return 0` at six internal
2225
+ // branches — probe 1's `gh pr list failed`, `could not filter PR search
2226
+ // results` and `could not count the PR search results`, probe 3's `cannot
2227
+ // resolve the git common directory`, `could not test the refs directories
2228
+ // under` and `git worktree list failed` — left this whole file green, six
2229
+ // mutants surviving. What the tests above pin is each probe's OUTWARD answer
2230
+ // on the failures they can drive through the fixture (an unreachable GitHub, an
2231
+ // unreachable origin, an unreadable refs directory or worktree registry, a
2232
+ // filter that cannot run): the exit code, `hits` and `unknown`. Which internal
2233
+ // branch produced that answer is mostly not pinned, and per-branch coverage is
2234
+ // still open — see the issue filed from #406's review.
2235
+ //
2236
+ // The gap that mattered is closed here rather than left to that issue: #406
2237
+ // found accumulation was per-PROBE, not per-SIGNAL, so a hit already computed
2238
+ // inside a probe was still discarded when a LATER stage of that same probe
2239
+ // failed. The two same-probe cases below pin both halves of that fix, and the
2240
+ // probe-1 filter case pins one of the six branches above.
2241
+
2242
+ test("accumulate: an open linked PR survives an unreachable origin — probe 1's hit outlives probe 2's failure", (t) => {
2243
+ const r = inflight(7, { linked: [12], prs: [pr(12, "OPEN", "fix/other-thing")], origin: "unreachable" }, t);
2244
+ assert.equal(r.code, 1, "the PR hit alone is sufficient — taken, not unanswerable");
2245
+ assert.equal(r.json.taken, true);
2246
+ assert.equal(r.json.evidence.pr, "#12 OPEN (linked)", "the hit found before the failure is not discarded");
2247
+ assert.deepEqual(r.json.hits, ["pr"]);
2248
+ assert.deepEqual(r.json.unknown, ["remote"], "the probe that could not look is named, not silently dropped");
2249
+ });
2250
+
2251
+ test("accumulate: a local worktree survives an unreachable origin — probe 3's hit outlives probe 2's failure", (t) => {
2252
+ const r = inflight(77, { detachedWorktreeUnder: "nospace", origin: "unreachable" }, t);
2253
+ assert.equal(r.code, 1, "the worktree hit alone is sufficient — taken, not unanswerable");
2254
+ assert.equal(r.json.taken, true);
2255
+ assert.match(r.json.evidence.worktree, /nospace\/fix-77-slug$/, "the hit found after the failure is not discarded either");
2256
+ assert.deepEqual(r.json.hits, ["local"]);
2257
+ assert.deepEqual(r.json.unknown, ["remote"]);
2258
+ });
2259
+
2260
+ // --- #406: the same discard, one level down. A hit is committed where it is
2261
+ // established, not at the end of the probe that established it.
2262
+
2263
+ test("accumulate: a PR hit outlives a later failure in its OWN probe — the diagnostic count cannot retract it", (t) => {
2264
+ // The counting python3 only fills in the "(N full-text match(es))" tally on
2265
+ // stderr; `$pr` is the answer and the filter call above it already produced
2266
+ // one. Measured with this shim before the fix: exit 2, `hits:[]`,
2267
+ // `unknown:["pr"]`, while `evidence.pr` in the same payload read
2268
+ // "#12 OPEN (linked)" — the proof the ticket was taken, thrown away over a
2269
+ // number nothing decides on.
2270
+ const r = inflight(7, {
2271
+ linked: [12], prs: [pr(12, "OPEN", "fix/other-thing")],
2272
+ python3FailWhenProgramHas: "len(json.load",
2273
+ }, t);
2274
+ assert.equal(r.code, 1, "the PR answer was established, so this is taken — not unanswerable");
2275
+ assert.equal(r.json.taken, true);
2276
+ assert.equal(r.json.evidence.pr, "#12 OPEN (linked)");
2277
+ assert.deepEqual(r.json.hits, ["pr"], "the hit survives a later stage of its own probe");
2278
+ assert.deepEqual(r.json.unknown, [], "a stage that cannot change the answer records no unknown");
2279
+ assert.match(r.stderr, /\(\? full-text match\(es\) considered\)/,
2280
+ "and the tally that could not run says so rather than printing a number it does not have");
2281
+ });
2282
+
2283
+ test("accumulate: a local-branch hit outlives a later failure in its OWN probe — the worktree half", (t) => {
2284
+ // Built by hand, and NOT `detachedWorktreeUnder`: that option is detached
2285
+ // precisely so no local branch exists, which is the reason every registry-
2286
+ // failure test above asserts `hits: []` and none of them could catch this.
2287
+ // Here the branch is the hit and the worktree filter is the later failure.
2288
+ const { repo, env } = fixture(t, 77, { awkFailWhenProgramHas: "substr($0,10)" });
2289
+ git(repo, env, "commit", "-q", "--allow-empty", "-m", "x");
2290
+ git(repo, env, "branch", "fix/77-slug");
2291
+
2292
+ // Measured before the fix: exit 2, `hits:[]`, `unknown:["local"]`, with
2293
+ // `evidence.localBranch` naming `fix/77-slug` in the same payload.
2294
+ const r = spawnSync("sh", [SCRIPT, "77"], { cwd: repo, env, encoding: "utf8" });
2295
+ assert.equal(r.status, 1, "the branch alone is sufficient — taken, not unanswerable");
2296
+ const json = JSON.parse(r.stdout);
2297
+ assert.equal(json.taken, true);
2298
+ assert.equal(json.evidence.localBranch, "fix/77-slug");
2299
+ assert.deepEqual(json.hits, ["local"], "recorded once, at the half that answered");
2300
+ assert.deepEqual(json.unknown, ["local"],
2301
+ "and the half that could not look is still named — a hit outranks it, it is not erased by it");
2302
+ assert.doesNotMatch(r.stderr, /no local branch or worktree/,
2303
+ "the probe found one, so it never reports finding none");
2304
+ });
2305
+
2306
+ test("probe 1: a PR filter that could not run is unknown, never free", (t) => {
2307
+ // The filter is the stage the count above is not: it produces `$pr`, the PR
2308
+ // answer itself, so its failure genuinely leaves the question unanswered.
2309
+ // One of the six branches the preamble above names as unpinned — a silent
2310
+ // `return 0` here reads as "no PR is about #7" and frees a taken ticket.
2311
+ const r = inflight(7, {
2312
+ linked: [12], prs: [pr(12, "OPEN", "fix/other-thing")],
2313
+ python3FailWhenProgramHas: "seg = re.compile",
2314
+ }, t);
2315
+ assert.equal(r.code, 2, "unanswerable is exit 2, not the exit 0 that means free");
2316
+ assert.match(r.stderr, /could not filter PR search results for #7/);
2317
+ assert.doesNotMatch(r.stderr, /no PR is about/, "a stage that could not run never reports 'no'");
2318
+ assert.deepEqual(r.json.hits, []);
2319
+ assert.deepEqual(r.json.unknown, ["pr"]);
2320
+ });
2321
+
2322
+ test("accumulate: all three probes unanswerable is exit 2 WITH a payload naming all three", (t) => {
2323
+ if (EUID0) return t.skip(NO_DENIAL);
2324
+ const { repo, env } = fixture(t, 999, {
2325
+ issueErr: "dial tcp: lookup api.github.com: no such host", origin: "unreachable",
2326
+ });
2327
+ const refsdir = join(repo, ".git", "refs", "heads");
2328
+ chmodSync(refsdir, 0o000);
2329
+ const r = spawnSync("sh", [SCRIPT, "999"], { cwd: repo, env, encoding: "utf8" });
2330
+ // Restored before the first assert, or a failure here leaves a fixture the
2331
+ // suite's own cleanup cannot remove.
2332
+ chmodSync(refsdir, 0o755);
2333
+
2334
+ assert.equal(r.status, 2);
2335
+ assert.notEqual(r.stdout.trim(), "", "exit 2 from a probe failure now carries a payload");
2336
+ const json = JSON.parse(r.stdout);
2337
+ assert.equal(json.taken, false);
2338
+ assert.deepEqual(json.hits, []);
2339
+ assert.deepEqual(json.unknown.slice().sort(), ["local", "pr", "remote"],
2340
+ "every probe that could not answer is named, not just the first one to fail");
2341
+ });
2342
+
2343
+ test("accumulate: a genuinely free ticket still exits 0, with an empty unknown list", (t) => {
2344
+ const r = inflight(8, {}, t);
2345
+ assert.equal(r.code, 0);
2346
+ assert.equal(r.json.taken, false);
2347
+ assert.deepEqual(r.json.hits, []);
2348
+ assert.deepEqual(r.json.unknown, [], "nothing failed, so nothing is unknown");
2349
+ });
2350
+
2351
+ // --- #96: the accumulate change must not manufacture a payload where none
2352
+ // existed before. Nothing has been established yet for either of these —
2353
+ // no probe has run — so both stay a hard, payload-less exit 2 exactly as
2354
+ // before.
2355
+
2356
+ test("accumulate: a bad argument is still refused before any probe runs, with no payload", (t) => {
2357
+ const r = spawnSync("sh", [SCRIPT, "abc"], { encoding: "utf8" });
2358
+ assert.equal(r.status, 2);
2359
+ assert.equal(r.stdout.trim(), "", "nothing has been established yet — this is not a probe failure");
2360
+ assert.match(r.stderr, /issue must be a number/);
2361
+ });
2362
+
2363
+ test("accumulate: a zero-padded issue is refused before any probe runs, with no payload", (t) => {
2364
+ // All-digits is not a JSON number — RFC 8259 forbids a leading zero — so
2365
+ // `007` used to clear the guard, reach the verdict printf and emit
2366
+ // `{"issue":007,…}` at exit 0: unparseable, with an exit code that gave the
2367
+ // caller no hint (#121). The guard's `0?*` arm refuses it at the same
2368
+ // boundary as a non-numeric argument. Normalising with `n=$((n))` instead
2369
+ // would be worse than the bug: /bin/sh reads `007` as octal 7 and `010` as
2370
+ // 8, silently answering about a different ticket. Two widths, because one
2371
+ // does not pin the guard: `0?*` narrowed to `0??*` still refuses `007` and
2372
+ // re-admits `01`, which is the same bug back.
2373
+ for (const padded of ["007", "01"]) {
2374
+ const r = spawnSync("sh", [SCRIPT, padded], { encoding: "utf8" });
2375
+ assert.equal(r.status, 2, padded);
2376
+ assert.equal(r.stdout.trim(), "", "nothing has been established yet — this is not a probe failure");
2377
+ assert.match(r.stderr, /issue must be a number/);
2378
+ }
2379
+ });
2380
+
2381
+ test("accumulate: a bare 0 clears the numeric guard", (t) => {
2382
+ // `0?*`, not `0*`: #121 lists `sh inflight.sh 0 -> parses` among its PASSING
2383
+ // cases, beside `42`. A bare `0` is a valid RFC 8259 number and `$((0))` is
2384
+ // `0`, so neither hazard the guard exists to close applies to it. Widening
2385
+ // the arm would refuse a value the ticket's own worked example shows working.
2386
+ const r = inflight(0, {}, t);
2387
+ assert.equal(r.code, 0);
2388
+ assert.equal(r.json.issue, 0, "emitted as a JSON number, and the payload parses");
2389
+ });
2390
+
2391
+ test("accumulate: an unpadded issue number still reaches a parseable verdict", (t) => {
2392
+ // The other half of #121's guard, and the half that would strand the fleet if
2393
+ // it were wrong: `gh` never zero-pads, so every legitimate caller passes a
2394
+ // bare number and must still be answered. Over-refusal is not subtle — under
2395
+ // a guard that refuses every digit string, the only cases left standing are
2396
+ // the two that expect a refusal anyway (`a bad argument …` and `a zero-padded
2397
+ // issue …`); every other test in this file goes red. Stated that way rather
2398
+ // than as a fraction, because the fraction rots on any PR that adds a test —
2399
+ // it read "70 of 72" until #185 made it 77 of 79 (both measured) —
2400
+ // so what this test adds is diagnosis, not detection: a name that says which
2401
+ // half of the guard broke, and an assertion that `issue` is emitted as a JSON
2402
+ // number rather than a string (rewrite the verdict printf to `{"issue":"%s"`
2403
+ // and only this test and the bare-0 one above fail).
2404
+ const r = inflight(7, {}, t);
2405
+ assert.equal(r.code, 0);
2406
+ assert.equal(r.json.issue, 7, "emitted as a JSON number, and the payload parses");
2407
+ });
2408
+
2409
+ test("accumulate: outside a git repository is still refused before any probe runs, with no payload", (t) => {
2410
+ const outside = mkdtempSync(join(tmpdir(), "inflight-not-a-repo-"));
2411
+ t.after(() => {
2412
+ spawnSync("chmod", ["-R", "u+rwX", outside]);
2413
+ execFileSync("rm", ["-rf", outside]);
2414
+ });
2415
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: outside, encoding: "utf8" });
2416
+ assert.equal(r.status, 2);
2417
+ assert.equal(r.stdout.trim(), "", "nothing has been established yet — this is not a probe failure");
2418
+ assert.match(r.stderr, /not inside a git repository/);
2419
+ });
2420
+
2421
+ // --- #91: the temp file `gh`'s stderr is captured to. Two problems, one fix:
2422
+ // a fixed /tmp/.inflight.$$ was guessable and symlink-truncatable, and a
2423
+ // capture that failed for its own reasons (unwritable /tmp, a full
2424
+ // filesystem) read back as an empty cause, indistinguishable from gh itself
2425
+ // having said nothing.
2426
+
2427
+ test("probe 1: gh failing with nothing on stderr still names a cause, not a blank tail", (t) => {
2428
+ // An empty `issueErr`, not a second knob — gh failed and printed nothing,
2429
+ // which is also what a capture that could not even write looks like, and is
2430
+ // distinct from every other failure case in this file, all of which have
2431
+ // real text to report.
2432
+ const r = inflight(8, { issueErr: "" }, t);
2433
+ assert.equal(r.code, 2);
2434
+ assert.match(r.stderr, /PR links are unknown: cause unavailable/,
2435
+ "an empty capture says so instead of trailing off after the colon");
2436
+ });
2437
+
2438
+ // The same fix lands on probe 1's SECOND gh call, and both call sites now read
2439
+ // the capture back through one `gh_cause`. These two are what prove the helper
2440
+ // is wired at BOTH sites rather than only at the first: hardcoding the fallback
2441
+ // here kills the text case, dropping the fallback from the helper kills the
2442
+ // silent case (and its `gh issue view` twin above).
2443
+ test("probe 1: gh pr list failing carries its own cause into the unknown it records", (t) => {
2444
+ const r = inflight(8, { prErr: "HTTP 403: API rate limit exceeded" }, t);
2445
+ assert.equal(r.code, 2);
2446
+ assert.match(r.stderr, /whether #8 is taken is unknown: HTTP 403: API rate limit exceeded/,
2447
+ "the cause is read back from the capture, not substituted for");
2448
+ assert.deepEqual(r.json.unknown, ["pr"]);
2449
+ });
2450
+
2451
+ test("probe 2's call: gh pr list failing with nothing on stderr still names a cause", (t) => {
2452
+ const r = inflight(8, { prErr: "" }, t);
2453
+ assert.equal(r.code, 2);
2454
+ assert.match(r.stderr, /whether #8 is taken is unknown: cause unavailable/,
2455
+ "the second capture site inherits the fallback instead of re-deriving it");
2456
+ });
2457
+
2458
+ test("mktemp failing leaves probe 2 to answer, rather than abandoning the run", (t) => {
2459
+ // A temp file is a probe's own resource, so losing it is "that probe could
2460
+ // not look" — not "the question cannot be answered". Measured with the
2461
+ // `|| die` this replaces, on this very fixture: exit 2, empty stdout, every
2462
+ // hit discarded.
2463
+ //
2464
+ // TWO probes need one since #185: probe 1 captures gh's stderr, and probe 3
2465
+ // holds the NUL-delimited worktree listing, which no shell variable can. So
2466
+ // a broken mktemp now blinds both, and only probe 2 — which needs neither gh
2467
+ // nor a file — still answers. That widening costs the QUEUE nothing: probe
2468
+ // 1's unknown alone already forced exit 2 on a ticket with no hit, so a
2469
+ // broken TMPDIR starved the queue before #185 exactly as it does after. It
2470
+ // moves in the safe direction besides — a probe that cannot look reports
2471
+ // unknown, never the "free" that would put two implementers on one ticket.
2472
+ //
2473
+ // Still kills the mutant the die killed: reverting to the old fixed
2474
+ // /tmp/.inflight.$$ path calls no mktemp at all, so this stub goes untouched,
2475
+ // probe 1 succeeds and `unknown` comes back empty.
2476
+ const { repo, env, bin } = fixture(t, 8, {
2477
+ remoteBranches: ["fix/8-thing"], detachedWorktreeUnder: "nospace",
2478
+ });
2479
+ writeFileSync(join(bin, "mktemp"), "#!/bin/sh\nexit 1\n");
2480
+ chmodSync(join(bin, "mktemp"), 0o755);
2481
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
2482
+ assert.equal(r.status, 1, "the probe that could still look found the ticket taken");
2483
+ const json = JSON.parse(r.stdout);
2484
+ assert.equal(json.taken, true);
2485
+ assert.deepEqual(json.hits, ["remote-branch"],
2486
+ "the hit from the probe that needs no temp file is not discarded");
2487
+ assert.deepEqual(json.unknown, ["pr", "local"], "and both probes that could not look are named");
2488
+ assert.match(r.stderr, /could not create a temporary file to capture gh's stderr/);
2489
+ assert.match(r.stderr, /could not create a temporary file to hold the worktree list/,
2490
+ "probe 3's own message, not probe 1's reused");
2491
+ });
2492
+
2493
+ test("cleanup that cannot remove the capture file never rewrites the verdict", (t) => {
2494
+ if (EUID0) return t.skip(NO_DENIAL);
2495
+ // The EXIT trap runs OUTSIDE the probe bodies, where `set -e` is live, so a
2496
+ // bare `rm -f` that fails aborts the shell with status 1 — and 1 is this
2497
+ // script's code for "taken". Measured on the unguarded trap: this free
2498
+ // ticket exited 1 while its own payload still said `taken:false`, and a run
2499
+ // that should have exited 2 came back 1 as well. The verdict is computed and
2500
+ // announced on stderr first, then overwritten by cleanup.
2501
+ const { repo, env, bin } = fixture(t, 8, {});
2502
+ const cap = join(bin, "..", "cap");
2503
+ // mktemp still hands back a real 0600 file; only its DIRECTORY is made
2504
+ // unremovable, which is what `rm -f` fails on (a read-only mount, perms
2505
+ // changed under the run). Writing the capture is unaffected: `2>` needs
2506
+ // permission on the file, not on the directory.
2507
+ writeFileSync(join(bin, "mktemp"), `#!/bin/sh
2508
+ mkdir -p '${cap}' && chmod 755 '${cap}'
2509
+ f='${cap}'/cap.$$
2510
+ (umask 077; : > "$f") || exit 1
2511
+ chmod 555 '${cap}'
2512
+ printf '%s\\n' "$f"
2513
+ `);
2514
+ chmodSync(join(bin, "mktemp"), 0o755);
2515
+ const r = spawnSync("sh", [SCRIPT, "8"], { cwd: repo, env, encoding: "utf8" });
2516
+ // Restored before the first assert, or a failure here leaves a fixture the
2517
+ // suite's own cleanup cannot remove.
2518
+ chmodSync(cap, 0o755);
2519
+
2520
+ assert.equal(r.status, 0, "a free ticket stays free — cleanup does not get to speak for the verdict");
2521
+ assert.equal(JSON.parse(r.stdout).taken, false, "and the payload the caller reads agrees with the code");
2522
+ assert.match(r.stderr, /could not remove .*\/cap\./,
2523
+ "the removal that failed is said out loud rather than swallowed");
2524
+ });
2525
+
2526
+ // --- #119: the escaping library this script now sources rather than carries.
2527
+ //
2528
+ // `.` is a POSIX special builtin, so failing to open its operand aborts a
2529
+ // non-interactive shell before any `||` on the line can run. Measured on
2530
+ // /bin/sh (macOS bash 3.2), bash 3.2 and `bash --posix`, that abort exits **1**
2531
+ // — and exit 1 here is not an error, it is the verdict `taken`. A ticket nobody
2532
+ // had claimed would come back claimed, on nothing but a missing file. The
2533
+ // script's guard is an `[ -r ]` ahead of the `.` for exactly that reason, and
2534
+ // this is the test that keeps it there.
2535
+ test("a missing json.sh exits 2, never the exit 1 that means `taken`", (t) => {
2536
+ const { repo, env } = fixture(t, 7, {});
2537
+ // The script alone in a directory with no json.sh beside it — the shape a
2538
+ // half-installed plugin takes. `dirname "$0"` resolves here, so this is the
2539
+ // real resolution path and not a stubbed stand-in for it.
2540
+ const lone = mkdtempSync(join(tmpdir(), "inflight-nolib-"));
2541
+ t.after(() => {
2542
+ spawnSync("chmod", ["-R", "u+rwX", lone]);
2543
+ execFileSync("rm", ["-rf", lone]);
2544
+ });
2545
+ copyFileSync(SCRIPT, join(lone, "inflight.sh"));
2546
+
2547
+ const r = spawnSync("sh", [join(lone, "inflight.sh"), "7"], { cwd: repo, env, encoding: "utf8" });
2548
+
2549
+ assert.equal(r.status, 2,
2550
+ "a missing library is `the question could not be answered`, never a verdict. Exit 1 here reads as `taken` and would fabricate a claim on a free ticket; exit 0 would free a ticket without probing.");
2551
+ assert.match(r.stderr, /json\.sh/,
2552
+ "and it names the file, so the operator is not left guessing which of this script's exit-2 paths fired");
2553
+ assert.equal(r.stdout, "",
2554
+ "no payload — a verdict was never established, so there is nothing to report");
2555
+ });
2556
+
2557
+ // --- #346: the bound outside git.
2558
+ //
2559
+ // #92 asked that an unattended probe never hang; PR #332 answered it with git's
2560
+ // own transport knobs, which reach only part of the class. What they miss is
2561
+ // re-derived here rather than quoted: against the accept-then-silent listener
2562
+ // below, with `http.lowSpeedLimit=1000 -c http.lowSpeedTime=10` set exactly as
2563
+ // probe 2 sets them, an `https` origin was still running when a 30s harness cap
2564
+ // killed it — curl's low-speed timer never arms because the TLS handshake never
2565
+ // completes, so no transfer is ever under way for it to time.
2566
+ //
2567
+ // So the bound has to come from outside git: background the fetch, kill it at a
2568
+ // budget. `INFLIGHT_LS_REMOTE_TIMEOUT` is how these cases buy a short budget
2569
+ // instead of paying the default one per test; it can only ever shorten, which
2570
+ // is what keeps it from being a new way to remove the bound — the very shape of
2571
+ // defect the ssh half of this issue reports.
2572
+ //
2573
+ // Every case here asserts `r.error` is unset alongside its exit code, and that
2574
+ // is not belt-and-braces. `spawnSync` waits on the inherited stdio pipes as well
2575
+ // as on the pid, so a transport helper that outlives the fetch holds the caller
2576
+ // for the full backstop with the answer already written and the direct child
2577
+ // already reaped — status set, `signal` null, and only `error`/elapsed able to
2578
+ // see it. Measured against this exact listener: killing the fetch process alone
2579
+ // left a `git remote-https` holding stderr and the caller sat out its whole cap.
2580
+ const silentListener = async (t) => {
2581
+ const server = createServer(); // accept, hold open, send nothing back
2582
+ t.after(() => new Promise((res) => server.close(res)));
2583
+ await new Promise((res) => server.listen(0, "127.0.0.1", res));
2584
+ return server.address().port;
2585
+ };
2586
+
2587
+ test("probe 2: an https origin whose handshake never completes is bounded, exit 2", async (t) => {
2588
+ const port = await silentListener(t);
2589
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2590
+ git(repo, env, "remote", "add", "origin", `https://127.0.0.1:${port}/x/y.git`);
2591
+
2592
+ const started = Date.now();
2593
+ const r = spawnSync("sh", [SCRIPT, "8"],
2594
+ { cwd: repo, env: { ...env, INFLIGHT_LS_REMOTE_TIMEOUT: "5" }, encoding: "utf8", timeout: 30_000 });
2595
+
2596
+ assert.equal(r.error, undefined,
2597
+ `the caller was held to its own backstop — either the script never terminated, or something it spawned outlived it still holding stderr: ${JSON.stringify(r)}`);
2598
+ assert.notEqual(r.signal, "SIGTERM", "the script's own bound must fire, not the test's backstop");
2599
+ assert.ok(Date.now() - started < 30_000, "must terminate on its own bound, not the test's backstop");
2600
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
2601
+ assert.match(r.stderr, /did not finish within/,
2602
+ "the timeout gets its own reason: a probe that was killed and one that was refused are different facts, and before this bound existed the only failure surface was reached when ls-remote RETURNED, so a stall was indistinguishable from a slow link");
2603
+ assert.match(r.stderr, /whether #8 has a remote branch is unknown/);
2604
+ });
2605
+
2606
+ // The default budget and the shorten-only rule, which every other case here
2607
+ // leaves untouched: they all BUY a short budget, so `ls_budget=30` and the
2608
+ // `-lt` clamp are never the operative path. Measured on the tree before this
2609
+ // case existed — raising the default tenfold AND flipping the clamp to `-gt 0`
2610
+ // left the whole inflight suite green, both mutants passing 89/89. The property
2611
+ // the comment beside that clamp argues, that the knob cannot become "one more
2612
+ // way for configuration to remove the bound", shipped with nothing holding it.
2613
+ //
2614
+ // This is the only case that pays the real 30s, and it is worth the wall clock
2615
+ // because it pins both halves at once: a value far above the default has to be
2616
+ // REFUSED, which leaves the reported budget at 30 and the wait at 30 rather
2617
+ // than the 600 asked for. Either mutant lengthens the real wait past this
2618
+ // case's own backstop and reddens it.
2619
+ test("probe 2: INFLIGHT_LS_REMOTE_TIMEOUT cannot lengthen the default budget", async (t) => {
2620
+ const port = await silentListener(t);
2621
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2622
+ git(repo, env, "remote", "add", "origin", `https://127.0.0.1:${port}/x/y.git`);
2623
+
2624
+ const started = Date.now();
2625
+ const r = spawnSync("sh", [SCRIPT, "8"],
2626
+ { cwd: repo, env: { ...env, INFLIGHT_LS_REMOTE_TIMEOUT: "600" }, encoding: "utf8", timeout: 90_000 });
2627
+
2628
+ assert.equal(r.error, undefined,
2629
+ `the caller was held to its own backstop, so the 600 was taken as a budget rather than refused: ${JSON.stringify(r)}`);
2630
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
2631
+ assert.match(r.stderr, /did not finish within 30s/,
2632
+ "the override may only SHORTEN: a value above the default is ignored and the default 30s is what the watchdog reports — a knob that could lengthen the budget is one more way for configuration to remove the bound, the very defect the ssh half of #346 reports");
2633
+ assert.ok(Date.now() - started < 60_000,
2634
+ "and the wait really was the default budget, not the 600s asked for");
2635
+ });
2636
+
2637
+ // The other end of the same guard, and it needs no stall: the comment beside it
2638
+ // says an unusable value "is not an error", and until the digit-count arm landed
2639
+ // the shell contradicted that sentence out loud. `*[!0-9]*` catches `5s` and
2640
+ // `-1` but passes any all-digit string straight into `[`, which then reports a
2641
+ // value it cannot represent — naming a LINE NUMBER, not the variable, on the
2642
+ // same stderr this script writes its own reasons to.
2643
+ //
2644
+ // Both wordings are refused, because only one of them is reachable from here:
2645
+ // `sh` on darwin says "integer expression expected" and the dash that is
2646
+ // `/bin/sh` on CI says "Illegal number", so a pin written against either one
2647
+ // alone is vacuous on the other platform.
2648
+ test("probe 2: a budget too large for the shell's integer is ignored, and says nothing", (t) => {
2649
+ const { repo, env } = fixture(t, 8, { remoteBranches: ["main", "fix/other-thing"] });
2650
+ const r = spawnSync("sh", [SCRIPT, "8"],
2651
+ { cwd: repo, env: { ...env, INFLIGHT_LS_REMOTE_TIMEOUT: "99999999999999999999" }, encoding: "utf8", timeout: 30_000 });
2652
+
2653
+ assert.equal(r.status, 0,
2654
+ "an unusable value is not an error — the default stands and the probe still answers");
2655
+ assert.equal(JSON.parse(r.stdout).taken, false, "and answers with the verdict it would have reached anyway");
2656
+ assert.doesNotMatch(r.stderr, /integer expression expected|Illegal number/,
2657
+ "`[` must never be handed a value too large for the shell's integer: a raw diagnostic naming a line number is the guard's comment being contradicted on the surface the guard writes to");
2658
+ });
2659
+
2660
+ // The control, and the reason this whole change is not simply "kill it sooner":
2661
+ // a watchdog that turns a working slow fetch into exit 2 is worse than the hang
2662
+ // it replaces, because exit 2 is a verdict the fleet acts on. The stub here is a
2663
+ // REAL working transport — it serves the fixture's own bare repo through
2664
+ // `git upload-pack` — delayed on the way in. So the case exercises the accept
2665
+ // path with genuine refs coming back, not a mock of one.
2666
+ //
2667
+ // Paired with its own sensitivity control below, and neither is worth much
2668
+ // alone: an accept-only case passes just as well against a watchdog that never
2669
+ // fires at all, which is to say against no watchdog, and would have passed
2670
+ // before this change existed. The stub is slow-transport.mjs's, shared with
2671
+ // every other bounded-fetch pair: its delay is the constant the pair's two
2672
+ // budgets — 20 above it, 1 below it — are chosen against, and it runs no
2673
+ // freshly written executable inside the region the budget bounds (#2221).
2674
+ // This file's own copy of it did, and paid macOS's first-exec scan in there.
2675
+
2676
+ test("probe 2: a slow but working link keeps its ordinary verdict, budget or no budget", (t) => {
2677
+ const { repo, env } = fixture(t, 41, { remoteBranches: ["main", "fix/41-thing"] });
2678
+ const sshCommand = slowTransport(join(repo, "..", "remote.git"));
2679
+ git(repo, env, "remote", "set-url", "origin", SSH_URL);
2680
+
2681
+ const r = spawnSync("sh", [SCRIPT, "41"], {
2682
+ cwd: repo, encoding: "utf8", timeout: 60_000,
2683
+ env: { ...env, GIT_SSH_COMMAND: sshCommand, INFLIGHT_LS_REMOTE_TIMEOUT: "20" },
2684
+ });
2685
+
2686
+ assert.equal(r.error, undefined, `the run did not come back: ${JSON.stringify(r)}`);
2687
+ assert.equal(r.status, 1,
2688
+ "the branch is really on the remote, so the verdict is `taken` — a bound that reports exit 2 here has invented an outage on a link that worked");
2689
+ assert.deepEqual(JSON.parse(r.stdout).hits, ["remote-branch"],
2690
+ "and the hit is probe 2's own, established from refs the slow transport really returned");
2691
+ });
2692
+
2693
+ // The other half of that pair: the same working transport, a budget under the
2694
+ // delay. Without this, the case above cannot tell a watchdog that spares slow
2695
+ // links from one that was never armed.
2696
+ test("probe 2: the budget is what spares the slow link, not the absence of a watchdog", (t) => {
2697
+ const { repo, env } = fixture(t, 41, { remoteBranches: ["main", "fix/41-thing"] });
2698
+ const sshCommand = slowTransport(join(repo, "..", "remote.git"));
2699
+ git(repo, env, "remote", "set-url", "origin", SSH_URL);
2700
+
2701
+ const r = spawnSync("sh", [SCRIPT, "41"], {
2702
+ cwd: repo, encoding: "utf8", timeout: 60_000,
2703
+ env: { ...env, GIT_SSH_COMMAND: sshCommand, INFLIGHT_LS_REMOTE_TIMEOUT: "1" },
2704
+ });
2705
+
2706
+ assert.equal(r.error, undefined, `the run did not come back: ${JSON.stringify(r)}`);
2707
+ assert.equal(r.status, 2, "under the delay, the same transport is cut off and the answer is `could not look`");
2708
+ assert.match(r.stderr, /did not finish within/);
2709
+ });
2710
+
2711
+ // The ssh case this issue gained after it was filed: probe 2 appends its options
2712
+ // after the user's own command and ssh takes the FIRST value of a repeated -o,
2713
+ // so a user ConnectTimeout of 0 wins and is accepted rather than rejected —
2714
+ // leaving the accept-then-silent case riding on nothing, since the ServerAlive
2715
+ // pair never arms before the banner exchange. Honouring that setting is
2716
+ // deliberate and unchanged; what changed is that the call around it is bounded.
2717
+ test("probe 2: a user ConnectTimeout of 0 no longer leaves the probe unbounded", async (t) => {
2718
+ const port = await silentListener(t);
2719
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2720
+ git(repo, env, "remote", "add", "origin", `ssh://git@127.0.0.1:${port}/x/y.git`);
2721
+
2722
+ const started = Date.now();
2723
+ const r = spawnSync("sh", [SCRIPT, "8"], {
2724
+ cwd: repo, encoding: "utf8", timeout: 30_000,
2725
+ env: { ...env, GIT_SSH_COMMAND: "ssh -o ConnectTimeout=0", INFLIGHT_LS_REMOTE_TIMEOUT: "5" },
2726
+ });
2727
+
2728
+ assert.equal(r.error, undefined,
2729
+ `the caller was held to its own backstop — the ssh the fetch spawned outlived it holding stderr: ${JSON.stringify(r)}`);
2730
+ assert.notEqual(r.signal, "SIGTERM", "the script's own bound must fire, not the test's backstop");
2731
+ assert.ok(Date.now() - started < 30_000, "must terminate on its own bound, not the test's backstop");
2732
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
2733
+ assert.match(r.stderr, /did not finish within/);
2734
+ });
2735
+
2736
+ // The surface the issue names in passing, and the one no git-side variable
2737
+ // reaches: GIT_TERMINAL_PROMPT=0 suppresses git's OWN credential prompt, not an
2738
+ // externally configured helper, and neither lowSpeed key times a helper's
2739
+ // execution. A keychain dialog or an OAuth device-code flow is this shape; a
2740
+ // helper that simply never answers stands in for both.
2741
+ //
2742
+ // The 401 is what makes git consult the helper at all — without a challenge the
2743
+ // request never reaches the credential path and the case would pass vacuously.
2744
+ //
2745
+ // And it DID, until this server was moved out of process. `spawnSync` blocks
2746
+ // this process's event loop for the whole child run, so a `node:http` server
2747
+ // running HERE accepts at the kernel level and can never serve a
2748
+ // response: measured, the handler ran zero times and mute-helper.sh was never
2749
+ // executed, leaving a case that only re-tested "an http origin that never
2750
+ // answers" — which `http.lowSpeedTime=10` bounds on its own, so it stayed green
2751
+ // even with net_kill_tree's subtree walk neutered. The 401 has to come from a
2752
+ // process that is still scheduled while spawnSync holds this one.
2753
+ const challengeServer = async (t) => {
2754
+ const srv = spawn(process.execPath, ["-e",
2755
+ `const s=require("node:http").createServer((q,r)=>{r.writeHead(401,{"WWW-Authenticate":'Basic realm="git"'});r.end("denied")});s.listen(0,"127.0.0.1",()=>console.log(s.address().port))`],
2756
+ { stdio: ["ignore", "pipe", "inherit"] });
2757
+ t.after(() => srv.kill());
2758
+ return await new Promise((res) => srv.stdout.once("data", (d) => res(d.toString().trim())));
2759
+ };
2760
+
2761
+ test("probe 2: a credential helper that never answers is bounded like any other stall", async (t) => {
2762
+ const port = await challengeServer(t);
2763
+
2764
+ const { repo, env } = fixture(t, 8, { origin: "none" });
2765
+ git(repo, env, "remote", "add", "origin", `http://127.0.0.1:${port}/x/y.git`);
2766
+ const helper = join(repo, "mute-helper.sh");
2767
+ // Written by the helper's FIRST line, so its existence is the one thing that
2768
+ // separates this case from the vacuous one its comment above describes. See
2769
+ // the assertion at the bottom for why that is not decoration here.
2770
+ const helperRan = join(repo, "helper-ran");
2771
+ // The `--fleet-warm` arm sits above the marker for the reason ledger.test.mjs
2772
+ // records at its own GH_STUB: warming without it would let the warm-up write
2773
+ // the marker itself, and the assertion below — the only thing standing
2774
+ // between this case and the vacuity it already regressed into once — would
2775
+ // read as satisfied on a helper that never ran. git passes a credential
2776
+ // helper its operation and nothing else (measured, git 2.50.1: argv is
2777
+ // exactly `get`), so no real invocation can take the arm.
2778
+ writeFileSync(helper,
2779
+ `#!/bin/sh\ncase " $* " in *" --fleet-warm "*) exit 0 ;; esac\n: > '${helperRan}'\nsleep 300\n`);
2780
+ chmodSync(helper, 0o755);
2781
+ git(repo, env, "config", "credential.helper", helper);
2782
+
2783
+ // Pay this helper's first-exec OS scan HERE, before the timed spawn, so it is
2784
+ // spent outside the 5 s budget the watchdog kills the fetch at — #1199's
2785
+ // finding and #1099's ruling on the remedy, reached again from a different
2786
+ // file and a different collision (#1606).
2787
+ //
2788
+ // Measured on this case: the first execution of the freshly written helper
2789
+ // costs ~2.5 s on an idle machine and 5.5-12.9 s under five concurrent copies
2790
+ // of this suite, the fleet's normal condition, while a second execution stays
2791
+ // at ~4 ms either way. The budget is 5 s. So unwarmed the scan never finished
2792
+ // inside it, and the helper was killed mid-scan having executed NONE of its
2793
+ // own lines — `helper-ran` absent in 15 of 15 runs, quiet and loaded alike.
2794
+ //
2795
+ // That is not the reported flake, it is worse and it is deterministic: with
2796
+ // the helper never reaching `sleep 300`, nothing in the case stalled on a
2797
+ // credential at all and it re-tested "an http origin that never answers" —
2798
+ // exactly the vacuity the comment above says moving the 401 out of process
2799
+ // had already fixed once. The 401 does arrive and git does spawn the helper;
2800
+ // what never happened is the helper running. Warmed: 14 of 14 runs reach it,
2801
+ // it really stalls, and net_kill_tree really reaps it (no survivor, and the
2802
+ // caller's stdio closes within 1 ms of the script's own exit).
2803
+ //
2804
+ // Warming, not a longer bound: the 30 s backstop is 5x the observed run and
2805
+ // raising it would only widen the window a helper can hide in. Warming, not a
2806
+ // shared helper, because credential.helper takes a path and the per-case temp
2807
+ // root is what keeps these fixtures isolated.
2808
+ //
2809
+ // "Warming, not a longer bound" is about the timed spawn's 30 s backstop
2810
+ // below, not about this warm-up's own bound, which is 120 s. The warm-up
2811
+ // runs the helper's `--fleet-warm` arm, which exits 0 above the marker write
2812
+ // and the `sleep 300`, so no helper stall can hide in a longer warm-up
2813
+ // bound: the only thing it can extend is the first-exec scan, and letting
2814
+ // that finish is the whole point of warming. Killing it early is worse than
2815
+ // useless — a warm-up killed mid-scan leaves the scan unpaid for the timed
2816
+ // spawn, as PR #2224 measured (first execs 15-16 s under load ~25; one
2817
+ // killed at 500 ms still took 14.5-15.0 s next time) (#2229). It stays
2818
+ // finite only so a truly hung exec still ends the case.
2819
+ spawnSync(helper, ["--fleet-warm"], { timeout: 120_000 });
2820
+
2821
+ const started = Date.now();
2822
+ const r = spawnSync("sh", [SCRIPT, "8"],
2823
+ { cwd: repo, env: { ...env, INFLIGHT_LS_REMOTE_TIMEOUT: "5" }, encoding: "utf8", timeout: 30_000 });
2824
+
2825
+ assert.equal(r.error, undefined,
2826
+ `the caller was held to its own backstop — the helper outlived the fetch still holding stderr, which is exactly what killing the fetch alone would leave: ${JSON.stringify(r)}`);
2827
+ // Before the three assertions below, because all three pass vacuously on a
2828
+ // helper that never ran: an http origin nothing answers reaches the same exit
2829
+ // 2 and the same wording through git's own transport, with the credential
2830
+ // path never entered. This is what makes the case about a CREDENTIAL helper.
2831
+ assert.equal(existsSync(helperRan), true,
2832
+ "the helper never executed a line, so nothing here stalled on a credential and the case degenerated into `an http origin that never answers` — which http.lowSpeedTime bounds on its own");
2833
+ assert.ok(Date.now() - started < 30_000, "must terminate on its own bound, not the test's backstop");
2834
+ assert.equal(r.status, 2, "unanswerable is exit 2, not the exit 0 that means free");
2835
+ assert.match(r.stderr, /did not finish within/);
2836
+ });
2837
+
2838
+ // The other half of the case above, and it needs a different technique. The
2839
+ // `helper-ran` assertion is what catches the vacuity UNDER LOAD, where the
2840
+ // scan runs 5.5-12.9 s and never fits the 5 s budget; it does not catch it on
2841
+ // an idle machine, where the scan is ~2.5 s and the helper squeezes in warmed
2842
+ // or not. Measured: deleting the warm-up line leaves this file green, 1 pass /
2843
+ // 0 fail, on a quiet host — the exact hole #1199 hit, and its remedy is the
2844
+ // same one ledger.test.mjs, arg.mjs's die() and candidates.mjs's EXCLUDE use.
2845
+ //
2846
+ // So the SHAPE is pinned as well, read back through stripComments() so a
2847
+ // comment alone cannot satisfy it, and anchored at line starts under `/m` so an
2848
+ // unrelated line inserted between the steps cannot still match.
2849
+ //
2850
+ // Anchored per STATEMENT, not per line (#2265): inside the warm-up call and
2851
+ // the writeFileSync() call every token boundary is `\s*`, and a trailing comma
2852
+ // is allowed wherever JS allows one, so wrapping either call across lines — a
2853
+ // behavior-neutral reformat a formatter makes on its own — cannot red this pin
2854
+ // the way deleting the call does. Only whitespace is free: every token, the
2855
+ // timeout's floor included, is still literal and in order.
2856
+ test("the credential helper's warm-up survives — deleting it would let a cold exec scan empty the case again (structural pin, #1606)", () => {
2857
+ const src = stripComments(readFileSync(THIS_FILE, "utf8"));
2858
+ const warmUp = /^\s*chmodSync\(helper, 0o755\);\s*^\s*git\(repo, env, "config", "credential\.helper", helper\);\s*^\s*spawnSync\(\s*helper,\s*\[\s*"--fleet-warm",?\s*\],\s*\{\s*timeout:\s*\d{3}_\d{3},?\s*\},?\s*\);\s*^\s*const started = Date\.now\(\);[\s\S]*?^\s*assert\.equal\(existsSync\(helperRan\), true,/m;
2859
+ assert.match(
2860
+ src,
2861
+ warmUp,
2862
+ "the helper must be warmed after it is written and configured and BEFORE the timed spawn, and the vacuity-guard assertion (assert.equal(existsSync(helperRan), true, ...)) must still exist below it — deleting either reopens #1606, and the suite stays green on an idle machine while it does",
2863
+ );
2864
+ // The input the pin must ACCEPT: the same four statements with the warm-up
2865
+ // wrapped the way a formatter wraps it. Quoted lines joined, never a template
2866
+ // literal — a template's lines would sit at line starts in THIS file's own
2867
+ // source and satisfy the pin above with the real warm-up deleted.
2868
+ assert.match(
2869
+ [
2870
+ " chmodSync(helper, 0o755);",
2871
+ ' git(repo, env, "config", "credential.helper", helper);',
2872
+ ' spawnSync(helper, ["--fleet-warm"], {',
2873
+ " timeout: 120_000,",
2874
+ " });",
2875
+ " const started = Date.now();",
2876
+ " assert.equal(existsSync(helperRan), true,",
2877
+ ].join("\n"),
2878
+ warmUp,
2879
+ "wrapping the warm-up call across lines changes neither its order nor its presence, so the pin must not read it as deleted (#2265)",
2880
+ );
2881
+ // The arm's POSITION inside the helper body, not merely its presence. Below
2882
+ // the marker write, the warm-up call itself would create `helper-ran` before
2883
+ // any timed run ever executes (measured: a lone --fleet-warm invocation on
2884
+ // the mutated order leaves the marker behind by itself): the vacuity
2885
+ // assertion would then read as satisfied on a helper that never ran during
2886
+ // the timed run. That is ledger.test.mjs's GH_STUB lesson, which had to be
2887
+ // learned once already.
2888
+ assert.match(
2889
+ src,
2890
+ /^\s*writeFileSync\(\s*helper,\s*`#!\/bin\/sh\\ncase " \$\* " in \*" --fleet-warm "\*\) exit 0 ;; esac\\n: > '\$\{helperRan\}'\\nsleep 300\\n`,?\s*\);/m,
2891
+ "the --fleet-warm arm must sit ABOVE the marker write, or warming writes the marker itself and the vacuity guard above goes blind — anchored at line starts under `/m` so a coincidental match elsewhere in the file cannot satisfy it",
2892
+ );
2893
+ });
2894
+
2895
+ test("the euid-0 guard does not fire on a normal run, and the modes it guards really deny (#184, #660)", (t) => {
2896
+ // Mirrors release-ticket.test.mjs's own pin for the same class. The 8
2897
+ // `if (EUID0) return t.skip(NO_DENIAL)` guards above are by construction
2898
+ // unreachable wherever this suite actually runs, so a green suite says
2899
+ // nothing about them — an inverted comparison would turn all 8 into skips
2900
+ // with nothing failing, indistinguishable in the summary from that many
2901
+ // tests passing (measured: flipping `=== 0` to `!== 0` drops this file from
2902
+ // 91 pass/0 skip to 83 pass/8 skip while the suite still exits 0). What a
2903
+ // green suite CAN say is the half that matters: that the guard reads false
2904
+ // here, and that the modes it guards really deny when it does.
2905
+ if (process.geteuid?.() === 0) return t.skip(NO_DENIAL);
2906
+ assert.equal(EUID0, false, "a guard that fires here voids every permission fixture in this file, silently");
2907
+
2908
+ const dir = mkdtempSync(join(tmpdir(), "inflight-euid-"));
2909
+ t.after(() => {
2910
+ chmodSync(dir, 0o755);
2911
+ rmSync(dir, { recursive: true, force: true });
2912
+ });
2913
+ writeFileSync(join(dir, "f"), "x");
2914
+ const read = () => readFileSync(join(dir, "f"), "utf8");
2915
+
2916
+ // 0o000 and 0o400 are the two modes the refs/heads, .git/worktrees and
2917
+ // registry-entry fixtures above chmod a DIRECTORY to. Both drop the search
2918
+ // bit — 0o000 is the realistic fault the issues measured, 0o400 is what
2919
+ // tells a fixed guard's `&&` from an `||` — and opening a file inside the
2920
+ // directory needs that bit regardless of the directory's own read bit.
2921
+ for (const mode of [0o000, 0o400]) {
2922
+ const at = `mode 0o${mode.toString(8).padStart(3, "0")}`;
2923
+ chmodSync(dir, mode);
2924
+ assert.throws(read, { code: "EACCES" }, `the search must be denied, ${at}`);
2925
+ }
2926
+
2927
+ // The `gitdir`-file fixture instead chmods a FILE 0o000 while its parent
2928
+ // stays searchable — a different precondition, pinned separately.
2929
+ chmodSync(dir, 0o755);
2930
+ chmodSync(join(dir, "f"), 0o000);
2931
+ assert.throws(read, { code: "EACCES" }, "an 0o000 FILE must deny its own read");
2932
+ });
2933
+
2934
+ // --- #1020: the ambient GIT_DIR probe 3 cannot see past.
2935
+ //
2936
+ // One case, not two, and that is a measurement rather than an omission.
2937
+ // GIT_WORK_TREE is unset by the script alongside GIT_DIR, but it is INERT
2938
+ // here: probe 3's calls read refs (`for-each-ref`, `ls-remote`) and the admin
2939
+ // directory (`worktree list`, `--git-common-dir`), never a work tree, so
2940
+ // three targets — the checkout root, a second clone, a plain directory — all
2941
+ // produce byte-identical output. A fixture for that half could only be
2942
+ // vacuous, which is precisely the shape PR #1015 warned about; the line's
2943
+ // GIT_WORK_TREE half is pinned as source by ambient-git-vars-prose.test.mjs
2944
+ // instead.
2945
+ //
2946
+ // `fixture()` deletes both variables for every case in this file, and has
2947
+ // since long before this ticket — a defence that protected the SUITE while
2948
+ // every real caller stayed exposed. This case opts back in, deliberately, to
2949
+ // reach the path that scrub makes unreachable.
2950
+ test("an ambient GIT_DIR does not ask another repository whether the ticket is taken (#1020)", (t) => {
2951
+ // Probe 3 alone answers here — no linked PR, no remote branch — so the
2952
+ // verdict IS probe 3's answer and a retarget flips `taken` outright. The
2953
+ // control for this shape is the pair of worktree cases above, which assert
2954
+ // the same `hits: ["local"]` without any ambient variable.
2955
+ const here = fixture(t, 77, { detachedWorktreeUnder: "nospace" });
2956
+ const elsewhere = fixture(t, 77, {});
2957
+
2958
+ // The fixture's own positive control: if the other repository happened to
2959
+ // carry a worktree for #77 too, looking in the wrong place would give the
2960
+ // right answer and this case would pass while pinning nothing.
2961
+ assert.doesNotMatch(
2962
+ execFileSync("git", ["-C", elsewhere.repo, "worktree", "list"], { encoding: "utf8" }),
2963
+ /77/,
2964
+ "fixture: the other repository must hold nothing for #77",
2965
+ );
2966
+
2967
+ const r = spawnSync("sh", [SCRIPT, "77"], {
2968
+ cwd: here.repo,
2969
+ env: { ...here.env, GIT_DIR: join(elsewhere.repo, ".git") },
2970
+ encoding: "utf8",
2971
+ });
2972
+ const json = r.stdout.trim() ? JSON.parse(r.stdout) : null;
2973
+
2974
+ // Exit code first, with the payload as the message: pre-fix this run exits 0
2975
+ // with a `taken: false` receipt, so leading with a `json.hits` assertion
2976
+ // would report the absence of an array element rather than the verdict that
2977
+ // is actually wrong.
2978
+ assert.equal(r.status, 1,
2979
+ `an ambient GIT_DIR must not make a claimed ticket read as free — that is the double-claim phase 0 runs this probe to prevent; got ${r.stdout}${r.stderr}`);
2980
+ assert.equal(json.taken, true);
2981
+ assert.deepEqual(json.hits, ["local"]);
2982
+ assert.match(json.evidence.worktree, /nospace\/fix-77-slug$/,
2983
+ "and the evidence must name this checkout's worktree, not the environment's repository");
2984
+ });