@feigi/fleet-ctl 3.23.36 → 3.23.38

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