@feigi/fleet-ctl 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/.claude-plugin/plugin.json +9 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/agents/fleet-finisher.agent.md +7 -0
  5. package/agents/fleet-implementer-alt.agent.md +210 -0
  6. package/agents/fleet-implementer.agent.md +210 -0
  7. package/agents/fleet-merge-bot.agent.md +7 -0
  8. package/agents/fleet-review-comments.agent.md +40 -0
  9. package/agents/fleet-review-correctness.agent.md +43 -0
  10. package/agents/fleet-review-runner.agent.md +73 -0
  11. package/agents/fleet-review-silent-failure.agent.md +49 -0
  12. package/agents/fleet-review-simplify.agent.md +46 -0
  13. package/agents/fleet-review-snapshot.agent.md +24 -0
  14. package/agents/fleet-review-tests.agent.md +46 -0
  15. package/agents/fleet-review-types.agent.md +41 -0
  16. package/agents/fleet-review-verifier.agent.md +29 -0
  17. package/commands/review-and-fix.md +98 -0
  18. package/commands/run-merge-bot.md +357 -0
  19. package/commands/run-team-help.md +17 -0
  20. package/package.json +23 -0
  21. package/scripts/agent-test-dir-prose.test.mjs +59 -0
  22. package/scripts/agent-test.test.mjs +1636 -0
  23. package/scripts/ambient-git-vars-mjs-prose.test.mjs +354 -0
  24. package/scripts/ambient-git-vars-prose.test.mjs +192 -0
  25. package/scripts/ancestry-check-position-prose.test.mjs +175 -0
  26. package/scripts/apply-ruleset.test.mjs +420 -0
  27. package/scripts/arg-header-probes-prose.test.mjs +393 -0
  28. package/scripts/arg.mjs +600 -0
  29. package/scripts/arg.test.mjs +1354 -0
  30. package/scripts/board-cli.test.mjs +694 -0
  31. package/scripts/board-identity.test.mjs +429 -0
  32. package/scripts/board-liveness-banner.test.mjs +119 -0
  33. package/scripts/board-prev-shape.test.mjs +229 -0
  34. package/scripts/board-tryparse-null.test.mjs +119 -0
  35. package/scripts/board.html +471 -0
  36. package/scripts/board.mjs +2037 -0
  37. package/scripts/board.test.mjs +3086 -0
  38. package/scripts/brief-after-cut-prose.test.mjs +53 -0
  39. package/scripts/candidates-exit3-prose.test.mjs +302 -0
  40. package/scripts/candidates.mjs +674 -0
  41. package/scripts/candidates.test.mjs +2101 -0
  42. package/scripts/caveat-unification-prose.test.mjs +98 -0
  43. package/scripts/ci-comment-rot-prose.test.mjs +2025 -0
  44. package/scripts/ci-completes-premise-prose.test.mjs +257 -0
  45. package/scripts/ci-state-prose.test.mjs +113 -0
  46. package/scripts/ci-state.mjs +761 -0
  47. package/scripts/ci-state.test.mjs +1640 -0
  48. package/scripts/ci-vacuous-green.test.mjs +368 -0
  49. package/scripts/citation-sweep-prose.test.mjs +1572 -0
  50. package/scripts/claim-lifecycle.test.mjs +185 -0
  51. package/scripts/claim-ticket.sh +417 -0
  52. package/scripts/claim-ticket.test.mjs +1121 -0
  53. package/scripts/closing-keyword-prose.test.mjs +193 -0
  54. package/scripts/cockpit-launch-idempotent-prose.test.mjs +165 -0
  55. package/scripts/cockpit-tick-nonblocking.test.mjs +210 -0
  56. package/scripts/compute-board.mjs +579 -0
  57. package/scripts/compute-board.test.mjs +1060 -0
  58. package/scripts/compute-spend.mjs +329 -0
  59. package/scripts/compute-spend.test.mjs +451 -0
  60. package/scripts/cross-repo-citation-prose.test.mjs +156 -0
  61. package/scripts/cwd-isolation-pins.mjs +83 -0
  62. package/scripts/dedupe-guard-prose.test.mjs +243 -0
  63. package/scripts/derive-testcmd.sh +239 -0
  64. package/scripts/derive-testcmd.test.mjs +380 -0
  65. package/scripts/diff-stats.mjs +231 -0
  66. package/scripts/diff-stats.test.mjs +408 -0
  67. package/scripts/dispatch-block-golden-prose.test.mjs +1024 -0
  68. package/scripts/dispatch-block-pins-prose.test.mjs +615 -0
  69. package/scripts/drop-merged-label.sh +173 -0
  70. package/scripts/drop-merged-label.test.mjs +480 -0
  71. package/scripts/expected-jobs-prose.test.mjs +80 -0
  72. package/scripts/filing-bar-seat-prose.test.mjs +242 -0
  73. package/scripts/filing-claim-bar-prose.test.mjs +166 -0
  74. package/scripts/finisher-dispatch-premise-prose.test.mjs +312 -0
  75. package/scripts/finisher-halt-prose.test.mjs +106 -0
  76. package/scripts/finisher-name-prose.test.mjs +134 -0
  77. package/scripts/finisher-own-tree-prose.test.mjs +285 -0
  78. package/scripts/finisher-pin-race-prose.test.mjs +339 -0
  79. package/scripts/fix-applier-correction-rules-prose.test.mjs +201 -0
  80. package/scripts/fix-applier-result-file-prose.test.mjs +100 -0
  81. package/scripts/fleet-bootstrap +155 -0
  82. package/scripts/fleet-heartbeat.mjs +272 -0
  83. package/scripts/fleet-heartbeat.test.mjs +450 -0
  84. package/scripts/fleet-provenance +207 -0
  85. package/scripts/fleet-provenance.test.mjs +64 -0
  86. package/scripts/fleet-run +148 -0
  87. package/scripts/fleet-run.test.mjs +90 -0
  88. package/scripts/fleet-state.mjs +400 -0
  89. package/scripts/fleet-state.test.mjs +373 -0
  90. package/scripts/fleet-tick-prose.test.mjs +299 -0
  91. package/scripts/fleet-tick.mjs +832 -0
  92. package/scripts/fleet-tick.test.mjs +1332 -0
  93. package/scripts/force-with-lease-reason-prose.test.mjs +184 -0
  94. package/scripts/frontmatter-allowlist.json +64 -0
  95. package/scripts/frontmatter-check.mjs +256 -0
  96. package/scripts/frontmatter-check.test.mjs +436 -0
  97. package/scripts/git-env.mjs +124 -0
  98. package/scripts/git-env.test.mjs +149 -0
  99. package/scripts/git-status-untracked-mode-sweep.test.mjs +216 -0
  100. package/scripts/gone-walk.test.mjs +213 -0
  101. package/scripts/gp-sep-invariant-prose.test.mjs +188 -0
  102. package/scripts/head-moved-after-label-prose.test.mjs +233 -0
  103. package/scripts/immutable-body-claim-prose.test.mjs +413 -0
  104. package/scripts/implementer-model-tier.test.mjs +643 -0
  105. package/scripts/inflight-citation-prose.test.mjs +144 -0
  106. package/scripts/inflight-exit2-prose.test.mjs +81 -0
  107. package/scripts/inflight-probe-guard-prose.test.mjs +109 -0
  108. package/scripts/inflight-scan-scope-prose.test.mjs +57 -0
  109. package/scripts/inflight.sh +1106 -0
  110. package/scripts/inflight.test.mjs +2984 -0
  111. package/scripts/injection-control-prose.test.mjs +404 -0
  112. package/scripts/install-root-audit.test.mjs +464 -0
  113. package/scripts/instrument-check-prose.test.mjs +235 -0
  114. package/scripts/instruments.sh +394 -0
  115. package/scripts/instruments.test.mjs +787 -0
  116. package/scripts/issue-tracker-prose.test.mjs +71 -0
  117. package/scripts/json.sh +248 -0
  118. package/scripts/json.test.mjs +364 -0
  119. package/scripts/ledger-dispatch.test.mjs +516 -0
  120. package/scripts/ledger-grammar.mjs +85 -0
  121. package/scripts/ledger-grammar.test.mjs +142 -0
  122. package/scripts/ledger-read-require-file.test.mjs +197 -0
  123. package/scripts/ledger.mjs +1753 -0
  124. package/scripts/ledger.test.mjs +3554 -0
  125. package/scripts/line-distance-prose.test.mjs +245 -0
  126. package/scripts/liveness-rationale-prose.test.mjs +83 -0
  127. package/scripts/locale-pin-prose.test.mjs +189 -0
  128. package/scripts/member-outcome-prose.test.mjs +167 -0
  129. package/scripts/member-outcomes-header.test.mjs +148 -0
  130. package/scripts/member-outcomes-prose.test.mjs +63 -0
  131. package/scripts/member-outcomes.mjs +231 -0
  132. package/scripts/member-outcomes.test.mjs +507 -0
  133. package/scripts/member-prompt-prose.test.mjs +161 -0
  134. package/scripts/member-record.mjs +605 -0
  135. package/scripts/member-record.test.mjs +516 -0
  136. package/scripts/member-write-guard.mjs +279 -0
  137. package/scripts/member-write-guard.test.mjs +211 -0
  138. package/scripts/merge-commit-probe-prose.test.mjs +122 -0
  139. package/scripts/merge-gate.mjs +262 -0
  140. package/scripts/merge-gate.test.mjs +613 -0
  141. package/scripts/muted-git-guard-sweep.test.mjs +493 -0
  142. package/scripts/net-ssh-precedence-prose.test.mjs +91 -0
  143. package/scripts/net-watchdog-prose.test.mjs +79 -0
  144. package/scripts/net.sh +409 -0
  145. package/scripts/net.test.mjs +211 -0
  146. package/scripts/no-ci-gate-prose.test.mjs +108 -0
  147. package/scripts/no-undo-audit.sh +1134 -0
  148. package/scripts/no-undo-audit.test.mjs +3965 -0
  149. package/scripts/no-wave.test.mjs +138 -0
  150. package/scripts/node-floor-sweep.test.mjs +611 -0
  151. package/scripts/pointer-target-prose.test.mjs +186 -0
  152. package/scripts/pr-overlap.mjs +417 -0
  153. package/scripts/pr-overlap.test.mjs +695 -0
  154. package/scripts/printf-die-sweep.test.mjs +384 -0
  155. package/scripts/prompt-renderer.mjs +39 -0
  156. package/scripts/prompt-renderer.test.mjs +68 -0
  157. package/scripts/prose-pin.mjs +808 -0
  158. package/scripts/prose-pin.test.mjs +1034 -0
  159. package/scripts/prove-merge.sh +228 -0
  160. package/scripts/prove-merge.test.mjs +995 -0
  161. package/scripts/pull-table-relabel-prose.test.mjs +60 -0
  162. package/scripts/quiet-payload-prose.test.mjs +222 -0
  163. package/scripts/reap.sh +1768 -0
  164. package/scripts/reap.test.mjs +4395 -0
  165. package/scripts/reaping-prose.test.mjs +159 -0
  166. package/scripts/refuter-scratch-prose.test.mjs +135 -0
  167. package/scripts/release-label-required-prose.test.mjs +71 -0
  168. package/scripts/release-label-split-prose.test.mjs +169 -0
  169. package/scripts/release-ticket.sh +1716 -0
  170. package/scripts/release-ticket.test.mjs +5106 -0
  171. package/scripts/renovate-release-contract.test.mjs +379 -0
  172. package/scripts/repo-root.mjs +544 -0
  173. package/scripts/repo-root.test.mjs +873 -0
  174. package/scripts/reporter-output-rule-prose.test.mjs +208 -0
  175. package/scripts/review-agent-report-only.test.mjs +49 -0
  176. package/scripts/review-core-cwd-isolation.test.mjs +374 -0
  177. package/scripts/review-core-reads.test.mjs +478 -0
  178. package/scripts/review-core-refuter-scratch.test.mjs +148 -0
  179. package/scripts/review-core-snapshot-path.test.mjs +777 -0
  180. package/scripts/review-core-specialist-scratch.test.mjs +189 -0
  181. package/scripts/review-core-testcmd.test.mjs +288 -0
  182. package/scripts/review-core-unrun.test.mjs +530 -0
  183. package/scripts/review-core-unverified-discriminant.test.mjs +208 -0
  184. package/scripts/review-core.mjs +1028 -0
  185. package/scripts/review-eval-resolver-path.test.mjs +55 -0
  186. package/scripts/review-eval.mjs +197 -0
  187. package/scripts/review-host-fixture.mjs +73 -0
  188. package/scripts/review-in-run-retry.test.mjs +187 -0
  189. package/scripts/review-no-vendor-dispatch.test.mjs +45 -0
  190. package/scripts/review-path-default.test.mjs +796 -0
  191. package/scripts/review-runner-spawns.test.mjs +93 -0
  192. package/scripts/review-runner.test.mjs +155 -0
  193. package/scripts/review-tier-audit.test.mjs +140 -0
  194. package/scripts/run-artifact-pr-prose.test.mjs +341 -0
  195. package/scripts/run-merge-bot-prose.test.mjs +1391 -0
  196. package/scripts/scratch-partition-invariant-prose.test.mjs +74 -0
  197. package/scripts/scripts-path-citation-sweep.test.mjs +73 -0
  198. package/scripts/section-between-guard-prose.test.mjs +378 -0
  199. package/scripts/select-dimensions.test.mjs +674 -0
  200. package/scripts/shared-refusal.test.mjs +388 -0
  201. package/scripts/shell-traps-prose.test.mjs +507 -0
  202. package/scripts/shortlist.mjs +355 -0
  203. package/scripts/shortlist.test.mjs +366 -0
  204. package/scripts/slow-transport.mjs +72 -0
  205. package/scripts/snapshot-repo.test.mjs +772 -0
  206. package/scripts/snapshot-runner-audience-prose.test.mjs +129 -0
  207. package/scripts/spend-view.test.mjs +312 -0
  208. package/scripts/staleness-qualifier-prose.test.mjs +251 -0
  209. package/scripts/staleness-verdict-prose.test.mjs +142 -0
  210. package/scripts/staleness.mjs +414 -0
  211. package/scripts/staleness.test.mjs +893 -0
  212. package/scripts/stalled-member-liveness-prose.test.mjs +219 -0
  213. package/scripts/stash-prohibition-prose.test.mjs +313 -0
  214. package/scripts/strip-comments.mjs +44 -0
  215. package/scripts/tier-check.mjs +468 -0
  216. package/scripts/tier-check.test.mjs +726 -0
  217. package/scripts/tier-guard-gate-prose.test.mjs +216 -0
  218. package/scripts/tier-outcomes-header.test.mjs +586 -0
  219. package/scripts/tier-outcomes.mjs +441 -0
  220. package/scripts/tier-outcomes.test.mjs +342 -0
  221. package/scripts/tier-roles.mjs +250 -0
  222. package/scripts/tier-roles.test.mjs +316 -0
  223. package/scripts/tracker-block-copy-prose.test.mjs +288 -0
  224. package/scripts/triage-labels-gloss-prose.test.mjs +97 -0
  225. package/scripts/unattended-git-sweep.test.mjs +142 -0
  226. package/scripts/verify-sha-exit2-prose.test.mjs +269 -0
  227. package/scripts/verify-sha.sh +117 -0
  228. package/scripts/verify-sha.test.mjs +693 -0
  229. package/scripts/watcher-degraded-block.test.mjs +372 -0
  230. package/scripts/watcher-key-prose.test.mjs +106 -0
  231. package/scripts/within-run-pair-prose.test.mjs +208 -0
  232. package/scripts/worktree-audit.sh +482 -0
  233. package/scripts/worktree-audit.test.mjs +1407 -0
  234. package/scripts/worktree-head-prose.test.mjs +276 -0
  235. package/scripts/worktree-listing-sweep.test.mjs +217 -0
  236. package/scripts/worktree-model-prose.test.mjs +216 -0
  237. package/scripts/worktree.sh +470 -0
  238. package/skills/next-ticket/SKILL.md +138 -0
  239. package/skills/run-team/SKILL.md +3603 -0
  240. package/skills/run-team/references/ci-and-staleness.md +75 -0
  241. package/skills/run-team/references/correction-tickets.md +37 -0
  242. package/skills/run-team/references/isolation.md +23 -0
  243. package/skills/run-team/references/member-lifecycle.md +73 -0
  244. package/skills/run-team/references/reaping.md +73 -0
  245. package/skills/sizing-a-ticket/SKILL.md +39 -0
@@ -0,0 +1,4395 @@
1
+ // Regression gate for reap.sh, the merge probe that authorizes deleting a
2
+ // [gone] branch. Zero deps: `node --test plugin/scripts/reap.test.mjs`.
3
+ //
4
+ // The load-bearing case is the failed-probe one: a `git cherry` that dies
5
+ // (issue #264) must KEEP the branch, never reap it. `cmd | grep -q` takes
6
+ // grep's exit status, never cmd's, so a dead cherry read as "nothing
7
+ // unmerged" and `--apply` force-deleted a branch whose commits existed
8
+ // nowhere else, at exit 0. The two control cases pin the other direction —
9
+ // a fix that keeps everything is as broken as one that deletes everything.
10
+
11
+ import { test } from "node:test";
12
+ import assert from "node:assert/strict";
13
+ import { execFileSync, spawnSync } from "node:child_process";
14
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { slowTransport, SSH_URL } from "./slow-transport.mjs";
19
+
20
+ const SCRIPT = fileURLToPath(new URL("./reap.sh", import.meta.url));
21
+
22
+ // Pin identity and cut the developer's ~/.gitconfig out of the fixture, so a
23
+ // local `pull.rebase` or hook cannot change what these repos look like.
24
+ const ENV = {
25
+ ...process.env,
26
+ // reap.sh reads BASE_REF and defaults to origin/main; the fleet harness is
27
+ // exactly the caller that would have it set, and inheriting it here would
28
+ // point every fixture at local `main` instead.
29
+ BASE_REF: undefined,
30
+ GIT_DIR: undefined,
31
+ GIT_WORK_TREE: undefined,
32
+ GIT_TEMPLATE_DIR: undefined,
33
+ GIT_INDEX_FILE: undefined,
34
+ GIT_AUTHOR_NAME: "t",
35
+ GIT_AUTHOR_EMAIL: "t@example.com",
36
+ GIT_COMMITTER_NAME: "t",
37
+ GIT_COMMITTER_EMAIL: "t@example.com",
38
+ GIT_CONFIG_GLOBAL: "/dev/null",
39
+ GIT_CONFIG_SYSTEM: "/dev/null",
40
+ };
41
+
42
+ const git = (cwd, ...args) =>
43
+ execFileSync("git", args, { cwd, env: ENV, encoding: "utf8" }).trim();
44
+
45
+ // Absolute path to the real git, for any test that shadows `git` on PATH.
46
+ const REAL_GIT = execFileSync("sh", ["-c", "command -v git"], { encoding: "utf8" }).trim();
47
+
48
+ // Absolute paths to the real `awk`, `paste` and `grep`, for the sites this
49
+ // file's own fault-injection fixtures shadow on PATH — the same reason
50
+ // REAL_GIT exists above. `grep` joined them for #1419: it is the last tool in
51
+ // both merged-commit checks and both registry re-reads, and the only one whose
52
+ // own failure used to read as a clean verdict about what it had not scanned.
53
+ const REAL_AWK = execFileSync("sh", ["-c", "command -v awk"], { encoding: "utf8" }).trim();
54
+ const REAL_PASTE = execFileSync("sh", ["-c", "command -v paste"], { encoding: "utf8" }).trim();
55
+ const REAL_GREP = execFileSync("sh", ["-c", "command -v grep"], { encoding: "utf8" }).trim();
56
+
57
+ /** Empty commit on the current branch; returns its sha. */
58
+ const commit = (w, msg) => {
59
+ git(w, "commit", "-q", "--allow-empty", "-m", msg);
60
+ return git(w, "rev-parse", "HEAD");
61
+ };
62
+
63
+ /** Bare origin + working clone with one commit on main. Returns the clone dir. */
64
+ function repo(t, dir = "w") {
65
+ // realpathSync: macOS resolves /var through /private, so a path built from
66
+ // the raw mkdtemp result would never string-equal what git itself reports
67
+ // in `worktree list --porcelain` (git canonicalises). Resolved once here,
68
+ // before any worktree path is derived from it.
69
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "reap-")));
70
+ t.after(() => rmSync(root, { recursive: true, force: true }));
71
+ const origin = join(root, "origin.git");
72
+ const w = join(root, dir);
73
+ execFileSync("git", ["-c", "init.defaultBranch=main", "init", "-q", "--bare", origin], { env: ENV });
74
+ execFileSync("git", ["clone", "-q", origin, w], { env: ENV });
75
+ commit(w, "root");
76
+ git(w, "branch", "-M", "main");
77
+ git(w, "push", "-q", "-u", "origin", "main");
78
+ return w;
79
+ }
80
+
81
+ /**
82
+ * Like `mergedGoneBranch`, but the commit lands in a LINKED worktree under
83
+ * `.worktrees/` instead of the main checkout — reap.sh's worktree-removal
84
+ * path had no fixture at all before this file (a dry run and `--apply` could
85
+ * each mispredict the other and nothing here would notice). Returns the
86
+ * worktree's absolute path.
87
+ *
88
+ * `wt` overrides that home. reap.sh exempts `.worktrees/` from the
89
+ * `--ignored` keep, so a test that exercises that keep has to put its
90
+ * worktree somewhere else and pass the path in.
91
+ */
92
+ function mergedGoneBranchWithWorktree(w, name, msg, wt = join(w, ".worktrees", name)) {
93
+ git(w, "worktree", "add", "-q", wt, "-b", name, "main");
94
+ commit(wt, msg);
95
+ git(wt, "push", "-q", "-u", "origin", name);
96
+ git(w, "merge", "-q", "--no-ff", "-m", `merge ${name}`, name);
97
+ git(w, "push", "-q", "origin", "main");
98
+ git(w, "push", "-q", "origin", "--delete", name);
99
+ git(w, "fetch", "-q", "--prune", "origin");
100
+ return wt;
101
+ }
102
+
103
+ /**
104
+ * Re-point the registration for `wt` at `dest` and take the real directory away.
105
+ *
106
+ * `git worktree list --porcelain` derives the worktree path from the entry's
107
+ * `gitdir` file, so rewriting that file is how a fixture gets git to name a
108
+ * path whose FIRST component under `/` does not exist — the one shape
109
+ * `git worktree add` cannot produce, since it has to create the directory. In
110
+ * production this is the hand-added worktree outside the checkout whose
111
+ * ancestor chain was removed (`git worktree add /scratch/wt`, then
112
+ * `rm -rf /scratch`). The registry entry itself survives, so any
113
+ * listed-vs-registered count stays balanced.
114
+ */
115
+ /**
116
+ * The `<git-common-dir>/worktrees/<id>` directory git keeps `$wt`'s admin
117
+ * files in — its `gitdir` pointer, its `HEAD`, and the sequencer state of any
118
+ * operation running inside it.
119
+ *
120
+ * Found by reading the `gitdir` pointers rather than by guessing the id from
121
+ * the directory name: git derives that id from the basename and disambiguates
122
+ * collisions, so a fixture that spelled it by hand would silently address the
123
+ * wrong entry the first time two worktrees shared a basename.
124
+ */
125
+ function adminEntry(w, wt) {
126
+ const admin = join(w, ".git", "worktrees");
127
+ // realpathSync: git canonicalises what it writes into `gitdir`, and on macOS
128
+ // a tmpdir path reaches this suite as /var/... while git recorded
129
+ // /private/var/... — the scan matches nothing without resolving first.
130
+ const target = join(realpathSync(wt), ".git");
131
+ const name = readdirSync(admin).find(
132
+ (n) => readFileSync(join(admin, n, "gitdir"), "utf8").trim() === target,
133
+ );
134
+ assert.ok(name, `fixture: no registry entry points at ${wt}`);
135
+ return join(admin, name);
136
+ }
137
+
138
+ // `latin1`, not the default utf8: `dest` may carry a byte above 127 as its own
139
+ // code unit (a #614 fixture's registry path, e.g. `bÿad`), and utf8 would
140
+ // re-encode that to two bytes instead of writing the one the fixture means.
141
+ // No behaviour change for an ASCII `dest` — latin1 and utf8 agree below 128.
142
+ function relocate(w, wt, dest) {
143
+ writeFileSync(join(adminEntry(w, wt), "gitdir"), Buffer.from(`${dest}/.git\n`, "latin1"));
144
+ rmSync(wt, { recursive: true, force: true });
145
+ return dest;
146
+ }
147
+
148
+ /**
149
+ * Branch `name` off main, merged back into main with a real merge commit,
150
+ * then given an upstream and dropped on the remote so `%(upstream:track)`
151
+ * reads `[gone]` — the exact state reap.sh's for-each-ref filter selects.
152
+ * git cherry sees no unique commits: the merge already carries them.
153
+ */
154
+ function mergedGoneBranch(w, name, msg) {
155
+ git(w, "checkout", "-q", "-b", name, "main");
156
+ commit(w, msg);
157
+ git(w, "push", "-q", "-u", "origin", name);
158
+ git(w, "checkout", "-q", "main");
159
+ git(w, "merge", "-q", "--no-ff", "-m", `merge ${name}`, name);
160
+ git(w, "push", "-q", "origin", "main");
161
+ git(w, "push", "-q", "origin", "--delete", name);
162
+ git(w, "fetch", "-q", "--prune", "origin");
163
+ }
164
+
165
+ /**
166
+ * Branch `name` off main with one commit, never merged, given an upstream
167
+ * and then dropped on the remote — `[gone]`, but its commit exists nowhere
168
+ * else. Returns the commit's sha.
169
+ */
170
+ function unmergedGoneBranch(w, name, msg) {
171
+ git(w, "checkout", "-q", "-b", name, "main");
172
+ const sha = commit(w, msg);
173
+ git(w, "push", "-q", "-u", "origin", name);
174
+ git(w, "checkout", "-q", "main");
175
+ git(w, "push", "-q", "origin", "--delete", name);
176
+ git(w, "fetch", "-q", "--prune", "origin");
177
+ return sha;
178
+ }
179
+
180
+ /**
181
+ * Shell leaving proof, beside the shim itself, that the injected fault fired.
182
+ *
183
+ * A fixture whose verdict is the SAME with and without the fault — every
184
+ * "noise on stderr must not change this negative verdict" arm in this file —
185
+ * stays green when the shim never runs at all: a PATH order slip, or a match
186
+ * that drifted off its argv slot the way #730's did. The arm then pins
187
+ * nothing, and nothing in it can say so. Spliced into `failOnlyShim`'s body
188
+ * automatically; a fall-through `match` (one ending in `false`, so the real
189
+ * git still answers) has to splice it in by hand — no body ever runs. #759
190
+ *
191
+ * Records `$*`, not just presence: `reap.sh` calls `git cherry $base $target`
192
+ * from two sweeps with the same `match`, so a bare touch is satisfied by
193
+ * EITHER sweep's probe — an arm testing one sweep's own cherry call reads as
194
+ * pinned when only the other sweep's ever fired. `assertShimFired`'s `expect`
195
+ * regex matches this file's contents to require the argv this arm names.
196
+ */
197
+ const SHIM_FIRED = `printf '%s\\n' "$*" >> "$0.fired"`;
198
+
199
+ /**
200
+ * Asserts the fault `failOnlyShim` injects actually reached the script under
201
+ * test — and, with `expect`, that it reached THIS call's own argv rather than
202
+ * a same-named git call elsewhere in the run. Delegates to
203
+ * `assertToolShimFired`, fixed to the `git` tool.
204
+ */
205
+ function assertShimFired(bin, why, expect) {
206
+ return assertToolShimFired(bin, "git", why, expect);
207
+ }
208
+
209
+ /**
210
+ * A PATH `git` that fails only the subcommand `match` names; everything else
211
+ * is real. A `toolFailShim` fixed to the `git` tool and `REAL_GIT`.
212
+ */
213
+ function failOnlyShim(t, match, stderr, code = 1) {
214
+ return toolFailShim(t, "git", REAL_GIT, match, stderr, code);
215
+ }
216
+
217
+ /**
218
+ * A PATH `<tool>` (awk or paste, for #789's four fault-injection fixtures)
219
+ * that fails only when `match` — a shell test against its own argv — holds;
220
+ * every other invocation execs the real one. `realTool` must be the absolute
221
+ * path `command -v <tool>` resolved, so the fall-through never re-enters this
222
+ * same shimmed PATH.
223
+ */
224
+ function toolFailShim(t, tool, realTool, match, stderr, code = 1) {
225
+ const bin = mkdtempSync(join(tmpdir(), `reap-${tool}-shim-`));
226
+ t.after(() => rmSync(bin, { recursive: true, force: true }));
227
+ writeFileSync(
228
+ join(bin, tool),
229
+ `#!/bin/sh\n` +
230
+ `if ${match}; then\n` +
231
+ ` ${SHIM_FIRED}\n` +
232
+ // Shell-quoted, not `JSON.stringify`: that escapes for JSON, but the
233
+ // splice lands in shell, where a `$` in a fixture line would expand
234
+ // instead of reaching git's stderr as data.
235
+ stderr.map((l) => ` printf '%s\\n' '${l.replace(/'/g, `'\\''`)}' >&2\n`).join("") +
236
+ ` exit ${code}\n` +
237
+ `fi\n` +
238
+ `exec ${realTool} "$@"\n`,
239
+ { mode: 0o755 },
240
+ );
241
+ return bin;
242
+ }
243
+
244
+ /**
245
+ * Asserts the fault `toolFailShim(t, tool, …)` injects actually reached the
246
+ * script under test, and — with `expect` — that it reached THIS call's own
247
+ * argv rather than a same-named call elsewhere in the run.
248
+ */
249
+ function assertToolShimFired(bin, tool, why, expect) {
250
+ const path = join(bin, `${tool}.fired`);
251
+ assert.equal(existsSync(path), true, why);
252
+ if (expect) assert.match(readFileSync(path, "utf8"), expect, why);
253
+ }
254
+
255
+ /**
256
+ * A PATH dir whose `git` fails only `cherry`, matching the ticket's real repro:
257
+ * multi-line stderr, exit 128 (one unreadable loose object suffices in the
258
+ * wild). Everything else execs the real git, unshimmed.
259
+ */
260
+ function cherryShim(t) {
261
+ return failOnlyShim(
262
+ t,
263
+ `[ "$1" = cherry ]`,
264
+ ["error: unable to open loose object deadbeefcafe: Permission denied", "fatal: revision walk setup failed"],
265
+ 128,
266
+ );
267
+ }
268
+
269
+ /**
270
+ * A PATH dir whose `git worktree list` fails on exactly the Nth call this
271
+ * shim sees (`cmp` is the shell comparison against that count, e.g. `-eq 2`
272
+ * or `-ge 2`); every other call, and every other subcommand, execs the real
273
+ * git. Built once per counted `git worktree list` fault-injection site so the
274
+ * counter's own tmpdir is not duplicated at each call.
275
+ */
276
+ function worktreeListFailsOnCall(t, cmp) {
277
+ const countDir = mkdtempSync(join(tmpdir(), "reap-count-"));
278
+ t.after(() => rmSync(countDir, { recursive: true, force: true }));
279
+ const counter = join(countDir, "n");
280
+ const bin = failOnlyShim(
281
+ t,
282
+ `[ "$1" = worktree ] && [ "$2" = list ] && ` +
283
+ `{ n=$(( $(cat "${counter}" 2>/dev/null || echo 0) + 1 )); printf '%s' "$n" > "${counter}"; [ "$n" ${cmp} ]; }`,
284
+ ["fatal: worktree list exploded"],
285
+ 128,
286
+ );
287
+ return { bin, counter };
288
+ }
289
+
290
+ /**
291
+ * A `failOnlyShim` match selecting the `--ignored` probe and nothing else.
292
+ *
293
+ * Selected on CONTENT, never on argv POSITION. It was `[ "$5" = --ignored ]`,
294
+ * which #730 broke by inserting `-uall` ahead of the flag: two of the three
295
+ * tests using it went red, and the third — the one asserting a REAP — went
296
+ * green vacuously, its shim silently matching nothing while the assertions it
297
+ * makes about a probe that never ran still held. A positional match is a
298
+ * false-green generator the next flag re-arms, so the position is gone.
299
+ *
300
+ * `$3` stays positional deliberately: it is `git -C <wt> status …`, the
301
+ * subcommand slot, and pinning it is what keeps this shim off the OTHER git
302
+ * calls in the sweep.
303
+ */
304
+ const IGNORED_PROBE = `[ "$3" = status ] && case " $* " in *" --ignored "*) : ;; *) false ;; esac`;
305
+
306
+ /**
307
+ * A `failOnlyShim` match selecting the PLAIN status probe (`git -C <wt>
308
+ * status --porcelain …`, no `--ignored`) and nothing else.
309
+ *
310
+ * Positional on `$4`, deliberately, not content-based like `IGNORED_PROBE`'s
311
+ * `case`: a content match for `--porcelain` alone would also catch the
312
+ * `--ignored` probe, which carries that flag too — the two have to stay
313
+ * distinguishable, not accidentally merged into one shim.
314
+ */
315
+ const STATUS_PROBE = `[ "$3" = status ] && [ "$4" = --porcelain ]`;
316
+
317
+ /**
318
+ * `timeout` is a wall-clock ceiling for the bounded-fetch pair at the end of
319
+ * this file and nothing else: those two runs are the only ones whose transport
320
+ * can hang, and without a ceiling a watchdog that never fired would hang the
321
+ * suite instead of failing the case. `error` is returned for the same pair — a
322
+ * run killed by that ceiling has a null status, which would otherwise read as
323
+ * a verdict rather than as a test that never got an answer.
324
+ */
325
+ function runReap(cwd, args, envOverrides = {}, timeout = undefined) {
326
+ const r = spawnSync("sh", [SCRIPT, ...args], {
327
+ cwd,
328
+ env: { ...ENV, ...envOverrides },
329
+ encoding: "utf8",
330
+ timeout,
331
+ });
332
+ return {
333
+ code: r.status,
334
+ json: r.stdout.trim() ? JSON.parse(r.stdout) : null,
335
+ stderr: r.stderr,
336
+ error: r.error,
337
+ };
338
+ }
339
+
340
+ function branchExists(w, name) {
341
+ return spawnSync("git", ["rev-parse", "--verify", "--quiet", `refs/heads/${name}`], { cwd: w, env: ENV }).status === 0;
342
+ }
343
+
344
+ function specRow() {
345
+ const spec = readFileSync(
346
+ fileURLToPath(new URL("../../docs/specs/2026-07-23-fleet-plugin-design.md", import.meta.url)),
347
+ "utf8",
348
+ );
349
+ const row = spec.split("\n").find((l) => l.startsWith("| `reap.sh` |"));
350
+ assert.ok(row, "the script-surface table must still carry a reap.sh row");
351
+ return row;
352
+ }
353
+
354
+ test("an uncorrupted repo still reaps a genuinely merged [gone] branch", (t) => {
355
+ const w = repo(t);
356
+ mergedGoneBranch(w, "feature/merged", "merged work");
357
+
358
+ const { code, json, stderr } = runReap(w, ["--apply"]);
359
+
360
+ assert.equal(code, 0);
361
+ assert.deepEqual(json.reaped, ["feature/merged"]);
362
+ assert.deepEqual(json.kept, []);
363
+ assert.doesNotMatch(stderr, /KEEP/);
364
+ assert.equal(branchExists(w, "feature/merged"), false, "a genuinely merged branch must still be deleted");
365
+ });
366
+
367
+ test("an uncorrupted repo keeps an unmerged [gone] branch for unmerged commits", (t) => {
368
+ const w = repo(t);
369
+ unmergedGoneBranch(w, "feature/unmerged", "solo work");
370
+
371
+ const { code, json, stderr } = runReap(w, ["--apply"]);
372
+
373
+ assert.equal(code, 0);
374
+ assert.deepEqual(json.reaped, []);
375
+ assert.equal(json.kept.length, 1);
376
+ assert.equal(json.kept[0].branch, "feature/unmerged");
377
+ assert.equal(json.kept[0].reason, "unmerged commits");
378
+ assert.match(stderr, /KEEP feature\/unmerged — unmerged commits/);
379
+ assert.equal(branchExists(w, "feature/unmerged"), true, "unmerged commits keep the branch alive");
380
+ });
381
+
382
+ // The two tests below share one fixture move: giving a branch a TAG of the
383
+ // same name, pointed at `main`. Both halves of that are load-bearing.
384
+ //
385
+ // The name collision is what breaks the enumeration. `%(refname:short)` is
386
+ // ambiguity-aware — with both refs present it stops shortening to the bare name
387
+ // and emits `heads/<name>` (measured here on git 2.50.1, Apple Git-155). That
388
+ // string is not a branch `git branch -D` can find, and it does not match the
389
+ // `refs/heads/$b` key the worktree lookup builds either, so every worktree
390
+ // guard silently stands down for it (#634).
391
+ //
392
+ // Pointing the tag at `main` — a merged commit — is what makes the pair
393
+ // DISCRIMINATING rather than merely representative. Git resolves a bare
394
+ // ambiguous name as a rev by preferring `refs/tags/` over `refs/heads/`, so
395
+ // anything that hands the bare name to a rev-taking command reaches the tag's
396
+ // merged commit instead of the branch's. A merge probe that does so reports
397
+ // clean for a branch that is not merged at all. That is why the unmerged case
398
+ // below is the one that has to stay red for a fix that only changes the
399
+ // enumeration: correcting the name without qualifying the rev converts a
400
+ // branch that is currently kept into one that is deleted.
401
+ test("a merged [gone] branch sharing its name with a tag is reaped, and reported under its bare branch name (#634)", (t) => {
402
+ const w = repo(t);
403
+ mergedGoneBranch(w, "feature/merged", "merged work");
404
+ const tagged = git(w, "rev-parse", "main");
405
+ git(w, "tag", "feature/merged", "main");
406
+
407
+ const { code, json, stderr } = runReap(w, ["--apply"]);
408
+
409
+ assert.equal(code, 0);
410
+ assert.deepEqual(
411
+ json.reaped,
412
+ ["feature/merged"],
413
+ "the payload names the branch that was deleted; `heads/feature/merged` is a string git would not accept back",
414
+ );
415
+ assert.deepEqual(json.kept, []);
416
+ assert.doesNotMatch(stderr, /heads\/feature\/merged/, "no operator-facing line may name the unusable prefixed form");
417
+ assert.equal(branchExists(w, "feature/merged"), false, "a same-named tag must not strand a genuinely merged branch");
418
+ assert.equal(git(w, "rev-parse", "refs/tags/feature/merged"), tagged, "reaping a branch must leave the tag alone");
419
+ });
420
+
421
+ test("a same-named tag on a merged commit must not authorize reaping an UNMERGED [gone] branch (#634)", (t) => {
422
+ const w = repo(t);
423
+ const sha = unmergedGoneBranch(w, "feature/unmerged", "solo work");
424
+ // Merged, and reachable under the branch's own name as a rev — the two
425
+ // properties that together let a tag answer a question asked about a branch.
426
+ git(w, "tag", "feature/unmerged", "main");
427
+
428
+ const { code, json, stderr } = runReap(w, ["--apply"]);
429
+
430
+ assert.equal(code, 0);
431
+ assert.deepEqual(
432
+ json.reaped,
433
+ [],
434
+ "the merge probe must read the branch it is about to delete, never a same-named tag that happens to be merged",
435
+ );
436
+ assert.equal(json.kept.length, 1);
437
+ assert.equal(json.kept[0].branch, "feature/unmerged");
438
+ assert.equal(json.kept[0].reason, "unmerged commits");
439
+ assert.match(stderr, /KEEP feature\/unmerged — unmerged commits/);
440
+ assert.equal(branchExists(w, "feature/unmerged"), true, "the branch — and its only copy of the commit — must survive");
441
+ assert.equal(git(w, "rev-parse", "refs/heads/feature/unmerged"), sha, "the commit itself is untouched");
442
+ });
443
+
444
+ // #924, the BASE side of the same family, and the third member of it: #634
445
+ // established that in this script the enumeration fix and the rev-consumption
446
+ // fix are separate, PR #914 qualified the BRANCH side (`refs/heads/$b`), and
447
+ // the base side reached `git cherry` exactly as BASE_REF spelled it. The
448
+ // fixture move below is one `git tag origin/main <rev>` — a tag carrying the
449
+ // full remote-tracking SPELLING of the default base, which git's own
450
+ // disambiguation order (refs/tags/<name> before refs/remotes/<name>) then
451
+ // prefers when the shorthand is resolved as a rev.
452
+ //
453
+ // Both halves of that move are load-bearing, and for a different reason than
454
+ // the #634 pair above. There a tag at ANY merged commit triggers it; here the
455
+ // tag has to actually CONTAIN the branch's commits, because a tag named
456
+ // `origin/main` at an unrelated commit yields `+` lines and correctly keeps —
457
+ // which is exactly what makes the control below a control rather than a second
458
+ // copy of the same case.
459
+ //
460
+ // Real content, never `commit()`'s empty commits, is NOT required here and
461
+ // deliberately not used: `unmergedGoneBranch` leaves `main` where it was, so
462
+ // the upstream-only set is empty and there is no patch-id for an empty commit
463
+ // to collide with. A fixture that advances `main` by an empty commit instead
464
+ // reads `-` (already upstream) under BOTH spellings and pins nothing — measured
465
+ // while building this, and the reason the control tags an EXISTING commit
466
+ // rather than making a new one.
467
+ test("a local tag named `origin/main` must not authorize reaping an unmerged [gone] branch (#924)", (t) => {
468
+ const w = repo(t);
469
+ const sha = unmergedGoneBranch(w, "feature/solo", "sole copy, nowhere else");
470
+ git(w, "tag", "origin/main", "refs/heads/feature/solo");
471
+ // `--quiet` for the reason the ticket recorded: it suppresses git's own
472
+ // `warning: refname 'origin/main' is ambiguous.`, which is the one signal
473
+ // this whole class produced and the reason a run was silent. Here it keeps
474
+ // the fixture's own probe from printing it into the suite's output.
475
+ assert.equal(
476
+ git(w, "rev-parse", "--verify", "--quiet", "origin/main"),
477
+ sha,
478
+ "fixture: the shorthand must resolve to the TAG, i.e. the branch's own tip",
479
+ );
480
+ assert.notEqual(
481
+ git(w, "rev-parse", "--verify", "refs/remotes/origin/main"),
482
+ sha,
483
+ "fixture: and the real base must be a different commit, or the shadowing changes no answer",
484
+ );
485
+
486
+ const { code, json, stderr } = runReap(w, ["--apply"]);
487
+
488
+ assert.equal(code, 0);
489
+ assert.deepEqual(
490
+ json.reaped,
491
+ [],
492
+ "the merge probe must measure against refs/remotes/origin/main, never a tag that spells it",
493
+ );
494
+ assert.deepEqual(json.kept, [{ branch: "feature/solo", reason: "unmerged commits" }]);
495
+ assert.match(stderr, /KEEP feature\/solo — unmerged commits/);
496
+ assert.equal(branchExists(w, "feature/solo"), true, "the branch — and its only copy of the commit — must survive");
497
+ assert.equal(git(w, "rev-parse", "refs/heads/feature/solo"), sha, "the commit itself is untouched");
498
+ });
499
+
500
+ test("that same tag, not covering the branch's commits, still reaps a genuinely merged one (#924)", (t) => {
501
+ // The control, and the direction a fix that simply keeps everything fails:
502
+ // the tag is present and still outranks the remote-tracking ref, but it sits
503
+ // at the commit `main` was on before the branch existed, so the branch's work
504
+ // is not in it. Measured against the pre-fix script this fixture is a false
505
+ // KEEP — `git cherry <that old commit> refs/heads/feature/merged` prints `+`
506
+ // for a branch that is fully merged — so the qualification is what restores
507
+ // the reap, not just what blocks one.
508
+ const w = repo(t);
509
+ const before = git(w, "rev-parse", "main");
510
+ mergedGoneBranch(w, "feature/merged", "merged work");
511
+ git(w, "tag", "origin/main", before);
512
+
513
+ const { code, json, stderr } = runReap(w, ["--apply"]);
514
+
515
+ assert.equal(code, 0);
516
+ assert.deepEqual(json.reaped, ["feature/merged"]);
517
+ assert.deepEqual(json.kept, []);
518
+ assert.doesNotMatch(stderr, /KEEP/);
519
+ assert.equal(branchExists(w, "feature/merged"), false, "a shadowing tag must not strand a genuinely merged branch either");
520
+ assert.equal(git(w, "rev-parse", "refs/tags/origin/main"), before, "reaping a branch must leave the tag alone");
521
+ });
522
+
523
+ test("a local tag named `origin/main` must not authorize REMOVING a detached worktree's only copy (#924)", (t) => {
524
+ // The second measurement site, and the one where the misread costs the FILES:
525
+ // this sweep removes directories. A fix applied to the branch sweep alone
526
+ // leaves it blind — the same split #730 pinned for the status probe — so it
527
+ // is pinned separately here.
528
+ const w = repo(t);
529
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
530
+ const sole = commit(wt, "sole copy, nowhere else");
531
+ git(w, "tag", "origin/main", sole);
532
+
533
+ const { code, json } = runReap(w, ["--apply"]);
534
+
535
+ assert.equal(code, 0);
536
+ assert.deepEqual(json.worktreesRemoved, [], "the probe must not read the worktree's own tip as the base");
537
+ assert.equal(existsSync(wt), true);
538
+ assert.equal(json.kept.length, 1);
539
+ assert.equal(json.kept[0].reason, `worktree ${wt} holds commits that exist nowhere else`);
540
+ assert.equal(git(wt, "rev-parse", "HEAD"), sole, "the commit is still reachable from the worktree");
541
+ });
542
+
543
+ test("a BASE_REF that only resolves as a TAG is refused, never measured against (#924)", (t) => {
544
+ // The guard site, and the fail-closed half of the same edit. `rev-parse
545
+ // --verify` used to ask about the shorthand, which a tag answers at exit 0 —
546
+ // so a BASE_REF with no remote-tracking ref behind it at all passed the guard
547
+ // and every sweep then measured against the tag. Measured on the pre-fix
548
+ // script: `REAPED feature/solo` at exit 0, the branch's sole commit gone.
549
+ // Asking about the qualified spelling turns that into a refusal naming the
550
+ // spelling the caller passed.
551
+ const w = repo(t);
552
+ const sha = unmergedGoneBranch(w, "feature/solo", "sole copy, nowhere else");
553
+ git(w, "tag", "origin/gone-upstream", "refs/heads/feature/solo");
554
+
555
+ const { code, json, stderr } = runReap(w, ["--apply"], { BASE_REF: "origin/gone-upstream" });
556
+
557
+ assert.equal(code, 2);
558
+ assert.equal(json, null, "a refusal emits no payload");
559
+ assert.match(stderr, /^reap: origin\/gone-upstream does not resolve$/m,
560
+ "the message names what the caller passed, not the qualified spelling it cannot act on");
561
+ assert.equal(branchExists(w, "feature/solo"), true, "and nothing is deleted on the way out");
562
+ assert.equal(git(w, "rev-parse", "refs/heads/feature/solo"), sha);
563
+ });
564
+
565
+ test("BASE_REF must be a remote-tracking ref (#924)", (t) => {
566
+ // The accept-list this script had none of, and the precondition that makes
567
+ // the qualification above sound: with the input restricted to the one
568
+ // namespace that can answer "has this landed upstream", prefixing
569
+ // `refs/remotes/` is always correct. Unrestricted, `refs/heads/main` was
570
+ // taken at face value — a local main never fast-forwarded strands every
571
+ // merged branch, and `refs/heads/<a branch in the sweep>` reads that branch's
572
+ // own commits as upstream and authorizes `-D` on them.
573
+ const w = repo(t);
574
+ unmergedGoneBranch(w, "feature/solo", "sole copy, nowhere else");
575
+
576
+ const { code, json, stderr } = runReap(w, ["--apply"], { BASE_REF: "refs/heads/main" });
577
+
578
+ assert.equal(code, 2);
579
+ assert.equal(json, null, "a refusal emits no payload");
580
+ assert.match(stderr, /^reap: BASE_REF must be a remote-tracking ref, got 'refs\/heads\/main'$/m);
581
+ assert.equal(branchExists(w, "feature/solo"), true, "a refused invocation reads nothing and deletes nothing");
582
+
583
+ // Fourth pin on the design spec's script-surface row, same reason as the
584
+ // three others: the row states this script's exit-2 contract in prose, and a
585
+ // reader trusting it draws safety conclusions about a script settings.json's
586
+ // autoMode allowlist lets run unattended. Taken from the real refusal rather
587
+ // than typed here — a hand-copied phrase drifts.
588
+ const label = /^reap: (.+?), got '/m.exec(stderr);
589
+ assert.ok(label, `fixture must reach the accept-list refusal: ${stderr}`);
590
+ const row = specRow();
591
+ assert.ok(
592
+ row.includes(label[1]),
593
+ `the spec row must state this refusal, and does not carry "${label[1]}".\nrow: ${row}`,
594
+ );
595
+ });
596
+
597
+ test("an already-qualified BASE_REF is measured with as given, never prefixed twice (#924)", (t) => {
598
+ // The `refs/remotes/*` arm of the qualification. Dropping it — prefixing
599
+ // unconditionally — builds `refs/remotes/refs/remotes/origin/main`, which
600
+ // resolves to nothing, so the accepted spelling this very accept-list admits
601
+ // would refuse at the guard below it.
602
+ const w = repo(t);
603
+ mergedGoneBranch(w, "feature/merged", "merged work");
604
+
605
+ const { code, json, stderr } = runReap(w, ["--apply"], { BASE_REF: "refs/remotes/origin/main" });
606
+
607
+ assert.equal(code, 0, `the qualified spelling must resolve: ${stderr}`);
608
+ assert.deepEqual(json.reaped, ["feature/merged"]);
609
+ assert.deepEqual(json.kept, []);
610
+ });
611
+
612
+ test("a git cherry that dies is KEPT, never reaped — an unanswerable probe authorizes nothing (#264)", (t) => {
613
+ const w = repo(t);
614
+ const sha = unmergedGoneBranch(w, "feature/onlyhere", "sole copy, nowhere else");
615
+
616
+ const bin = cherryShim(t);
617
+
618
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
619
+
620
+ assert.equal(code, 0, "an unanswerable probe is not a script failure");
621
+ assert.deepEqual(json.reaped, [], "the sole-copy commit must not be deleted on a probe that could not answer");
622
+ assert.equal(json.kept.length, 1);
623
+ assert.equal(json.kept[0].branch, "feature/onlyhere");
624
+ assert.match(json.kept[0].reason, /cherry probe failed/, "the reason must name the probe failure, not read as a clean merge");
625
+ assert.match(json.kept[0].reason, /revision walk setup failed/, "git's own message must reach the reason, not just a generic label");
626
+ assert.doesNotMatch(
627
+ json.kept[0].reason,
628
+ /\n/,
629
+ "git's stderr is multi-line; an embedded newline would break the JSON payload — the reason must be flattened",
630
+ );
631
+ assert.match(stderr, /cherry probe failed/);
632
+
633
+ assert.equal(branchExists(w, "feature/onlyhere"), true, "the branch — and its only copy of the commit — must survive");
634
+ assert.equal(git(w, "rev-parse", "feature/onlyhere"), sha, "the commit itself is untouched");
635
+ });
636
+
637
+ test("a `+` inside git's stderr is not a commit line — a merged branch is still reaped", (t) => {
638
+ const w = repo(t);
639
+ mergedGoneBranch(w, "feature/merged", "merged work");
640
+ const tip = git(w, "rev-parse", "refs/heads/feature/merged");
641
+
642
+ // The warning goes in the `match`, not the stderr array: a false match falls
643
+ // THROUGH to `exec ${REAL_GIT}`, so the shim warns and the merge check still
644
+ // reads a genuine `git cherry` run's stdout rather than an empty one.
645
+ // `git cherry` SUCCEEDS here — rc 0, no commit lines on stdout — but writes a
646
+ // diagnostic containing a `+` to stderr, which the capture's 2>&1 folds into
647
+ // the value the merge check matches. Only the line-start `+` is a commit, so
648
+ // this branch must still be reaped. An unanchored match keeps it forever.
649
+ const bin = failOnlyShim(t, `[ "$1" = cherry ] && { printf '%s\\n' "warning: unable to access '/x/c++/lib/.gitattributes'" >&2; ${SHIM_FIRED}; false; }`, []);
650
+
651
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
652
+
653
+ // The fixture branch is genuinely merged, so every assertion below also held
654
+ // with the shim argument replaced by `{}` (measured, #759): the arm could not
655
+ // tell an absent anchoring bug from an absent fault. This is what makes it a
656
+ // test of the anchoring rather than of the fixture.
657
+ // The branch sweep's cherry targets the tip SHA it read once (#2219), not
658
+ // `refs/heads/<b>`, so the argv pin is that SHA.
659
+ assertShimFired(
660
+ bin,
661
+ "no `+` ever reached the merge check — the rest of this arm passes on any fixture",
662
+ new RegExp(`^cherry \\S+ ${tip}$`, "m"),
663
+ );
664
+ assert.equal(code, 0);
665
+ assert.deepEqual(json.kept, [], "a `+` inside a diagnostic is not an unmerged commit");
666
+ assert.deepEqual(json.reaped, ["feature/merged"]);
667
+ assert.equal(branchExists(w, "feature/merged"), false, "noisy stderr must not strand a merged branch");
668
+ });
669
+
670
+ /**
671
+ * A PATH dir whose `git` fails only `worktree prune`, standing in for the
672
+ * repo-level faults that do exit non-zero — an unreadable `.git/config`, a
673
+ * `GIT_DIR` off the repo — never a filesystem one: an unwritable
674
+ * `.git/worktrees` prints `error: failed to delete …` and still exits 0, and
675
+ * prune skips a locked entry at 0. Everything else, including
676
+ * `git worktree remove`, execs the real git, unshimmed.
677
+ */
678
+ function pruneShim(t) {
679
+ return failOnlyShim(t, `[ "$1" = worktree ] && [ "$2" = prune ]`, ["fatal: unable to prune worktrees: permission denied"]);
680
+ }
681
+
682
+ // #265: `git worktree prune` used to be the last command of an AND-OR list
683
+ // after the branch loop, so under `set -eu` its own failure — not just a
684
+ // false `[ apply = true ]` — reached -e and aborted the script before the
685
+ // payload printed, after the branches above were already deleted. The
686
+ // caller lost the only record of what had happened, at exit 1: the code the
687
+ // fleet's script contract reserves for a verdict, from a script with none.
688
+ test("a failing `git worktree prune` still prints the payload and refuses on 2, never 1 (#265)", (t) => {
689
+ const w = repo(t);
690
+ mergedGoneBranch(w, "feature/merged", "merged work");
691
+
692
+ const bin = pruneShim(t);
693
+
694
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
695
+
696
+ assert.equal(code, 2, "a failing prune must refuse loudly on 2, never fall through to the -e default of 1");
697
+ assert.ok(json, "the payload must still print even though the prune below it failed");
698
+ assert.deepEqual(json.reaped, ["feature/merged"], "branches already deleted must still be recorded");
699
+ assert.deepEqual(json.kept, []);
700
+ assert.match(stderr, /git worktree prune/, "the refusal must name the command that failed");
701
+ });
702
+
703
+ // The other half of #992, and the one the cwd refusal below cannot cover: a
704
+ // prune that fails for a reason nobody here caused still has to say what git
705
+ // said. `die "git worktree prune failed"` named the step and dropped git's
706
+ // stdout and stderr on the floor — the class #578 catalogues at this script's
707
+ // other sites — so an operator read a step name, and in the deleted-cwd case
708
+ // git's own `fatal: Unable to read current working directory` reached the
709
+ // terminal on a line of its own with nothing tying the two together.
710
+ //
711
+ // Its own two-line shim rather than `pruneShim`: the realism argument is that
712
+ // helper's (a repo-level fault that really does exit non-zero), and the second
713
+ // line is what pins the `tr '\n' ' '` fold every other reason in this script
714
+ // applies — a message that kept its newline would split one refusal across two
715
+ // stderr lines and read as two failures.
716
+ test("a failing `git worktree prune` refusal carries git's own message, folded to one line (#992)", (t) => {
717
+ const w = repo(t);
718
+ mergedGoneBranch(w, "feature/merged", "merged work");
719
+
720
+ const bin = failOnlyShim(t, `[ "$1" = worktree ] && [ "$2" = prune ]`, [
721
+ "error: could not lock config file .git/config: Permission denied",
722
+ "fatal: unable to prune worktrees: permission denied",
723
+ ]);
724
+
725
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
726
+
727
+ assert.equal(code, 2, "a genuinely failing prune must still refuse");
728
+ assert.deepEqual(json.reaped, ["feature/merged"], "the payload still precedes the prune (#265)");
729
+ assertShimFired(bin, "the fixture must actually reach the prune", /worktree prune/);
730
+ assert.match(
731
+ stderr,
732
+ /reap: git worktree prune failed: error: could not lock config file \.git\/config: Permission denied fatal: unable to prune worktrees: permission denied/,
733
+ `the refusal must quote git, not just name the step: ${stderr}`,
734
+ );
735
+ });
736
+
737
+ // Accept-side control for the fix above: a run where nothing fails must be
738
+ // completely unchanged — same payload shape, exit 0, and the prune must
739
+ // still actually run (not just get skipped to dodge the -e trap).
740
+ test("a successful --apply run still reaps, still prunes, and exits 0 unchanged", (t) => {
741
+ const w = repo(t);
742
+ mergedGoneBranch(w, "feature/merged", "merged work");
743
+
744
+ // A worktree whose directory is gone but whose registration survives until
745
+ // `git worktree prune` runs — proof the prune still executes post-fix.
746
+ const wtDir = join(w, "..", "stale-wt");
747
+ git(w, "worktree", "add", "-q", "-b", "scratch/stale", wtDir, "main");
748
+ rmSync(wtDir, { recursive: true, force: true });
749
+ assert.match(git(w, "worktree", "list"), /stale-wt/, "fixture must start with a prunable registration");
750
+
751
+ const { code, json } = runReap(w, ["--apply"]);
752
+
753
+ assert.equal(code, 0);
754
+ assert.deepEqual(json.reaped, ["feature/merged"]);
755
+ assert.deepEqual(json.kept, []);
756
+ assert.doesNotMatch(git(w, "worktree", "list"), /stale-wt/, "the prune must still run and clear the stale registration");
757
+ });
758
+
759
+ // The other half of the same guard, and the half no test had: the default
760
+ // mode runs no prune at all, but the guard is the script's last statement, so
761
+ // the guard's SHAPE decides the dry run's exit status. Every other test here
762
+ // passes --apply, which is exactly how an AND-OR form regressed this path from
763
+ // 0 to a bare 1 under a fully green suite (#265).
764
+ test("the default dry run reports its verdict and exits 0, never a bare 1 (#265)", (t) => {
765
+ const w = repo(t);
766
+ mergedGoneBranch(w, "feature/merged", "merged work");
767
+
768
+ const { code, json } = runReap(w, []);
769
+
770
+ assert.equal(code, 0, "a dry run with nothing to report must exit 0, not the -e default of 1");
771
+ assert.equal(json.applied, false);
772
+ assert.deepEqual(json.reaped, ["feature/merged"], "a dry run still reports what it would reap");
773
+ assert.equal(branchExists(w, "feature/merged"), true, "a dry run must not delete anything");
774
+ });
775
+
776
+ // #250. The usage guard was arity-only — it rejected a second argument and
777
+ // nothing looked at what a single one SAID, while the `--apply` test beside it
778
+ // demoted anything that was not exactly `--apply` to "not --apply". A mistyped
779
+ // flag therefore ran the dry run and reported it as one. Measured against the
780
+ // pre-fix script, `reap.sh --aply` exited 0 and printed
781
+ // `{"applied":false,"reaped":[],"kept":[]}` — the exit code and the payload of
782
+ // a deliberate dry run, with nothing anywhere saying the flag was not
783
+ // understood. The direction of the silence is the mild one (a typo'd `--apply`
784
+ // under-deletes), which is why it is a refusal rather than a data-loss bug.
785
+ //
786
+ // Exit 2 and an empty stdout do not on their own pin THIS guard: every later
787
+ // refusal in this script produces both, so a downstream one would satisfy the
788
+ // pair while the prologue let the argument through. What discriminates is what
789
+ // the run never reached — the fetch it echoes before running, and the dry-run
790
+ // banner — plus the branch still standing.
791
+ test("a mistyped --apply refuses instead of quietly running a dry run (#250)", (t) => {
792
+ const w = repo(t);
793
+ mergedGoneBranch(w, "feature/merged", "merged work");
794
+
795
+ const { code, json, stderr } = runReap(w, ["--aply"]);
796
+
797
+ assert.equal(code, 2, "an unrecognised argument must refuse, not be demoted to 'not --apply'");
798
+ assert.equal(json, null, "a refused invocation reports nothing — a payload here would read as a clean no-op");
799
+ assert.match(stderr, /unrecognised argument '--aply'/, "the refusal must name the argument it did not understand");
800
+ assert.doesNotMatch(stderr, /git fetch --prune origin/, "the guard is fatal and fires above the fetch");
801
+ assert.doesNotMatch(stderr, /DRY RUN/, "a refusal must not also announce the dry run it used to become");
802
+ assert.equal(branchExists(w, "feature/merged"), true, "a refused invocation deletes nothing");
803
+ });
804
+
805
+ // The other direction, and the one a new guard gets wrong: what it must still
806
+ // ACCEPT. Both accepted forms, against a fixture with a branch to act on, so a
807
+ // guard that refused either would be visible here rather than as a fleet run
808
+ // that stopped reaping.
809
+ test("the invocations reap.sh accepts are unchanged — bare and --apply (#250)", (t) => {
810
+ for (const [args, applied] of [[[], false], [["--apply"], true]]) {
811
+ const w = repo(t, `w-${applied}`);
812
+ mergedGoneBranch(w, "feature/merged", "merged work");
813
+
814
+ const { code, json, stderr } = runReap(w, args);
815
+
816
+ assert.equal(code, 0, `\`reap.sh ${args.join(" ")}\` must still run: ${stderr}`);
817
+ assert.equal(json.applied, applied);
818
+ assert.deepEqual(json.reaped, ["feature/merged"], "the accepted forms still report what they reap");
819
+ assert.doesNotMatch(stderr, /unrecognised argument/, "an accepted invocation must not be refused");
820
+ }
821
+ });
822
+
823
+ // Arity is a separate arm from value, and the value guard's own message also
824
+ // carries the usage line — so `doesNotMatch` is what says two arguments took
825
+ // the arity path rather than falling through it into the new one.
826
+ test("two arguments still refuse via the arity path (#250)", (t) => {
827
+ const w = repo(t);
828
+
829
+ const { code, json, stderr } = runReap(w, ["a", "b"]);
830
+
831
+ assert.equal(code, 2);
832
+ assert.equal(json, null);
833
+ assert.match(stderr, /usage: reap\.sh \[--apply\]/);
834
+ assert.doesNotMatch(stderr, /unrecognised argument/, "an arity refusal is not a value refusal");
835
+ });
836
+
837
+ // Third pin on the same table row, for the same reason as the two below: the
838
+ // row states this script's exit-2 contract in prose, #114 audited it while the
839
+ // guard was arity-only, and a reader trusting it draws a conclusion about a
840
+ // script that settings.json's autoMode allowlist lets run unattended. Taken
841
+ // from a real refusal rather than typed here — a hand-copied phrase drifts
842
+ // exactly the way the row did.
843
+ test("the design spec's script-surface row carries the argument refusal this script emits (#250)", (t) => {
844
+ const w = repo(t);
845
+
846
+ const { stderr } = runReap(w, ["--aply"]);
847
+
848
+ // The label only: the argument itself is the caller's to vary and no doc can
849
+ // carry it.
850
+ const label = /^reap: (.+?) '/m.exec(stderr);
851
+ assert.ok(label, `fixture must reach the argument refusal: ${stderr}`);
852
+
853
+ const row = specRow();
854
+ assert.ok(
855
+ row.includes(label[1]),
856
+ `the spec row must state this refusal, and does not carry "${label[1]}".\nrow: ${row}`,
857
+ );
858
+ });
859
+
860
+ // The design spec's script-surface table states this script's exit-0 contract in
861
+ // prose, and it spent the whole life of #264 asserting the bug as the behaviour:
862
+ // "the merged check reads a `git cherry` that failed as 'no unmerged commits'
863
+ // and reaps the branch". Fixing that is one edited row; this is the part that
864
+ // keeps the next one from rotting silently — a reader trusting the table would
865
+ // draw the opposite safety conclusion about a script that settings.json's
866
+ // autoMode allowlist lets run unattended. Derived from a real run, never from a
867
+ // phrase typed here: a hand-copied phrase drifts from the script exactly the way
868
+ // the row did.
869
+ // Sibling pin, same table, same reason: no-undo-audit.test.mjs.
870
+ test("the design spec's script-surface row carries the keep reason this script actually emits", (t) => {
871
+ const w = repo(t);
872
+ unmergedGoneBranch(w, "feature/onlyhere", "sole copy, nowhere else");
873
+ const bin = cherryShim(t);
874
+
875
+ const { json } = runReap(w, ["--apply"], withShim(bin));
876
+
877
+ // Everything up to the first colon: the label reap.sh chose, without git's
878
+ // own message, which is the machine's to vary and no doc can carry.
879
+ const label = json.kept[0].reason.split(":")[0].trim();
880
+ assert.match(label, /^cherry probe failed/, "fixture must reach the failed-probe keep, not some other one");
881
+
882
+ const row = specRow();
883
+ assert.ok(
884
+ row.includes(label),
885
+ `the spec row must quote the keep reason verbatim, and does not carry "${label}".\nrow: ${row}`,
886
+ );
887
+ });
888
+
889
+ // Worktree-removal coverage (#83, #128). Before this file, reap.sh's
890
+ // worktree-removal path had NO fixture at all: a merged [gone] branch was
891
+ // always tested without a worktree, so the dirty check, the linkage guard and
892
+ // the absent-directory path never ran under test.
893
+
894
+ test("a healthy clean worktree on a merged [gone] branch is reaped, directory and all", (t) => {
895
+ const w = repo(t);
896
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
897
+ assert.ok(existsSync(wt), "fixture");
898
+
899
+ const { code, json, stderr } = runReap(w, ["--apply"]);
900
+
901
+ assert.equal(code, 0);
902
+ assert.deepEqual(json.reaped, ["feature/merged"]);
903
+ assert.deepEqual(json.kept, []);
904
+ assert.doesNotMatch(stderr, /KEEP/);
905
+ assert.equal(branchExists(w, "feature/merged"), false);
906
+ assert.equal(existsSync(wt), false, "the worktree directory itself must be removed");
907
+ });
908
+
909
+ test("a dirty worktree on an otherwise-mergeable [gone] branch is kept, not reaped", (t) => {
910
+ const w = repo(t);
911
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
912
+ writeFileSync(join(wt, "scratch.txt"), "uncommitted\n");
913
+
914
+ const { code, json, stderr } = runReap(w, ["--apply"]);
915
+
916
+ assert.equal(code, 0);
917
+ assert.deepEqual(json.reaped, []);
918
+ assert.equal(json.kept.length, 1);
919
+ assert.equal(json.kept[0].branch, "feature/merged");
920
+ assert.match(json.kept[0].reason, /^dirty worktree /);
921
+ assert.match(stderr, /KEEP feature\/merged — dirty worktree/);
922
+ assert.equal(branchExists(w, "feature/merged"), true);
923
+ assert.equal(existsSync(wt), true, "a dirty worktree must survive untouched");
924
+ });
925
+
926
+ // #730, and the reason the probe above carries `-uall`. The untracked mode is
927
+ // CONFIG: `git status --porcelain` honours `status.showUntrackedFiles`, so with
928
+ // it set to `no` the probe exits 0 with EMPTY output over a worktree holding
929
+ // untracked work. The `if !` idiom fails closed only on a NON-ZERO exit, so it
930
+ // never fires; `gp_cut_short` has no stderr to match; `[ -n "$gp_out" ]` reads
931
+ // clean. Measured on the unmodified script before the fix, with a control on
932
+ // the identical fixture: config set -> `REAPED feature/merged` at exit 0, the
933
+ // worktree directory and the untracked file gone, no KEEP and nothing on
934
+ // stderr; config unset -> `KEEP feature/merged — dirty worktree …`, file alive.
935
+ //
936
+ // A FLEET worktree deliberately, under `.worktrees/`: that home is exempt from
937
+ // the `--ignored` probe below, so this gate is the only thing between the file
938
+ // and `git worktree remove` — and `remove` without `--force` is no backstop,
939
+ // being the same machinery the same config silences.
940
+ //
941
+ // The config goes in the repo's own config, not GIT_CONFIG_GLOBAL: ENV already
942
+ // pins that to /dev/null, and the repo config is what a linked worktree shares
943
+ // — which is the point, since it is set from the main checkout and silences the
944
+ // worktree's probe.
945
+ test("a worktree holding untracked work is kept under status.showUntrackedFiles=no (#730)", (t) => {
946
+ const w = repo(t);
947
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
948
+ writeFileSync(join(wt, "precious.txt"), "untracked, and it exists nowhere else\n");
949
+ git(w, "config", "status.showUntrackedFiles", "no");
950
+ // The fixture's own positive control. Without it a git that stopped honouring
951
+ // the config would leave this test green while pinning nothing at all.
952
+ assert.equal(git(wt, "status", "--porcelain"), "",
953
+ "fixture: the config must really silence the unpinned probe, or this test measures nothing");
954
+
955
+ const { code, json, stderr } = runReap(w, ["--apply"]);
956
+
957
+ assert.equal(code, 0);
958
+ assert.deepEqual(json.reaped, []);
959
+ assert.deepEqual(json.worktreesRemoved, []);
960
+ assert.equal(json.kept.length, 1);
961
+ // The reason, not merely the keep: several other guards also leave `reaped`
962
+ // empty, so the pair alone does not say which one answered.
963
+ assert.equal(json.kept[0].reason, `dirty worktree ${wt}`);
964
+ assert.match(stderr, /KEEP feature\/merged — dirty worktree/);
965
+ assert.equal(branchExists(w, "feature/merged"), true);
966
+ assert.equal(readFileSync(join(wt, "precious.txt"), "utf8"), "untracked, and it exists nowhere else\n",
967
+ "the untracked file must survive the run — this is the data loss the ticket measured");
968
+ });
969
+
970
+ test("an ignored file is still seen under status.showUntrackedFiles=no (#730)", (t) => {
971
+ // The backstop, and it is the SAME machinery as the gate above — so one
972
+ // config silences both and the defence in depth is only apparent. Measured on
973
+ // this fixture: under `showUntrackedFiles = no`, `--porcelain --ignored`
974
+ // answers 0 bytes at rc 0, the `!!` lines suppressed along with the `??`
975
+ // ones, so a precious ignored file reads as absent. Outside `.worktrees/`
976
+ // this probe is the only thing left between a merged, linked, tracked-clean
977
+ // worktree and a `git worktree remove` that deletes ignored files silently
978
+ // under every config.
979
+ //
980
+ // No untracked file in this fixture, only an ignored one: the plain scan
981
+ // above answers empty either way, so the verdict here is the `--ignored`
982
+ // probe's alone and a fix applied to only the first site fails this test.
983
+ const w = repo(t);
984
+ writeFileSync(join(w, ".gitignore"), ".env\n");
985
+ git(w, "add", ".gitignore");
986
+ commit(w, "ignore .env");
987
+ git(w, "push", "-q", "origin", "main");
988
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "outside"));
989
+ writeFileSync(join(wt, ".env"), "SECRET=exists nowhere else\n");
990
+ git(w, "config", "status.showUntrackedFiles", "no");
991
+ assert.equal(git(wt, "status", "--porcelain", "--ignored"), "",
992
+ "fixture: the config must silence the unpinned --ignored probe, or this test measures nothing");
993
+
994
+ const { code, json } = runReap(w, ["--apply"]);
995
+
996
+ assert.equal(code, 0);
997
+ assert.deepEqual(json.reaped, []);
998
+ assert.equal(json.kept.length, 1);
999
+ assert.match(json.kept[0].reason, /^ignored files present in .*: \.env$/);
1000
+ assert.equal(branchExists(w, "feature/merged"), true);
1001
+ assert.equal(readFileSync(join(wt, ".env"), "utf8"), "SECRET=exists nowhere else\n",
1002
+ "the precious ignored file must survive the run");
1003
+ });
1004
+
1005
+ // #614: the BEHAVIOURAL twin of locale-pin-prose.test.mjs' source assertion for
1006
+ // this script — that file checks `export LC_ALL=C` is PRESENT, this one checks
1007
+ // it is load-bearing.
1008
+ //
1009
+ // The ambient locale must reach the child genuinely, not merely differ from
1010
+ // `C`: a POSIX shell keeps a variable's export attribute once it is already in
1011
+ // the environment, so seeding `LC_ALL: "en_US.UTF-8"` here would leave a mutant
1012
+ // that drops only the `export` keyword still propagating `C` downstream. `LANG`
1013
+ // with `LC_ALL` and `LC_CTYPE` absent is what an unset `LC_ALL` really looks
1014
+ // like — the shape #599's own regression test got wrong.
1015
+ const AMBIENT_UTF8 = { LANG: "en_US.UTF-8", LC_ALL: undefined, LC_CTYPE: undefined };
1016
+
1017
+ // CEILING: this kills its mutant on macOS only. BWK awk aborts (rc 2,
1018
+ // `towc: multibyte conversion failure`) on a record it must scan past and
1019
+ // cannot convert to wide characters; gawk 5.4.1 and mawk 1.3.4 both answer
1020
+ // rc 0 on the same input, so on `ubuntu-latest` — the one platform ci.yml runs
1021
+ // — the unpinned script already gives the right answer and this test is
1022
+ // vacuous. It asserts the CORRECT answer, so it is green on both. #790.
1023
+ //
1024
+ // The byte reaches the sweep through the registry, never the filesystem: APFS
1025
+ // refuses the name outright, but `git worktree list --porcelain` derives the
1026
+ // path it prints from the entry's `gitdir` file and emits it raw and unquoted.
1027
+ // One such SIBLING entry is enough — awk tests every rule against every record,
1028
+ // so the `/^branch /` rule scans the bad `worktree` record and dies there,
1029
+ // taking the lookup for the branch actually under sweep with it.
1030
+ //
1031
+ // Measured with the pin deleted: awk itself dies (`towc: multibyte conversion
1032
+ // failure`), and because this script runs under `set -eu` that failing command
1033
+ // substitution (line ~347) TERMINATES the whole script at exit 2 — nothing is
1034
+ // reaped, `feature/merged`'s branch and its uncommitted work both survive.
1035
+ // This test still catches the mutant (`assert.equal(code, 0)` fails, `2 !== 0`)
1036
+ // — only the narrative below used to be wrong, not the test. What this pins is
1037
+ // that the sweep must not silently ABORT mid-run on a sibling's bad path,
1038
+ // leaving the caller to guess whether anything was mutated before the crash —
1039
+ // not a data-loss-prevented story, since data loss was never actually
1040
+ // reachable here.
1041
+ test("an invalid UTF-8 byte in a SIBLING worktree's registered path does not cost a dirty worktree its keep (#614)", (t) => {
1042
+ const w = repo(t);
1043
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1044
+ writeFileSync(join(wt, "scratch.txt"), "uncommitted\n");
1045
+
1046
+ const other = join(w, ".worktrees", "other");
1047
+ git(w, "worktree", "add", "-q", other, "-b", "feature/other", "main");
1048
+ relocate(w, other, `${w}/.worktrees/bÿad`);
1049
+
1050
+ const { code, json, stderr } = runReap(w, ["--apply"], AMBIENT_UTF8);
1051
+
1052
+ assert.equal(code, 0, `stderr: ${stderr}`);
1053
+ assert.deepEqual(json.reaped, []);
1054
+ const kept = json.kept.find((k) => k.branch === "feature/merged");
1055
+ assert.ok(kept, `feature/merged must still be kept, got ${JSON.stringify(json.kept)}`);
1056
+ assert.match(kept.reason, /^dirty worktree /);
1057
+ assert.equal(branchExists(w, "feature/merged"), true);
1058
+ assert.equal(existsSync(join(wt, "scratch.txt")), true, "the uncommitted work must survive untouched");
1059
+ });
1060
+
1061
+ test("a status probe that dies (rc 128) is kept with git's own message, not just a label (#625)", (t) => {
1062
+ // Before #625, this probe's stderr went to /dev/null and the reason named
1063
+ // only the step ("could not be read"), never the fault. Git's own message —
1064
+ // here the admin path it names — is the whole remedy signal, and it used to
1065
+ // reach nobody but the terminal that ran this by hand.
1066
+ const w = repo(t);
1067
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1068
+
1069
+ const bin = failOnlyShim(
1070
+ t,
1071
+ STATUS_PROBE,
1072
+ ["fatal: not a git repository: /some/admin/path"],
1073
+ 128,
1074
+ );
1075
+
1076
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1077
+
1078
+ assert.equal(code, 0, "an unanswerable probe is not a script failure");
1079
+ assert.deepEqual(json.reaped, []);
1080
+ assert.equal(json.kept.length, 1);
1081
+ assert.equal(json.kept[0].branch, "feature/merged");
1082
+ assert.match(json.kept[0].reason, /^worktree .* could not be read: /);
1083
+ assert.match(json.kept[0].reason, /fatal: not a git repository: \/some\/admin\/path/, "git's own message must reach the reason");
1084
+ assert.match(stderr, /KEEP feature\/merged/);
1085
+ assert.equal(branchExists(w, "feature/merged"), true);
1086
+ assert.equal(existsSync(wt), true);
1087
+ });
1088
+
1089
+ test("a clean worktree with a warning on the plain status probe's stderr is still reaped, never misread as dirty (#625)", (t) => {
1090
+ // The control that proves the fix keeps the two streams apart rather than
1091
+ // folding them with `2>&1`. Folded, this warning would land IN the value
1092
+ // the dirty-check tests with `[ -n ]`, and a clean worktree would read as
1093
+ // dirty and never be reaped again — silently, and looking like correct,
1094
+ // conservative behavior. Left at the old `2>/dev/null`, this test would
1095
+ // still pass; it exists to catch a REGRESSION to the merged-stream mistake,
1096
+ // not to distinguish the fix from the original bug.
1097
+ const w = repo(t);
1098
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1099
+
1100
+ const bin = failOnlyShim(
1101
+ t,
1102
+ STATUS_PROBE,
1103
+ ["warning: unrelated advice from git, not about this worktree's contents"],
1104
+ 0,
1105
+ );
1106
+
1107
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1108
+
1109
+ assertShimFired(bin, "the warning never reached the dirty check — the rest of this arm passes on any fixture");
1110
+ assert.equal(code, 0);
1111
+ assert.deepEqual(json.kept, [], "a warning unrelated to dirtiness must not keep this branch");
1112
+ assert.deepEqual(json.reaped, ["feature/merged"]);
1113
+ assert.doesNotMatch(stderr, /dirty worktree/, "the warning must never be read as dirty content");
1114
+ assert.equal(branchExists(w, "feature/merged"), false);
1115
+ assert.equal(existsSync(wt), false);
1116
+ });
1117
+
1118
+ test("an `--ignored` probe that warns at rc 0 is kept, listing incomplete, never read as an empty answer (#625)", (t) => {
1119
+ // Measured, PR #726 review: a `chmod 000` ignored directory made exactly
1120
+ // this probe print a permission warning and exit 0 — not a failure this
1121
+ // script's rc check ever saw, and not a keep either, so the run proceeded to
1122
+ // reap a worktree it had provably not finished reading. `--ignored` OPENS
1123
+ // every ignored path to list what's inside, unlike the plain scan above,
1124
+ // which is what makes this probe (and only this one) able to reach that
1125
+ // warning at all.
1126
+ const w = repo(t);
1127
+ // Outside .worktrees/: that home exempts the ignored-file probe entirely, so
1128
+ // this fixture has to sit elsewhere for the probe to run at all.
1129
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "outside"));
1130
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so only the --ignored probe can decide");
1131
+
1132
+ const bin = failOnlyShim(
1133
+ t,
1134
+ IGNORED_PROBE,
1135
+ ["warning: could not open directory 'secret/': Permission denied"],
1136
+ 0,
1137
+ );
1138
+
1139
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1140
+
1141
+ assert.equal(code, 0);
1142
+ assert.deepEqual(json.reaped, []);
1143
+ assert.equal(json.kept.length, 1);
1144
+ assert.equal(json.kept[0].branch, "feature/merged");
1145
+ assert.match(json.kept[0].reason, /^worktree .* status --ignored warned, listing may be incomplete: /);
1146
+ assert.match(json.kept[0].reason, /Permission denied/, "git's own warning must reach the reason");
1147
+ assert.match(stderr, /KEEP feature\/merged/);
1148
+ assert.equal(branchExists(w, "feature/merged"), true);
1149
+ assert.equal(existsSync(wt), true);
1150
+ });
1151
+
1152
+ test("a plain status probe that warns its walk was cut short keeps the branch, never reads the empty answer as clean (#625)", (t) => {
1153
+ // The other half of the same asymmetry. `git status --porcelain` opens
1154
+ // UNTRACKED directories, so an unreadable one makes it warn at rc 0 and
1155
+ // answer EMPTY — measured, git 2.50.1 (Apple Git-155). The rc check above
1156
+ // never fires, `[ -n "$gp_out" ]` reads the empty answer as clean, and
1157
+ // `--apply` deletes a worktree holding work git had provably not finished
1158
+ // listing. This is the fleet-worktree path: `.worktrees/` is exempt from the
1159
+ // `--ignored` probe, so the plain scan is the ONLY probe that can catch it.
1160
+ const w = repo(t);
1161
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1162
+
1163
+ const bin = failOnlyShim(
1164
+ t,
1165
+ STATUS_PROBE,
1166
+ ["warning: could not open directory 'wip/': Permission denied"],
1167
+ 0,
1168
+ );
1169
+
1170
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1171
+
1172
+ assert.equal(code, 0);
1173
+ assert.deepEqual(json.reaped, []);
1174
+ assert.equal(json.kept.length, 1);
1175
+ assert.equal(json.kept[0].branch, "feature/merged");
1176
+ assert.match(json.kept[0].reason, /^worktree .* status warned, listing may be incomplete: /);
1177
+ assert.match(json.kept[0].reason, /could not open directory 'wip\/': Permission denied$/, "git's own warning must reach the reason, and end it");
1178
+ assert.match(stderr, /KEEP feature\/merged/);
1179
+ assert.equal(branchExists(w, "feature/merged"), true);
1180
+ assert.equal(existsSync(wt), true, "a worktree git could not finish reading must survive");
1181
+ });
1182
+
1183
+ test("ambient git noise on the `--ignored` probe's stderr does not strand a clean worktree (#625)", (t) => {
1184
+ // The gate's other failure direction, and the one a plain `[ -n "$gp_err" ]`
1185
+ // walks straight into: a global gitconfig with a key outside any section
1186
+ // makes EVERY git command print this at rc 0 — the same fault this file's
1187
+ // rev-parse probe is redirected for — while leaving the listing COMPLETE.
1188
+ // Gated on stderr merely existing, every worktree outside `.worktrees/` is
1189
+ // kept for as long as the operator's config stays broken, with a reason
1190
+ // blaming the worktree for a fault in ~/.gitconfig.
1191
+ const w = repo(t);
1192
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "noisy"));
1193
+
1194
+ const bin = failOnlyShim(
1195
+ t,
1196
+ IGNORED_PROBE,
1197
+ ["error: key does not contain a section: stray"],
1198
+ 0,
1199
+ );
1200
+
1201
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1202
+
1203
+ assertShimFired(bin, "the noise never reached the `--ignored` gate — the rest of this arm passes on any fixture");
1204
+ assert.equal(code, 0);
1205
+ assert.deepEqual(json.kept, [], "noise that left the listing whole must not keep this branch");
1206
+ assert.deepEqual(json.reaped, ["feature/merged"]);
1207
+ assert.doesNotMatch(stderr, /listing may be incomplete/, "a complete listing must never be reported as incomplete");
1208
+ assert.equal(branchExists(w, "feature/merged"), false);
1209
+ assert.equal(existsSync(wt), false);
1210
+ });
1211
+
1212
+ test("an `--ignored` probe that DIES is kept with git's own message, not just a label (#625)", (t) => {
1213
+ // Sibling of the plain probe's rc-128 test above, for the branch this file
1214
+ // had no coverage of at all: the rc check on the `--ignored` probe. The keep
1215
+ // is unconditional either way, so what is at stake is only the diagnostic
1216
+ // text — which is the entire thing #625 exists to preserve.
1217
+ const w = repo(t);
1218
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "outside-dead"));
1219
+
1220
+ const bin = failOnlyShim(
1221
+ t,
1222
+ IGNORED_PROBE,
1223
+ ["fatal: unable to read index file .git/index"],
1224
+ 128,
1225
+ );
1226
+
1227
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1228
+
1229
+ assert.equal(code, 0, "an unanswerable probe is not a script failure");
1230
+ assert.deepEqual(json.reaped, []);
1231
+ assert.equal(json.kept.length, 1);
1232
+ assert.equal(json.kept[0].branch, "feature/merged");
1233
+ assert.equal(
1234
+ json.kept[0].reason,
1235
+ `worktree ${wt} unreadable (git status --ignored failed): fatal: unable to read index file .git/index`,
1236
+ "git's message must reach the reason whole — and the reason must not trail a separator or a space",
1237
+ );
1238
+ assert.match(stderr, /KEEP feature\/merged/);
1239
+ assert.equal(branchExists(w, "feature/merged"), true);
1240
+ assert.equal(existsSync(wt), true);
1241
+ });
1242
+
1243
+ test("the branchless sweep's status probe reports git's own message when it dies, too (#625)", (t) => {
1244
+ // The third call site. The branch sweep's two probes got #625 coverage; this
1245
+ // copy — the one the detached/branchless sweep runs, and the only probe a
1246
+ // worktree that wandered off its branch is ever measured by — got none, so a
1247
+ // regression here reverted silently under a green suite.
1248
+ const w = repo(t);
1249
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
1250
+
1251
+ const bin = failOnlyShim(
1252
+ t,
1253
+ STATUS_PROBE,
1254
+ ["fatal: not a git repository: /some/admin/path"],
1255
+ 128,
1256
+ );
1257
+
1258
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1259
+
1260
+ assert.equal(code, 0, "an unanswerable probe is not a script failure");
1261
+ assert.deepEqual(json.worktreesRemoved, []);
1262
+ assert.equal(json.kept.length, 1);
1263
+ assert.equal(json.kept[0].branch, null, "the branchless sweep has no branch to name");
1264
+ assert.equal(
1265
+ json.kept[0].reason,
1266
+ `worktree ${wt} could not be read: fatal: not a git repository: /some/admin/path`,
1267
+ "git's message must reach the reason whole — and the reason must not trail a separator or a space",
1268
+ );
1269
+ assert.match(stderr, /KEEP \(no branch\)/);
1270
+ assert.equal(existsSync(wt), true, "a worktree that could not be read must survive");
1271
+ });
1272
+
1273
+ test("the branchless sweep keeps a worktree whose status walk was cut short, too (#625)", (t) => {
1274
+ // The third call site's copy of the gate, on the same rc-0 shape the branch
1275
+ // sweep's copy is pinned against above. Without it a detached worktree whose
1276
+ // walk git could not finish reads as clean here as well, and this sweep
1277
+ // removes the directory outright — there is no branch left to keep as a
1278
+ // second chance.
1279
+ const w = repo(t);
1280
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
1281
+
1282
+ const bin = failOnlyShim(
1283
+ t,
1284
+ STATUS_PROBE,
1285
+ ["warning: could not open directory 'wip/': Permission denied"],
1286
+ 0,
1287
+ );
1288
+
1289
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
1290
+
1291
+ assert.equal(code, 0);
1292
+ assert.deepEqual(json.worktreesRemoved, [], "a walk git could not finish is not grounds to remove");
1293
+ assert.equal(json.kept.length, 1);
1294
+ assert.equal(json.kept[0].branch, null);
1295
+ assert.equal(
1296
+ json.kept[0].reason,
1297
+ `worktree ${wt} status warned, listing may be incomplete: warning: could not open directory 'wip/': Permission denied`,
1298
+ );
1299
+ assert.match(stderr, /KEEP \(no branch\)/);
1300
+ assert.equal(existsSync(wt), true);
1301
+ });
1302
+
1303
+ test("a [gone] branch whose worktree directory was deleted by hand is reaped, never kept as dirty (#83)", (t) => {
1304
+ // The bug: `|| echo dirty` folds ANY failed status — including one that
1305
+ // failed because the directory is not there at all — into "dirty", pinning
1306
+ // the branch forever. A deleted worktree holds nothing to protect.
1307
+ const w = repo(t);
1308
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1309
+ rmSync(wt, { recursive: true, force: true });
1310
+ assert.match(git(w, "worktree", "list"), /feature\/merged/, "fixture: the stale registration must still be listed");
1311
+
1312
+ const { code, json } = runReap(w, ["--apply"]);
1313
+
1314
+ assert.equal(code, 0);
1315
+ assert.deepEqual(json.reaped, ["feature/merged"], "a directory that is not there holds no work to protect");
1316
+ assert.deepEqual(json.kept, []);
1317
+ assert.equal(branchExists(w, "feature/merged"), false);
1318
+ assert.doesNotMatch(git(w, "worktree", "list"), /feature\/merged/, "the stale registration must not survive the run");
1319
+ });
1320
+
1321
+ test("a dry run and --apply agree about a deleted worktree directory (#128)", (t) => {
1322
+ const w = repo(t);
1323
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1324
+ rmSync(wt, { recursive: true, force: true });
1325
+
1326
+ const dry = runReap(w, []);
1327
+ assert.equal(dry.code, 0);
1328
+ assert.deepEqual(dry.json.reaped, ["feature/merged"], "a dry run must predict the same outcome --apply produces");
1329
+ assert.deepEqual(dry.json.kept, []);
1330
+
1331
+ const applied = runReap(w, ["--apply"]);
1332
+ assert.deepEqual(applied.json.reaped, ["feature/merged"]);
1333
+ });
1334
+
1335
+ test("a [gone] branch checked out in the MAIN checkout is kept, with the reason that is true", (t) => {
1336
+ // The enumeration does not exclude the main worktree: `worktree list
1337
+ // --porcelain` emits a `branch refs/heads/...` line for it, so a [gone]
1338
+ // branch checked out there binds $wt to the main checkout. Its `.git` is a
1339
+ // DIRECTORY, so the `-f` linkage guard read it as "no .git linkage" — false;
1340
+ // git answers about that repo correctly through it. Both halves matter and
1341
+ // are asserted separately: the reason must be true, and the dry run must not
1342
+ // promise a reap that `git worktree remove` and `git branch -D` both refuse.
1343
+ const w = repo(t);
1344
+ mergedGoneBranch(w, "feature/merged", "merged work");
1345
+ git(w, "checkout", "-q", "feature/merged");
1346
+
1347
+ const dry = runReap(w, []);
1348
+ const applied = runReap(w, ["--apply"]);
1349
+
1350
+ for (const { json } of [dry, applied]) {
1351
+ assert.deepEqual(json.reaped, []);
1352
+ assert.equal(json.kept.length, 1);
1353
+ assert.equal(json.kept[0].branch, "feature/merged");
1354
+ assert.match(json.kept[0].reason, /is the main checkout/);
1355
+ assert.doesNotMatch(json.kept[0].reason, /no \.git linkage/, "git answers correctly through a .git directory");
1356
+ }
1357
+ assert.deepEqual(dry.json.kept, applied.json.kept, "a dry run must predict what --apply produces");
1358
+ assert.equal(branchExists(w, "feature/merged"), true);
1359
+ });
1360
+
1361
+ test("a worktree behind an unreadable parent is kept, never reaped as clean", (t) => {
1362
+ if (process.getuid?.() === 0) return t.skip("root reads every directory");
1363
+ const w = repo(t);
1364
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1365
+ writeFileSync(join(wt, "precious.txt"), "work that exists nowhere else\n");
1366
+ const parent = join(w, ".worktrees");
1367
+
1368
+ chmodSync(parent, 0o000);
1369
+ const { code, json, stderr } = runReap(w, ["--apply"]);
1370
+ chmodSync(parent, 0o755);
1371
+
1372
+ assert.equal(code, 0);
1373
+ assert.deepEqual(json.reaped, []);
1374
+ assert.equal(json.kept.length, 1);
1375
+ assert.equal(json.kept[0].branch, "feature/merged");
1376
+ assert.match(json.kept[0].reason, /cannot tell whether worktree/);
1377
+ assert.doesNotMatch(json.kept[0].reason, /dirty/, "an unanswerable probe must not be misreported as a dirty one");
1378
+ assert.match(stderr, /KEEP feature\/merged — cannot tell whether worktree/);
1379
+ assert.equal(branchExists(w, "feature/merged"), true);
1380
+ assert.equal(readFileSync(join(wt, "precious.txt"), "utf8"), "work that exists nowhere else\n");
1381
+ });
1382
+
1383
+
1384
+ test("a worktree with no surviving ancestor below / is reaped, never kept as unanswerable (#178)", (t) => {
1385
+ // The escalation of the case above: there the parent could not be SEARCHED,
1386
+ // which is genuinely unknown and must keep. Here every ancestor below `/` is
1387
+ // absent — but `${p%/*}` on `/x` yields the empty string rather than `/`, so
1388
+ // the walk fell out on "" and `[ -x "" ]` answered unknown for a path that is
1389
+ // provably absent with a searchable root. That kept a merged branch forever
1390
+ // on a directory holding nothing, which is the refusal `gone` exists to end.
1391
+ const w = repo(t);
1392
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1393
+ const dest = relocate(w, wt, "/nonexistent-top-level-178/wt");
1394
+
1395
+ const { code, json, stderr } = runReap(w, ["--apply"]);
1396
+
1397
+ assert.equal(code, 0);
1398
+ assert.deepEqual(json.reaped, ["feature/merged"]);
1399
+ assert.deepEqual(json.kept, [], `an absent path with a searchable root is not an unknown one: ${JSON.stringify(json.kept)}`);
1400
+ // The keep's own wording, not just an empty `kept`: any other keep reason
1401
+ // would also leave `reaped` short, so the pair alone does not say which
1402
+ // question was answered wrong.
1403
+ assert.doesNotMatch(stderr, /cannot tell whether worktree/);
1404
+ assert.ok(!stderr.includes(`dirty worktree ${dest}`), "and it is never guessed dirty either");
1405
+ assert.equal(branchExists(w, "feature/merged"), false);
1406
+ });
1407
+
1408
+ test("a worktree whose .git file is gone is kept, never reaped as clean (#128)", (t) => {
1409
+ // The directory EXISTS (so a bare `[ -e ]` says present) and `git -C` does
1410
+ // not fail on a missing `.git` — it walks UP to the enclosing repo and
1411
+ // answers about THAT at rc 0. `.worktrees/` gitignored and the parent clean
1412
+ // makes the leaked answer empty: a positive "clean" produced without ever
1413
+ // looking at the worktree, which the old code would have reaped on.
1414
+ const w = repo(t);
1415
+ writeFileSync(join(w, ".gitignore"), ".worktrees/\n");
1416
+ git(w, "add", ".gitignore");
1417
+ git(w, "commit", "-q", "-m", "ignore the worktrees dir");
1418
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1419
+ writeFileSync(join(wt, "precious.txt"), "work that exists nowhere else\n");
1420
+ rmSync(join(wt, ".git"));
1421
+ assert.equal(git(w, "status", "--porcelain"), "", "fixture: the leaked answer really is an empty one");
1422
+
1423
+ const { code, json, stderr } = runReap(w, ["--apply"]);
1424
+
1425
+ assert.equal(code, 0);
1426
+ assert.deepEqual(json.reaped, []);
1427
+ assert.equal(json.kept.length, 1);
1428
+ assert.equal(json.kept[0].branch, "feature/merged");
1429
+ assert.match(json.kept[0].reason, /no \.git linkage/);
1430
+ assert.equal(branchExists(w, "feature/merged"), true);
1431
+ assert.equal(existsSync(wt), true, "the worktree directory and its work must survive untouched");
1432
+ assert.equal(readFileSync(join(wt, "precious.txt"), "utf8"), "work that exists nowhere else\n");
1433
+ });
1434
+
1435
+ test("a worktree whose .git is a dangling symlink is kept, never reaped as clean (#128)", (t) => {
1436
+ const w = repo(t);
1437
+ writeFileSync(join(w, ".gitignore"), ".worktrees/\n");
1438
+ git(w, "add", ".gitignore");
1439
+ git(w, "commit", "-q", "-m", "ignore the worktrees dir");
1440
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1441
+ rmSync(join(wt, ".git"));
1442
+ symlinkSync(join(wt, "nowhere"), join(wt, ".git"));
1443
+
1444
+ const { json } = runReap(w, ["--apply"]);
1445
+
1446
+ assert.deepEqual(json.reaped, []);
1447
+ assert.equal(json.kept.length, 1);
1448
+ assert.match(json.kept[0].reason, /no \.git linkage/);
1449
+ assert.equal(branchExists(w, "feature/merged"), true);
1450
+ });
1451
+
1452
+ // #2042. A `.git` that exists as a regular file is not yet a `.git` that
1453
+ // answers for `$wt`: two shapes keep the file well-formed and move git's
1454
+ // WORKING TREE elsewhere, so the dirty check reads that other tree, calls it
1455
+ // clean over the work sitting in `$wt`, and the dry run promised a removal
1456
+ // that `--apply` then could not perform (measured before the fix: both shapes,
1457
+ // both sweeps, `would remove worktree` in the dry run, `worktree remove
1458
+ // refused` under `--apply`). Each fixture below is also the control for the
1459
+ // other sweep's copy of the guard — the two are separately duplicated in the
1460
+ // script, so one sweep's fix leaves the other's matrix rows red.
1461
+
1462
+ /**
1463
+ * Redirect git's working tree for `wt` away from it, then plant uncommitted
1464
+ * work in `wt` that the redirect hides. Returns the directory git now answers
1465
+ * for, spelled exactly as `--show-toplevel` prints it.
1466
+ *
1467
+ * c2 — `wt/.git` rewritten to name a foreign git dir NOT called `.git`, whose
1468
+ * `core.worktree` is a clean checkout elsewhere.
1469
+ * b2 — `wt/.git` untouched; `extensions.worktreeConfig` on, and one
1470
+ * `git config --worktree core.worktree <elsewhere>` in `wt` itself.
1471
+ * nl — b2, but `<elsewhere>` is `wt`'s own canonical path plus a trailing
1472
+ * newline byte: a real, distinct directory whose name `$(...)` would
1473
+ * strip back to `wt`'s own, so a compare built on bare command
1474
+ * substitution reads the redirect as a match.
1475
+ */
1476
+ function redirectWorkingTree(w, wt, shape) {
1477
+ let elsewhere;
1478
+ if (shape === "nl") {
1479
+ elsewhere = `${realpathSync(wt)}\n`;
1480
+ mkdirSync(elsewhere);
1481
+ } else {
1482
+ elsewhere = join(w, "..", "elsewhere");
1483
+ execFileSync("git", ["clone", "-q", join(w, "..", "origin.git"), elsewhere], { env: ENV });
1484
+ }
1485
+ if (shape === "c2") {
1486
+ const foreign = join(w, "..", "foreign-gitdir");
1487
+ renameSync(join(elsewhere, ".git"), foreign);
1488
+ execFileSync("git", ["--git-dir", foreign, "config", "core.worktree", elsewhere], { env: ENV });
1489
+ writeFileSync(join(wt, ".git"), `gitdir: ${foreign}\n`);
1490
+ } else {
1491
+ git(w, "config", "extensions.worktreeConfig", "true");
1492
+ git(wt, "config", "--worktree", "core.worktree", elsewhere);
1493
+ }
1494
+ writeFileSync(join(wt, "precious.txt"), "work that exists nowhere else\n");
1495
+ assert.equal(git(wt, "status", "--porcelain", "-uall"), "", `fixture (${shape}): the redirect must hide the planted work from the dirty check`);
1496
+ // Untrimmed, unlike `git()`: the `nl` shape's whole point is a byte a trim eats.
1497
+ const top = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: wt, env: ENV, encoding: "utf8" }).slice(0, -1);
1498
+ assert.equal(top, shape === "nl" ? elsewhere : realpathSync(elsewhere), `fixture (${shape}): git must answer for the other tree`);
1499
+ assert.notEqual(top, realpathSync(wt), `fixture (${shape}): and that tree must not be the worktree's own`);
1500
+ return top;
1501
+ }
1502
+
1503
+ for (const shape of ["c2", "b2", "nl"]) {
1504
+ for (const sweep of ["[gone]-branch", "branchless"]) {
1505
+ test(`a worktree whose working tree is redirected (${shape}) is kept by the ${sweep} sweep, dry run and --apply alike (#2042)`, (t) => {
1506
+ const w = repo(t);
1507
+ const branchless = sweep === "branchless";
1508
+ const wt = branchless
1509
+ ? detachedMergedWorktree(w, "docs/79-brief", "work that landed")
1510
+ : mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1511
+ const top = redirectWorkingTree(w, wt, shape);
1512
+
1513
+ for (const args of [[], ["--apply"]]) {
1514
+ const mode = args.length ? "--apply" : "dry run";
1515
+ const { code, json, stderr } = runReap(w, args);
1516
+
1517
+ assert.equal(code, 0, `${mode}: ${stderr}`);
1518
+ assert.deepEqual(json.worktreesRemoved, [], `${mode}: the redirected worktree must not be promised or removed`);
1519
+ assert.doesNotMatch(stderr, /would remove worktree|REMOVED worktree/, `${mode}: ${stderr}`);
1520
+ const mine = json.kept.filter((k) => k.reason.includes(wt));
1521
+ assert.equal(mine.length, 1, `${mode}: exactly one keep must name the worktree: ${JSON.stringify(json.kept)}`);
1522
+ assert.equal(mine[0].branch, branchless ? null : "feature/merged");
1523
+ // Refused by the linkage guard itself, not by `git worktree remove`'s
1524
+ // own backstop further down — which only --apply reaches, and which is
1525
+ // why the dry run used to promise what --apply then kept.
1526
+ assert.match(mine[0].reason, /linkage/, `${mode}: ${mine[0].reason}`);
1527
+ assert.ok(mine[0].reason.includes(top), `${mode}: the reason must name where the linkage resolves: ${mine[0].reason}`);
1528
+ assert.doesNotMatch(mine[0].reason, /worktree remove refused/, mode);
1529
+ if (!branchless) assert.deepEqual(json.reaped, [], `${mode}: the branch goes nowhere its worktree cannot`);
1530
+ }
1531
+
1532
+ assert.equal(readFileSync(join(wt, "precious.txt"), "utf8"), "work that exists nowhere else\n");
1533
+ assert.match(git(w, "worktree", "list", "--porcelain"), new RegExp(`^worktree ${wt.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`, "m"));
1534
+ if (!branchless) assert.equal(branchExists(w, "feature/merged"), true);
1535
+ });
1536
+ }
1537
+ }
1538
+
1539
+ /**
1540
+ * A merged worktree — a `[gone]` branch's, or a detached one for the
1541
+ * branchless sweep — that `worktree list --porcelain` names by a different
1542
+ * SPELLING than git's own `--show-toplevel` answer: one directory, two byte
1543
+ * strings. Returns `{ wt, cwd }`: the listed spelling reap.sh acts on, and the
1544
+ * directory to run it from when the run must stand inside the worktree —
1545
+ * `wt` itself, or with `nested` a detached worktree inside it holding
1546
+ * uncommitted work (#1441's shape; `ignoreNestedWorktrees` keeps it out of the
1547
+ * outer one's dirty check).
1548
+ *
1549
+ * symlink — `.worktrees` moved aside and symlinked back: the listing keeps
1550
+ * the path recorded at `worktree add` time, git answers canonical
1551
+ * (#2042).
1552
+ * nfd — the worktree's name is `cafe` + U+0301 COMBINING ACUTE ACCENT.
1553
+ * Where the filesystem also resolves the precomposed spelling to
1554
+ * that directory (APFS), the `core.precomposeunicode` `git clone`
1555
+ * writes there lists it precomposed while `--show-toplevel`
1556
+ * answers the on-disk NFD bytes (#2072). Where it does not
1557
+ * (ext4), the two spellings are two names, both answers are the
1558
+ * NFD bytes, and this row is the plain case — which is why the
1559
+ * symlink row exists beside it: it reaches the same compare on
1560
+ * every filesystem.
1561
+ */
1562
+ function respelledWorktree(w, sweep, spelling, { nested = false } = {}) {
1563
+ const branchless = sweep === "branchless";
1564
+ const make = branchless ? detachedMergedWorktree : mergedGoneBranchWithWorktree;
1565
+ const name = branchless ? "docs/79-brief" : "feature/merged";
1566
+ if (nested) ignoreNestedWorktrees(w);
1567
+ const addNested = (outer) => {
1568
+ if (!nested) return outer;
1569
+ const inner = join(outer, "nested");
1570
+ git(w, "worktree", "add", "-q", "--detach", inner, "main");
1571
+ writeFileSync(join(inner, "wip.txt"), "work that exists nowhere else\n");
1572
+ return inner;
1573
+ };
1574
+ const listing = () => git(w, "worktree", "list", "--porcelain").split("\n").filter((l) => l.startsWith("worktree ")).map((l) => l.slice(9));
1575
+
1576
+ if (spelling === "symlink") {
1577
+ const wt = make(w, name, "merged work");
1578
+ const cwd = addNested(wt);
1579
+ renameSync(join(w, ".worktrees"), join(w, ".worktrees-real"));
1580
+ symlinkSync(".worktrees-real", join(w, ".worktrees"));
1581
+ assert.notEqual(realpathSync(wt), wt, "fixture: the listed path must not be canonical");
1582
+ assert.ok(listing().includes(wt), "fixture: git must list it through the symlink");
1583
+ return { wt, cwd };
1584
+ }
1585
+
1586
+ const onDisk = join(w, ".worktrees", "cafe\u0301");
1587
+ mkdirSync(onDisk, { recursive: true });
1588
+ make(w, name, "merged work", onDisk);
1589
+ const wt = listing().find((p) => p.normalize("NFC") === onDisk.normalize("NFC"));
1590
+ assert.ok(wt, `fixture: git must list the worktree: ${listing()}`);
1591
+ assert.equal(git(onDisk, "rev-parse", "--show-toplevel"), onDisk, "fixture: git must answer the on-disk NFD bytes");
1592
+ if (existsSync(onDisk.normalize("NFC"))) {
1593
+ assert.equal(wt, onDisk.normalize("NFC"), "fixture: a filesystem that aliases the two spellings must list the precomposed one");
1594
+ assert.notEqual(wt, onDisk, "fixture: so the listing and git's answer differ byte for byte");
1595
+ }
1596
+ return { wt, cwd: addNested(wt) };
1597
+ }
1598
+
1599
+ for (const spelling of ["symlink", "nfd"]) {
1600
+ for (const sweep of ["[gone]-branch", "branchless"]) {
1601
+ test(`a healthy worktree listed under another spelling (${spelling}) still reaps in the ${sweep} sweep (#2042, #2072)`, (t) => {
1602
+ // The accept side of the compare above: a string compare refuses every
1603
+ // healthy worktree in either layout, forever, and names the directory
1604
+ // itself as the tree its linkage "answers for" instead.
1605
+ const w = repo(t);
1606
+ const { wt } = respelledWorktree(w, sweep, spelling);
1607
+
1608
+ const dry = runReap(w, []);
1609
+ assert.equal(dry.code, 0, dry.stderr);
1610
+ assert.deepEqual(dry.json.kept, [], `nothing here is a finding: ${JSON.stringify(dry.json.kept)}`);
1611
+ assert.deepEqual(dry.json.worktreesRemoved, [wt]);
1612
+
1613
+ const { code, json, stderr } = runReap(w, ["--apply"]);
1614
+ assert.equal(code, 0, stderr);
1615
+ assert.deepEqual(json.kept, []);
1616
+ assert.deepEqual(json.worktreesRemoved, [wt]);
1617
+ assert.equal(existsSync(wt), false, "the directory itself must be gone");
1618
+ if (sweep !== "branchless") assert.equal(branchExists(w, "feature/merged"), false);
1619
+ });
1620
+ }
1621
+ }
1622
+
1623
+ // The cwd-delete guard (#992, #1441) matched the listed `$wt` against git's
1624
+ // `--show-toplevel` for the cwd by string prefix, so the same two spellings
1625
+ // hid the worktree a run stands in from it and `--apply` deleted its own cwd:
1626
+ // `REMOVED worktree`, then every later git call dead on "Unable to read current
1627
+ // working directory", exit 2 (measured on both layouts). Under a string
1628
+ // linkage compare the NFD worktree never got this far; it does now.
1629
+ for (const spelling of ["symlink", "nfd"]) {
1630
+ for (const [sweep, nested] of [["[gone]-branch", false], ["branchless", false], ["[gone]-branch", true]]) {
1631
+ const where = nested ? "a worktree nested inside it" : "it";
1632
+ test(`a run standing in ${where} keeps a worktree listed under another spelling (${spelling}, ${sweep} sweep, #2072)`, (t) => {
1633
+ const w = repo(t);
1634
+ const { wt, cwd } = respelledWorktree(w, sweep, spelling, { nested });
1635
+
1636
+ for (const args of [[], ["--apply"]]) {
1637
+ const mode = args.length ? "--apply" : "dry run";
1638
+ const { code, json, stderr } = runReap(cwd, args);
1639
+ assert.equal(code, 0, `${mode}: ${stderr}`);
1640
+ assert.deepEqual(json.worktreesRemoved, [], `${mode}: the worktree holding cwd must not be promised or removed`);
1641
+ const mine = json.kept.find((k) => k.reason.startsWith(`worktree ${wt} `));
1642
+ assert.ok(mine, `${mode}: the worktree must be its own finding: ${JSON.stringify(json.kept)}`);
1643
+ assert.match(mine.reason, /holds the working directory this run was started in/, mode);
1644
+ }
1645
+ assert.equal(existsSync(cwd), true);
1646
+ if (nested) assert.equal(readFileSync(join(cwd, "wip.txt"), "utf8"), "work that exists nowhere else\n");
1647
+ if (sweep !== "branchless") assert.equal(branchExists(w, "feature/merged"), true);
1648
+ });
1649
+ }
1650
+ }
1651
+
1652
+ for (const sweep of ["[gone]-branch", "branchless"]) {
1653
+ test(`an unsearchable worktree is kept with git's own denial, not a linkage cause the compare invented (${sweep} sweep, #2042)`, (t) => {
1654
+ // The `-f` gate in front of the #2042 compare is what keeps this reason
1655
+ // git's: `-f "$wt/.git"` is false when `$wt` cannot be searched, so the
1656
+ // compare stands aside and the status probe reports the denial. Without
1657
+ // the gate the compare's own `cd` fails first and the keep blames a
1658
+ // linkage nothing ever looked at.
1659
+ const w = repo(t);
1660
+ const branchless = sweep === "branchless";
1661
+ const wt = branchless
1662
+ ? detachedMergedWorktree(w, "docs/79-brief", "work that landed")
1663
+ : mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1664
+
1665
+ chmodSync(wt, 0o000);
1666
+ const { code, json, stderr } = runReap(w, []);
1667
+ chmodSync(wt, 0o755);
1668
+
1669
+ assert.equal(code, 0, stderr);
1670
+ assert.deepEqual(json.worktreesRemoved, []);
1671
+ const mine = json.kept.filter((k) => k.reason.includes(wt));
1672
+ assert.equal(mine.length, 1, JSON.stringify(json.kept));
1673
+ assert.match(mine[0].reason, /could not be read: .*Permission denied/);
1674
+ assert.doesNotMatch(mine[0].reason, /linkage/);
1675
+ });
1676
+ }
1677
+
1678
+ test("a non-fleet worktree holding an ignored file is kept, never reaped", (t) => {
1679
+ // The one keep the worktree-present branch owns that nothing else here
1680
+ // reaches. `git worktree remove` refuses on modified and untracked files but
1681
+ // deletes IGNORED ones silently, so outside `.worktrees/` — where an ignored
1682
+ // file is a .env or a scratch note that exists nowhere else — the
1683
+ // `--ignored` probe is the only thing left between a merged, linked,
1684
+ // tracked-clean worktree and `git branch -D`. Every earlier guard passes by
1685
+ // construction, which is what makes this test see that probe and only it.
1686
+ const w = repo(t);
1687
+ writeFileSync(join(w, ".gitignore"), ".env\n");
1688
+ git(w, "add", ".gitignore");
1689
+ commit(w, "ignore .env");
1690
+ git(w, "push", "-q", "origin", "main");
1691
+ // Deliberately NOT under `.worktrees/`: that home is what the case statement
1692
+ // keys the fleet exemption on, and a fleet worktree is reaped WITH its
1693
+ // machine-generated ignored files.
1694
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "outside"));
1695
+ writeFileSync(join(wt, ".env"), "SECRET=exists nowhere else\n");
1696
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so only the --ignored probe can keep it");
1697
+
1698
+ const { code, json } = runReap(w, ["--apply"]);
1699
+
1700
+ assert.equal(code, 0);
1701
+ assert.deepEqual(json.reaped, []);
1702
+ assert.equal(json.kept.length, 1);
1703
+ assert.equal(json.kept[0].branch, "feature/merged");
1704
+ // The reason, not just the keep: every other guard in this branch also
1705
+ // leaves `reaped` empty, so the pair alone does not say which one answered.
1706
+ assert.match(json.kept[0].reason, /^ignored files present in .*: \.env$/);
1707
+ assert.equal(branchExists(w, "feature/merged"), true);
1708
+ assert.equal(readFileSync(join(wt, ".env"), "utf8"), "SECRET=exists nowhere else\n", "the precious file must survive the run");
1709
+ });
1710
+
1711
+ test("a non-fleet worktree with NO ignored file is reaped — the control for the case above", (t) => {
1712
+ // Without this, the test above passes on a reap.sh that keeps every
1713
+ // non-fleet worktree unconditionally: it would be pinning the `.worktrees/`
1714
+ // arm of the case, not the `--ignored` probe inside it. Same fixture, one
1715
+ // difference — the ignored file — and the opposite verdict.
1716
+ //
1717
+ // It is also the exit-status control for this branch. Reached with
1718
+ // `$ignored` empty, the `if [ -n "$ignored" ]` is the last command of the
1719
+ // worktree-present branch, and a condition that tests false leaves an `if`
1720
+ // with no `else` at status 0. Under `set -eu` any other answer would abort
1721
+ // the sweep here, after the earlier branches were already deleted.
1722
+ const w = repo(t);
1723
+ writeFileSync(join(w, ".gitignore"), ".env\n");
1724
+ git(w, "add", ".gitignore");
1725
+ commit(w, "ignore .env");
1726
+ git(w, "push", "-q", "origin", "main");
1727
+ // Deliberately NOT under `.worktrees/`, same as the case above.
1728
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "outside"));
1729
+ // and NO .env written this time
1730
+
1731
+ const { code, json } = runReap(w, ["--apply"]);
1732
+
1733
+ assert.equal(code, 0, "the sweep must not abort under set -eu on the branch's own last command");
1734
+ assert.deepEqual(json.reaped, ["feature/merged"]);
1735
+ assert.deepEqual(json.kept, []);
1736
+ assert.equal(branchExists(w, "feature/merged"), false);
1737
+ assert.equal(existsSync(wt), false, "the worktree directory goes with it");
1738
+ });
1739
+
1740
+ test("a FLEET worktree under `.worktrees/` is reaped, ignored file and all", (t) => {
1741
+ // The other arm of `case "$wt" in */.worktrees/*) : ;; *) ...ignored-check... ;; esac`.
1742
+ // The pair above reaches the `--ignored` keep from OUTSIDE that home, so both
1743
+ // pin the `*)` arm; nothing pinned the exemption itself. Measured BEFORE this
1744
+ // test existed: mutating the pattern to one that never matches — routing every
1745
+ // fleet worktree through the keep and stranding all of them, the regression the
1746
+ // comment at reap.sh's case statement warns about — left this file 37/37 green.
1747
+ // It now fails here, and only here.
1748
+ const w = repo(t);
1749
+ writeFileSync(join(w, ".gitignore"), ".env\n");
1750
+ git(w, "add", ".gitignore");
1751
+ commit(w, "ignore .env");
1752
+ git(w, "push", "-q", "origin", "main");
1753
+ // The home is the ONLY difference from the pair above: same ignored file, same
1754
+ // tracked-clean worktree, opposite verdict.
1755
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1756
+ writeFileSync(join(wt, ".env"), "AGENT_TEST=machine-generated\n");
1757
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so only the --ignored probe could keep it");
1758
+ assert.match(git(wt, "status", "--porcelain", "--ignored"), /^!! \.env$/m, "fixture: the file really is ignored, or the exemption is untested");
1759
+
1760
+ const { code, json } = runReap(w, ["--apply"]);
1761
+
1762
+ assert.equal(code, 0);
1763
+ assert.deepEqual(json.reaped, ["feature/merged"]);
1764
+ assert.deepEqual(json.kept, []);
1765
+ assert.equal(existsSync(wt), false, "the exemption reaps a fleet worktree WITH its machine-generated ignored files");
1766
+ });
1767
+
1768
+ test("a repo path containing a space still finds and reaps the branch's worktree", (t) => {
1769
+ const w = repo(t, "my repos");
1770
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1771
+
1772
+ const { code, json } = runReap(w, ["--apply"]);
1773
+
1774
+ assert.equal(code, 0);
1775
+ assert.deepEqual(json.reaped, ["feature/merged"]);
1776
+ assert.deepEqual(json.kept, []);
1777
+ assert.equal(existsSync(wt), false);
1778
+ });
1779
+
1780
+ test("a repo path containing a space still finds a dirty worktree and keeps it", (t) => {
1781
+ const w = repo(t, "my repos");
1782
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1783
+ writeFileSync(join(wt, "scratch.txt"), "uncommitted\n");
1784
+
1785
+ const { code, json } = runReap(w, ["--apply"]);
1786
+
1787
+ assert.equal(code, 0);
1788
+ assert.deepEqual(json.reaped, []);
1789
+ assert.equal(json.kept.length, 1);
1790
+ assert.match(json.kept[0].reason, /^dirty worktree /);
1791
+ assert.ok(json.kept[0].reason.includes("/my repos/.worktrees/feature/merged"), json.kept[0].reason);
1792
+ });
1793
+
1794
+ // --- #119: the payload's own string fields.
1795
+ //
1796
+ // `keep()` splices its two arguments raw, and five call sites reach it: the
1797
+ // branch name, `dirty worktree $wt`, `ignored files present in $wt: $ignored`,
1798
+ // the `reaped` accumulator, and `cherry probe failed …: $cherry`, which routes
1799
+ // arbitrary git stderr. The branch name is the demonstrated trigger — measured
1800
+ // on the pre-fix script, an unmerged `[gone]` branch named `feat/has"quote`
1801
+ // produced `{"branch":"feat/has"quote",…}` at exit 0 and `JSON.parse` failed at
1802
+ // position 56. The script's decision was correct throughout; what broke was the
1803
+ // sole machine-readable record of it.
1804
+ test("a quote in a [gone] branch name still emits parseable JSON", (t) => {
1805
+ const w = repo(t);
1806
+ unmergedGoneBranch(w, 'feat/has"quote', "work nobody merged");
1807
+
1808
+ const { code, json, stderr } = runReap(w, []);
1809
+
1810
+ assert.equal(code, 0, "a kept branch is a finding at exit 0, quote or no quote");
1811
+ assert.equal(json.kept.length, 1);
1812
+ assert.equal(json.kept[0].branch, 'feat/has"quote',
1813
+ "the field round-trips to the name that went in — `runReap` JSON.parses stdout, so an unescaped splice fails here before this assert runs");
1814
+ assert.equal(json.kept[0].reason, "unmerged commits");
1815
+ assert.ok(branchExists(w, 'feat/has"quote'), "and it is still there: escaping must not change what gets deleted");
1816
+ assert.match(stderr, /KEEP feat\/has"quote/, "the human line stays raw — it is prose, not JSON");
1817
+ });
1818
+
1819
+ test("git's own stderr reaches the payload escaped, not raw", (t) => {
1820
+ // The fifth interpolation, and the only one that carries text neither this
1821
+ // repo nor its operator chose. Real `git cherry` corruption output happens to
1822
+ // carry no quote, which makes this the least likely of the five to fire —
1823
+ // and the one with the least control over what it splices when it does.
1824
+ const w = repo(t);
1825
+ unmergedGoneBranch(w, "feature/onlyhere", "work");
1826
+ // `failOnlyShim` emits each line through `printf '%s\n'`, so the `"` this test
1827
+ // exists to chase reaches git's stderr as data — the payload has something
1828
+ // real to escape.
1829
+ const bin = failOnlyShim(t, `[ "$1" = cherry ]`, ['error: unable to open loose object "deadbeef cafe": Permission denied'], 128);
1830
+
1831
+ const { code, json } = runReap(w, [], withShim(bin));
1832
+
1833
+ assert.equal(code, 0);
1834
+ assert.match(json.kept[0].reason, /cherry probe failed/);
1835
+ assert.match(json.kept[0].reason, /"deadbeef cafe"/,
1836
+ "the quotes survive as data rather than terminating the JSON string");
1837
+ });
1838
+
1839
+ test("an ordinary branch name is untouched — the escaping accepts what it should", (t) => {
1840
+ // The false-positive half. Nothing here has anything to escape, so the
1841
+ // payload must be exactly what this script has always emitted.
1842
+ const w = repo(t);
1843
+ unmergedGoneBranch(w, "fix/119-json-sh-extract", "work");
1844
+
1845
+ const { code, json } = runReap(w, []);
1846
+
1847
+ assert.equal(code, 0);
1848
+ assert.deepEqual(json, {
1849
+ applied: false,
1850
+ reaped: [],
1851
+ worktreesRemoved: [],
1852
+ kept: [{ branch: "fix/119-json-sh-extract", reason: "unmerged commits" }],
1853
+ warnings: [],
1854
+ });
1855
+ });
1856
+
1857
+ test("a reaped branch name is escaped too — the other accumulator", (t) => {
1858
+ const w = repo(t);
1859
+ mergedGoneBranch(w, 'chore/re"aped', "work that landed");
1860
+
1861
+ const { code, json } = runReap(w, ["--apply"]);
1862
+
1863
+ assert.equal(code, 0);
1864
+ assert.deepEqual(json.reaped, ['chore/re"aped'],
1865
+ "`reaped` is built by its own accumulator, not by keep() — escaping one and not the other leaves half the payload broken");
1866
+ assert.equal(branchExists(w, 'chore/re"aped'), false, "and it really was deleted");
1867
+ });
1868
+
1869
+ // `.` is a POSIX special builtin, so failing to open its operand aborts a
1870
+ // non-interactive shell before any `||` on the line can run. This script's
1871
+ // contract is exit 0 or exit 2 with no exit 1 at all (#265), and the guard sits
1872
+ // ahead of the fetch, so a missing library refuses before anything is deleted.
1873
+ test("a missing json.sh is exit 2, before any branch is deleted", (t) => {
1874
+ const w = repo(t);
1875
+ mergedGoneBranch(w, "chore/landed", "work that landed");
1876
+ const lone = mkdtempSync(join(tmpdir(), "reap-nolib-"));
1877
+ t.after(() => rmSync(lone, { recursive: true, force: true }));
1878
+ copyFileSync(SCRIPT, join(lone, "reap.sh"));
1879
+
1880
+ const r = spawnSync("sh", [join(lone, "reap.sh"), "--apply"], { cwd: w, env: ENV, encoding: "utf8" });
1881
+
1882
+ assert.equal(r.status, 2, "a missing library is a refusal — this script has no exit 1 to be confused with");
1883
+ assert.match(r.stderr, /json\.sh/, "and it names the file rather than blaming the fetch or the base ref");
1884
+ assert.equal(r.stdout, "", "no payload: nothing happened");
1885
+ assert.ok(branchExists(w, "chore/landed"),
1886
+ "and the branch is still there — the guard fires ahead of every deletion, so this is a clean refusal");
1887
+ });
1888
+
1889
+ // --- #391: the reason a keep carries, on the three calls that derived it from
1890
+ // an exit code and sent git's own diagnosis to /dev/null.
1891
+ //
1892
+ // Measured before this suite existed, by mutating each arm and re-running the
1893
+ // file: garbling the `worktree remove` reason and garbling the `branch -D`
1894
+ // reason each left all 24 tests green. Both arms were invisible.
1895
+
1896
+ /**
1897
+ * Put a symlink where the worktree directory was, keeping the registration
1898
+ * pointed at the symlink's path — the shape that makes `git worktree remove`
1899
+ * fail AFTER it has already cleared the admin entry.
1900
+ *
1901
+ * Measured, git 2.50.1 (Apple Git-155): rc 255,
1902
+ * `error: failed to delete '<wt>': Not a directory`, the porcelain no longer
1903
+ * lists the entry, and both the symlink and its target survive on disk.
1904
+ *
1905
+ * Chosen over a `chmod 555` parent, which produces the same deregistered state
1906
+ * by a different route: this one reproduces as any user, needs no permission
1907
+ * bits, and so carries none of the euid-0 vacuity the `0o000` fixtures in this
1908
+ * file already have to skip around (#184). Every guard ahead of the removal
1909
+ * still passes through it — `.git` is a regular file and `git -C` follows the
1910
+ * link, so the linkage guard and the status probe both answer about the real
1911
+ * worktree.
1912
+ */
1913
+ function symlinkStandIn(wt) {
1914
+ const real = `${wt}-real`;
1915
+ renameSync(wt, real);
1916
+ symlinkSync(real, wt);
1917
+ return real;
1918
+ }
1919
+
1920
+ const withShim = (bin) => ({ PATH: `${bin}:${ENV.PATH}` });
1921
+
1922
+ // Every shim test above and below routes through this helper, and gross damage
1923
+ // here fails LOUDLY: drop the tail and every one of them goes red, reverse the
1924
+ // order and all but one does — the shim stops shadowing `git`, or the real
1925
+ // toolchain stops resolving. What none of them can see is a tail that stays
1926
+ // PLAUSIBLE. An empty entry (`::` — that is the CWD) or a duplicated one leaves
1927
+ // the shim first and every tool still findable, so the whole file stays green
1928
+ // while reap.sh runs on a PATH nobody meant; the PATH equality below is the
1929
+ // only thing in this file that catches that class. The Object.keys line covers
1930
+ // the other invisible one: runReap spreads this over ENV, so a second key here
1931
+ // would clobber one of ENV's git-scrubbing entries and the fixtures would
1932
+ // quietly start reading the developer's ~/.gitconfig. The tail asserts against
1933
+ // `process.env.PATH`, not `ENV.PATH`: ENV spreads process.env and never sets
1934
+ // PATH, and that identity is exactly what lets this helper spell the tail
1935
+ // without the `?? process.env.PATH` fallback its call sites used to.
1936
+ test("withShim prepends the shim dir, keeps the real PATH, and sets nothing else", () => {
1937
+ assert.equal(withShim("/x/bin").PATH, `/x/bin:${process.env.PATH}`);
1938
+ assert.deepEqual(Object.keys(withShim("/x/bin")), ["PATH"]);
1939
+ });
1940
+
1941
+ test("a refusal that CLEARED the registration is reported as a partial removal, not as a no-op (#391)", (t) => {
1942
+ // The worst of the two: git unregistered the worktree and then failed to
1943
+ // delete it, so the run reported `worktree remove refused` — indistinguishable
1944
+ // from "nothing happened" — while leaving an orphaned directory behind and
1945
+ // the branch standing as though it had been deliberately retained.
1946
+ const w = repo(t);
1947
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1948
+ const real = symlinkStandIn(wt);
1949
+
1950
+ // A second registration whose path merely BEGINS with the refused one. The
1951
+ // probe has to match a whole porcelain line, not a substring: without the
1952
+ // anchor this entry keeps matching after the refused one is gone, and the
1953
+ // run reports "registration intact" for a registration that was cleared —
1954
+ // measured, an unanchored grep survived every other test here. Its branch
1955
+ // has no upstream, so it is not [gone] and reap never touches it.
1956
+ git(w, "worktree", "add", "-q", `${wt}-sibling`, "-b", "scratch/sibling", "main");
1957
+
1958
+ const { code, json, stderr } = runReap(w, ["--apply"]);
1959
+
1960
+ assert.equal(code, 0, "a refusal is a finding, not a script failure");
1961
+ assert.deepEqual(json.reaped, []);
1962
+ assert.equal(json.kept.length, 1);
1963
+ assert.equal(json.kept[0].branch, "feature/merged");
1964
+ assert.match(
1965
+ json.kept[0].reason,
1966
+ /registration cleared/,
1967
+ `a refusal that unregistered the worktree must not read as a no-op: ${json.kept[0].reason}`,
1968
+ );
1969
+ assert.match(json.kept[0].reason, /Not a directory/, "git's own diagnosis must reach the payload");
1970
+ assert.doesNotMatch(json.kept[0].reason, /\n/, "git's stderr is multi-line; the reason must be flattened");
1971
+ assert.match(stderr, /KEEP feature\/merged — worktree remove refused/);
1972
+
1973
+ // The registration really is gone — the state the reason claims, measured.
1974
+ // Compared whole-line, for the reason the script's own probe is: a substring
1975
+ // test against this porcelain matches the sibling entry below and would call
1976
+ // a cleared registration intact. (This assertion was written unanchored
1977
+ // first, and the sibling caught it.)
1978
+ const reg = git(w, "worktree", "list", "--porcelain").split("\n");
1979
+ assert.ok(!reg.includes(`worktree ${wt}`), `the refused worktree's registration must be gone: ${reg.join(" | ")}`);
1980
+ assert.ok(reg.includes(`worktree ${wt}-sibling`), "fixture: the prefix-sharing sibling must still be registered");
1981
+ // ...and nothing on disk was removed by this script, under any path.
1982
+ assert.ok(lstatSync(wt).isSymbolicLink(), "the stand-in symlink must survive");
1983
+ assert.equal(existsSync(real), true, "the orphaned directory is not this script's to delete");
1984
+ assert.equal(branchExists(w, "feature/merged"), true, "and the branch is still kept");
1985
+ });
1986
+
1987
+ test("a refusal that LEFT the registration in place is reported as such, distinctly (#391)", (t) => {
1988
+ // The other half, and the half the old message happened to describe
1989
+ // correctly — asserted so the two outcomes cannot collapse back into one
1990
+ // string. A locked worktree exits 128 with the admin entry untouched
1991
+ // (measured, git 2.50.1). Per the brief this needs no dedicated arm: once
1992
+ // git's stderr is quoted, the lock names itself and its own remedy.
1993
+ const w = repo(t);
1994
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
1995
+ git(w, "worktree", "lock", wt);
1996
+
1997
+ const { code, json, stderr } = runReap(w, ["--apply"]);
1998
+
1999
+ assert.equal(code, 0);
2000
+ assert.deepEqual(json.reaped, []);
2001
+ assert.equal(json.kept.length, 1);
2002
+ assert.match(
2003
+ json.kept[0].reason,
2004
+ /registration intact/,
2005
+ `a refusal that changed nothing must say so: ${json.kept[0].reason}`,
2006
+ );
2007
+ assert.doesNotMatch(json.kept[0].reason, /registration cleared/, "the two outcomes must not collapse into one reason");
2008
+ assert.match(json.kept[0].reason, /locked working tree/, "git's message names the fault and the remedy");
2009
+ assert.match(json.kept[0].reason, /remove -f -f/, "including the remedy, which only git can supply");
2010
+ assert.doesNotMatch(json.kept[0].reason, /\n/, "git's message here really is two lines — it must arrive flattened");
2011
+ assert.match(stderr, /KEEP feature\/merged/);
2012
+
2013
+ assert.match(git(w, "worktree", "list", "--porcelain"), /feature\/merged/, "the registration really did survive");
2014
+ assert.equal(existsSync(wt), true);
2015
+ assert.equal(branchExists(w, "feature/merged"), true);
2016
+ });
2017
+
2018
+ test("a refusal whose registration a PEER cleared claims nothing about the directory (#391)", (t) => {
2019
+ // The registry and the directory are INDEPENDENT facts, and the reason may
2020
+ // only carry the one that was read. Shape: a concurrent session finishes the
2021
+ // same removal between this run's lookup and its own `git worktree remove`
2022
+ // — the concurrency reap.sh's own header documents — so the registration is
2023
+ // cleared, our removal fails, and NOTHING is left behind. A reason that
2024
+ // hard-codes "removal was partial — $wt is still on disk" reports an orphan
2025
+ // that does not exist, and this ticket exists because a reason that names
2026
+ // something other than what was measured is the defect.
2027
+ //
2028
+ // Neither arm above can catch that: in the symlink shape the directory
2029
+ // happens to survive, so both stay green with the false clause in place —
2030
+ // measured, 907/907, which is why this arm is here at all.
2031
+ //
2032
+ // The shim runs the PEER's removal with the real git and then returns false,
2033
+ // so the `exec` below it runs OUR removal for real and it fails in git's own
2034
+ // words. No permission bits, hence none of the euid-0 vacuity the `0o000`
2035
+ // fixtures in this file have to skip around (#184).
2036
+ const w = repo(t);
2037
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
2038
+ const bin = failOnlyShim(
2039
+ t,
2040
+ `[ "$1" = worktree ] && [ "$2" = remove ] && { ${REAL_GIT} worktree remove "$3" >/dev/null 2>&1; false; }`,
2041
+ [],
2042
+ );
2043
+
2044
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
2045
+
2046
+ // Both halves of the fixture, asserted before the reason is read: the peer
2047
+ // really did finish the job, so "still on disk" would be false and
2048
+ // "registration cleared" true.
2049
+ assert.equal(existsSync(wt), false, "fixture: the peer's removal must leave nothing on disk");
2050
+ assert.ok(
2051
+ !git(w, "worktree", "list", "--porcelain").split("\n").includes(`worktree ${wt}`),
2052
+ "fixture: the peer's removal must clear the registration",
2053
+ );
2054
+
2055
+ assert.equal(code, 0, "a refusal is a finding, not a script failure");
2056
+ assert.deepEqual(json.reaped, []);
2057
+ assert.equal(json.kept.length, 1);
2058
+ assert.match(
2059
+ json.kept[0].reason,
2060
+ /registration cleared/,
2061
+ `the registry is what was read, and it says cleared: ${json.kept[0].reason}`,
2062
+ );
2063
+ assert.doesNotMatch(
2064
+ json.kept[0].reason,
2065
+ /on disk|orphan|removal was partial/,
2066
+ `nothing stat'd the directory, so the reason must claim nothing about it: ${json.kept[0].reason}`,
2067
+ );
2068
+ assert.match(json.kept[0].reason, /is not a working tree/, "git's own diagnosis still reaches the payload");
2069
+ assert.equal(branchExists(w, "feature/merged"), true);
2070
+ });
2071
+
2072
+ test("the sweep continues past a worktree-removal refusal and still reaps the branches AFTER it (#391)", (t) => {
2073
+ // The constraint that separates this ticket's ruling from #208's: reap.sh
2074
+ // sweeps every [gone] branch unattended in one pass, so one orphan must not
2075
+ // strand the rest. The new registry re-read runs inside that loop, which is
2076
+ // exactly where an added git call could introduce a bail.
2077
+ //
2078
+ // The `a-`/`b-` names are load-bearing, not decoration. `git for-each-ref`
2079
+ // sorts by refname, so a healthy branch named to sort FIRST is already
2080
+ // reaped before the refusal happens and the test passes under a `break`
2081
+ // just as happily as under a `continue`. Measured both ways on this branch,
2082
+ // rather than carrying a count that drifts every time a test is added: under
2083
+ // the alternative spelling the whole file stays green with the mutant in
2084
+ // place, and under the shipped one exactly this test reds.
2085
+ const w = repo(t);
2086
+ const wt = mergedGoneBranchWithWorktree(w, "feature/a-locked", "work behind a lock");
2087
+ git(w, "worktree", "lock", wt);
2088
+ mergedGoneBranch(w, "feature/b-healthy", "work that landed");
2089
+
2090
+ const { code, json } = runReap(w, ["--apply"]);
2091
+
2092
+ assert.equal(code, 0);
2093
+ assert.deepEqual(json.reaped, ["feature/b-healthy"], "the refusal must not strand the branches after it");
2094
+ assert.equal(json.kept.length, 1);
2095
+ assert.equal(json.kept[0].branch, "feature/a-locked");
2096
+ assert.equal(branchExists(w, "feature/b-healthy"), false, "reached only by continuing past the refusal");
2097
+ assert.equal(branchExists(w, "feature/a-locked"), true);
2098
+ });
2099
+
2100
+ test("a branch delete failure carries git's own message, not just the label (#391)", (t) => {
2101
+ // `>/dev/null 2>&1` sent the cause to the void and reported "branch delete
2102
+ // failed". The real message names the fault outright. No shim: a stale
2103
+ // `.lock` beside the ref makes the real `git update-ref -d` refuse (#2219
2104
+ // moved the delete off `git branch -D`), with git's multi-line "Another
2105
+ // git process" prose — and the reason has to survive as a single JSON string.
2106
+ //
2107
+ // Scoped to one branch, and a healthy branch sorts after it, so this also
2108
+ // pins the other half of "the sweep continues past EITHER failure".
2109
+ const w = repo(t);
2110
+ mergedGoneBranch(w, "feature/a-broken", "merged work");
2111
+ mergedGoneBranch(w, "feature/b-healthy", "work that landed");
2112
+ writeFileSync(join(w, ".git", "refs", "heads", "feature", "a-broken.lock"), "");
2113
+
2114
+ const { code, json, stderr } = runReap(w, ["--apply"]);
2115
+
2116
+ assert.equal(code, 0);
2117
+ assert.deepEqual(json.reaped, ["feature/b-healthy"], "a branch that was not deleted must not be reported as reaped, and the sweep goes on");
2118
+ assert.equal(json.kept.length, 1);
2119
+ assert.equal(json.kept[0].branch, "feature/a-broken");
2120
+ assert.match(json.kept[0].reason, /^branch delete failed: /, "the label stays — it is the reason that gains a cause");
2121
+ assert.match(json.kept[0].reason, /cannot lock ref 'refs\/heads\/feature\/a-broken'/, "git's diagnosis must reach the payload");
2122
+ assert.match(json.kept[0].reason, /Another git process/, "every line, not just the first");
2123
+ assert.doesNotMatch(json.kept[0].reason, /\n/, "flattened into one JSON string");
2124
+ assert.match(stderr, /KEEP feature\/a-broken — branch delete failed/);
2125
+ assert.equal(branchExists(w, "feature/a-broken"), true);
2126
+ assert.equal(branchExists(w, "feature/b-healthy"), false, "reached only by continuing past the failure");
2127
+ });
2128
+
2129
+ test("a branch-config removal failure after a successful delete is not lost — it reaches warnings, not just stderr (#2219)", (t) => {
2130
+ // `git update-ref -d` only touches the ref DB; the `[branch "<b>"]` config
2131
+ // section it leaves behind is removed by a SEPARATE `git config
2132
+ // --remove-section` call that can fail on its own (here, a stale
2133
+ // `.git/config.lock`). The branch is already gone by then, so this is
2134
+ // never a `keep` — but an unattended caller reading only stdout JSON must
2135
+ // still learn the leftover section was left, or a later `git branch
2136
+ // --no-track` of the same name silently inherits the dead upstream and
2137
+ // reads `[gone]` at once (the leak the success-path test above pins).
2138
+ const w = repo(t);
2139
+ mergedGoneBranch(w, "feature/leak", "merged work");
2140
+ writeFileSync(join(w, ".git", "config.lock"), "");
2141
+
2142
+ const { code, json, stderr } = runReap(w, ["--apply"]);
2143
+
2144
+ assert.equal(code, 0);
2145
+ assert.deepEqual(json.reaped, ["feature/leak"], "the branch is genuinely gone — this is never a keep");
2146
+ assert.deepEqual(json.kept, []);
2147
+ assert.equal(json.warnings.length, 1);
2148
+ assert.equal(json.warnings[0].branch, "feature/leak");
2149
+ assert.match(json.warnings[0].note, /^branch config section was left: /);
2150
+ assert.match(json.warnings[0].note, /could not lock config file/, "git's own diagnosis must reach the payload");
2151
+ assert.match(stderr, /note: feature\/leak deleted, but its branch config section was left/);
2152
+ assert.equal(branchExists(w, "feature/leak"), false);
2153
+ });
2154
+
2155
+ test("a [gone] branch that gains a commit after its tip is read is kept, and the commit survives (#2219)", (t) => {
2156
+ // `git branch -D` deleted whatever the ref held when it ran, in a call
2157
+ // separate from the `git cherry` that authorized it, so a commit landing
2158
+ // between the two was force-deleted at exit 0 — release-ticket.sh's gap
2159
+ // before #1325. The shim lands that commit the moment the real `git cherry`
2160
+ // has answered, which is inside the window under the `-D` delete and the
2161
+ // compare-and-swap alike: red on the first, green on the second.
2162
+ // `git update-ref -d refs/heads/<b> <tip>` refuses the moved ref, and git's
2163
+ // own `cannot lock ref` reaches the reason (#391).
2164
+ const w = repo(t);
2165
+ mergedGoneBranch(w, "feature/raced", "merged work");
2166
+ const bin = failOnlyShim(
2167
+ t,
2168
+ `[ "$1" = cherry ] && {
2169
+ out=$("${REAL_GIT}" "$@"); rc=$?
2170
+ ${SHIM_FIRED}
2171
+ old=$("${REAL_GIT}" rev-parse refs/heads/feature/raced) &&
2172
+ newc=$("${REAL_GIT}" commit-tree "$old^{tree}" -p "$old" -m race) &&
2173
+ "${REAL_GIT}" update-ref refs/heads/feature/raced "$newc"
2174
+ [ -z "$out" ] || printf '%s\\n' "$out"
2175
+ exit $rc
2176
+ }`,
2177
+ [],
2178
+ );
2179
+
2180
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
2181
+
2182
+ assertShimFired(bin, "the commit must land inside the cherry-to-delete window", /^cherry /m);
2183
+ assert.equal(code, 0, stderr);
2184
+ assert.deepEqual(json.reaped, [], "a branch that moved after its tip was read is never deleted");
2185
+ const kept = json.kept.filter((k) => k.branch === "feature/raced");
2186
+ assert.equal(kept.length, 1, JSON.stringify(json.kept));
2187
+ assert.match(kept[0].reason, /^branch delete failed: .*cannot lock ref 'refs\/heads\/feature\/raced'/, "git's own compare-and-swap refusal, quoted");
2188
+ assert.equal(git(w, "log", "-1", "--format=%s", "refs/heads/feature/raced"), "race", "the commit that landed in the window is still the branch's tip");
2189
+ });
2190
+
2191
+ /** Real git with stdio captured, so a rebase's `Stopped at` prose stays out of the test output. */
2192
+ const quietGit = (cwd, ...args) => execFileSync("git", args, { cwd, env: ENV, stdio: "pipe" });
2193
+
2194
+ /**
2195
+ * A merged `[gone]` branch whose linked worktree `stop` leaves mid-operation
2196
+ * and DETACHED: the listing prints no `branch` line for it, so the `$wt`
2197
+ * lookup never binds it and the branch reaches the delete with nothing
2198
+ * matched. `git branch -D` refused it there all the same ("used by
2199
+ * worktree"), because git reads the operation's own state out of the admin
2200
+ * dir; after #2219 the delete is `update-ref -d`, which reads none, and
2201
+ * worktree.sh's `wt_holding` (#2218) has to. Two real-content commits, so a
2202
+ * rebase has something to stop on and a bisect has a midpoint to detach at.
2203
+ */
2204
+ function heldMidOperation(t, name, stop) {
2205
+ const w = repo(t);
2206
+ const wt = join(w, ".worktrees", "held");
2207
+ git(w, "worktree", "add", "-q", wt, "-b", name, "main");
2208
+ for (const n of [1, 2]) {
2209
+ writeFileSync(join(wt, `work-${n}.txt`), `work ${n}\n`);
2210
+ git(wt, "add", `work-${n}.txt`);
2211
+ git(wt, "commit", "-q", "-m", `work ${n}`);
2212
+ }
2213
+ git(wt, "push", "-q", "-u", "origin", name);
2214
+ git(w, "merge", "-q", "--no-ff", "-m", `merge ${name}`, name);
2215
+ git(w, "push", "-q", "origin", "main");
2216
+ git(w, "push", "-q", "origin", "--delete", name);
2217
+ git(w, "fetch", "-q", "--prune", "origin");
2218
+ stop(wt);
2219
+ assert.match(
2220
+ git(w, "worktree", "list", "--porcelain"),
2221
+ /\/held\nHEAD [0-9a-f]+\ndetached$/m,
2222
+ "fixture: the worktree must be detached, or the porcelain `branch` line already answers",
2223
+ );
2224
+ return { w, wt };
2225
+ }
2226
+
2227
+ for (const [what, stop, finish] of [
2228
+ ["stopped mid-`rebase -i`", (wt) => quietGit(wt, "-c", "sequence.editor=sed -i.bak s/^pick/edit/", "rebase", "-i", "HEAD~1"), (wt) => quietGit(wt, "rebase", "--continue")],
2229
+ ["mid-`bisect`", (wt) => quietGit(wt, "bisect", "start", "HEAD", "HEAD~2"), (wt) => quietGit(wt, "bisect", "reset")],
2230
+ ]) {
2231
+ test(`a [gone] branch held by a worktree ${what} is kept (#2219)`, (t) => {
2232
+ // Green before #2219 and after, by different mechanisms: `-D`'s own
2233
+ // refusal then, `wt_holding` now. What it protects: the operation can
2234
+ // still finish onto its branch.
2235
+ const name = "feature/held";
2236
+ const { w, wt } = heldMidOperation(t, name, stop);
2237
+
2238
+ const { code, json, stderr } = runReap(w, ["--apply"]);
2239
+
2240
+ assert.equal(code, 0, stderr);
2241
+ assert.deepEqual(json.reaped, []);
2242
+ const kept = json.kept.filter((k) => k.branch === name);
2243
+ assert.equal(kept.length, 1, JSON.stringify(json.kept));
2244
+ assert.ok(kept[0].reason.includes(wt), `the reason names the worktree that holds it: ${kept[0].reason}`);
2245
+ assert.equal(branchExists(w, name), true);
2246
+ finish(wt);
2247
+ assert.equal(git(wt, "symbolic-ref", "HEAD"), `refs/heads/${name}`, "the operation can still finish onto its branch");
2248
+ });
2249
+ }
2250
+
2251
+ test("a [gone] branch whose holder check cannot read a worktree's rebase state is kept as unknown (#2219)", (t) => {
2252
+ // `wt_holding` answers "cannot tell" when a detached worktree's
2253
+ // `rebase-merge` dir exists but cannot be searched, so its `head-name` —
2254
+ // which branch the rebase holds — is unreadable. Nothing earlier refuses
2255
+ // this shape: the HEAD is a real commit, so the registry cross-check
2256
+ // passes, and the listing names no branch, so the `$wt` lookup binds
2257
+ // nothing. Unknown is a keep, never "not held".
2258
+ if (process.getuid?.() === 0) return t.skip("root reads every file");
2259
+ const name = "feature/held";
2260
+ const { w, wt } = heldMidOperation(t, name, (wt) =>
2261
+ quietGit(wt, "-c", "sequence.editor=sed -i.bak s/^pick/edit/", "rebase", "-i", "HEAD~1"),
2262
+ );
2263
+ const rebaseMerge = join(adminEntry(w, wt), "rebase-merge");
2264
+ chmodSync(rebaseMerge, 0o000);
2265
+ let r;
2266
+ try {
2267
+ r = runReap(w, ["--apply"]);
2268
+ } finally {
2269
+ chmodSync(rebaseMerge, 0o755);
2270
+ }
2271
+ const { code, json, stderr } = r;
2272
+
2273
+ assert.equal(code, 0, stderr);
2274
+ assert.deepEqual(json.reaped, []);
2275
+ const kept = json.kept.filter((k) => k.branch === name);
2276
+ assert.equal(kept.length, 1, JSON.stringify(json.kept));
2277
+ assert.match(kept[0].reason, /^cannot tell whether feature\/held is held by worktree .* — not deleted$/);
2278
+ assert.equal(branchExists(w, name), true);
2279
+ });
2280
+
2281
+ test("a [gone] branch whose tip cannot be read is kept with git's cause, never deleted (#2219)", (t) => {
2282
+ // The tip is what the cherry measures and what the compare-and-swap
2283
+ // compares against, so a read that fails authorizes nothing.
2284
+ const w = repo(t);
2285
+ mergedGoneBranch(w, "feature/a-unread", "merged work");
2286
+ mergedGoneBranch(w, "feature/b-healthy", "work that landed");
2287
+ const bin = failOnlyShim(
2288
+ t,
2289
+ `[ "$1" = rev-parse ] && [ "$2" = --verify ] && [ "$3" = refs/heads/feature/a-unread ]`,
2290
+ ["fatal: unable to read tree deadbeef"],
2291
+ 128,
2292
+ );
2293
+
2294
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
2295
+
2296
+ assertShimFired(bin, "the tip read must be the call that failed", /^rev-parse --verify refs\/heads\/feature\/a-unread$/m);
2297
+ assert.equal(code, 0);
2298
+ assert.deepEqual(json.reaped, ["feature/b-healthy"], "the sweep goes on past it");
2299
+ assert.equal(json.kept.length, 1);
2300
+ assert.equal(json.kept[0].reason, "cannot read the branch tip — not deleted: fatal: unable to read tree deadbeef");
2301
+ assert.equal(branchExists(w, "feature/a-unread"), true);
2302
+ });
2303
+
2304
+ test("a worktree mid-rebase of a DIFFERENT branch does not hold a [gone] branch's delete (#2219)", (t) => {
2305
+ // The false-refusal half: an operation in progress is not by itself a hold.
2306
+ // Only the branch it names blocks the delete.
2307
+ const w = repo(t);
2308
+ mergedGoneBranch(w, "feature/merged", "merged work");
2309
+ const sib = join(w, ".worktrees", "other");
2310
+ git(w, "worktree", "add", "-q", sib, "-b", "other", "main");
2311
+ writeFileSync(join(sib, "other.txt"), "other work\n");
2312
+ git(sib, "add", "other.txt");
2313
+ git(sib, "commit", "-q", "-m", "other work");
2314
+ quietGit(sib, "-c", "sequence.editor=sed -i.bak s/^pick/edit/", "rebase", "-i", "HEAD~1");
2315
+
2316
+ const { code, json, stderr } = runReap(w, ["--apply"]);
2317
+
2318
+ assert.equal(code, 0, stderr);
2319
+ assert.deepEqual(json.reaped, ["feature/merged"], JSON.stringify(json.kept));
2320
+ assert.equal(branchExists(w, "feature/merged"), false);
2321
+ });
2322
+
2323
+ test("a reaped branch leaves no upstream behind for a re-created branch of the same name (#2219)", (t) => {
2324
+ // `git branch -D` removed the `[branch "<b>"]` config section with the ref;
2325
+ // ref-only `update-ref -d` does not. Left behind, a later `git branch
2326
+ // --no-track <b>` inherits the dead upstream and reads `[gone]` at once —
2327
+ // selected by the very next pass.
2328
+ const w = repo(t);
2329
+ mergedGoneBranch(w, "feature/merged", "merged work");
2330
+
2331
+ const { json } = runReap(w, ["--apply"]);
2332
+ assert.deepEqual(json.reaped, ["feature/merged"]);
2333
+
2334
+ git(w, "branch", "--no-track", "feature/merged", "main");
2335
+ assert.equal(git(w, "for-each-ref", "--format=%(upstream)%(upstream:track)", "refs/heads/feature/merged"), "");
2336
+ });
2337
+
2338
+ test("a [gone] branch that is a symbolic ref is deleted itself, never the branch it points at (#2219)", (t) => {
2339
+ // `git update-ref -d` dereferences by default: on a symref branch it
2340
+ // deletes the TARGET and leaves the symref dangling (measured, git 2.50.1).
2341
+ // `git branch -D` deleted the symref itself, which `--no-deref` keeps.
2342
+ const w = repo(t);
2343
+ git(w, "branch", "target", "main");
2344
+ git(w, "symbolic-ref", "refs/heads/feature/alias", "refs/heads/target");
2345
+ git(w, "config", "branch.feature/alias.remote", "origin");
2346
+ git(w, "config", "branch.feature/alias.merge", "refs/heads/feature/alias");
2347
+
2348
+ const { json, stderr } = runReap(w, ["--apply"]);
2349
+
2350
+ assert.deepEqual(json.reaped, ["feature/alias"], stderr);
2351
+ assert.equal(branchExists(w, "target"), true, "the branch the symref pointed at was never selected, and survives");
2352
+ assert.equal(existsSync(join(w, ".git", "refs", "heads", "feature", "alias")), false, "the symref itself is what was deleted");
2353
+ });
2354
+
2355
+ test("a dying `git worktree list` keeps every [gone] branch and names git's cause (#622)", (t) => {
2356
+ // The per-branch lookup used to swallow the listing's failure (`|| :`), so
2357
+ // a dying list left $wt empty: every check under `[ -n "$wt" ]` was skipped
2358
+ // and flow fell through to `git branch -D`. A merged branch with no worktree
2359
+ // was then force-deleted while the sweep could not see the registry at all,
2360
+ // and only a branch that DID have a worktree was saved — by git's own
2361
+ // refusal, under the label `branch delete failed`.
2362
+ //
2363
+ // Ruled on #622: fail closed, like every other could-not-check in reap.sh.
2364
+ // Both branches are kept with the cause, `git branch -D` is never reached,
2365
+ // and the next merge pass retries them. This moves the pin #391 left here.
2366
+ const w = repo(t);
2367
+ mergedGoneBranchWithWorktree(w, "feature/a-merged", "merged work");
2368
+ mergedGoneBranch(w, "feature/b-merged", "more merged work");
2369
+ const bin = failOnlyShim(
2370
+ t,
2371
+ `[ "$1" = worktree ] && [ "$2" = list ]`,
2372
+ ["fatal: worktree list exploded"],
2373
+ 128,
2374
+ );
2375
+
2376
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
2377
+
2378
+ assert.equal(code, 0, "a registry nobody could read is a finding, not a script failure");
2379
+ assert.deepEqual(json.reaped, [], "nothing is reaped while the registry is unread");
2380
+ assert.equal(json.kept.length, 3);
2381
+ for (const [i, branch] of [[0, "feature/a-merged"], [1, "feature/b-merged"]]) {
2382
+ assert.equal(json.kept[i].branch, branch);
2383
+ assert.match(json.kept[i].reason, /^worktree lookup failed/);
2384
+ assert.match(json.kept[i].reason, /worktree list exploded/, "git's own words, not just the label");
2385
+ assert.doesNotMatch(json.kept[i].reason, /branch delete failed/, "`git branch -D` is never reached");
2386
+ assert.doesNotMatch(json.kept[i].reason, /\n/, "flattened into one JSON string");
2387
+ }
2388
+ // The worktree sweep reads the same dead registry, and says so rather than
2389
+ // reporting an empty enumeration as "no branchless worktrees" — the silence
2390
+ // #381 exists to end, reachable here by a different route.
2391
+ assert.equal(json.kept[2].branch, null, "a sweep that never named a worktree has no branch to blame");
2392
+ assert.match(json.kept[2].reason, /^cannot enumerate worktrees/);
2393
+ assert.match(json.kept[2].reason, /worktree list exploded/, "git's own words, not just the label");
2394
+ assert.match(stderr, /KEEP feature\/a-merged — worktree lookup failed/);
2395
+ assert.match(stderr, /KEEP feature\/b-merged — worktree lookup failed/);
2396
+ assert.equal(branchExists(w, "feature/a-merged"), true);
2397
+ assert.equal(branchExists(w, "feature/b-merged"), true, "the branch with no worktree is no longer reaped blind");
2398
+ });
2399
+
2400
+ test("a transient `git worktree list` failure keeps only the branch it hit — not the whole pass (#622)", (t) => {
2401
+ // #622's own fix comment says the listing is re-read per branch, so "one
2402
+ // repo-level failure keeps every [gone] branch in the pass" describes a
2403
+ // PERSISTENT fault (the realistic case: filesystem or registry
2404
+ // corruption), not a mechanism that latches once true for every later
2405
+ // iteration. No fixture above distinguishes the two: every other
2406
+ // listing-failure test in this file starves `worktree list` for the whole
2407
+ // run, which a sticky "cache the failure at the loop's first hit" bug would
2408
+ // pass exactly as well as a genuine per-iteration re-read.
2409
+ //
2410
+ // Three branches, alphabetical so `for-each-ref`'s default refname sort
2411
+ // fixes the iteration order; the shim fails ONLY the THIRD `worktree list`
2412
+ // call — the second branch's lookup, since under --apply each reaped
2413
+ // branch reads the listing twice, at the lookup and again at the holder
2414
+ // check before its delete (#2219). If the guard truly re-reads per branch,
2415
+ // the first and third branches see a healthy listing and reap normally —
2416
+ // only the second, the one whose own call hit the fault, is kept.
2417
+ const w = repo(t);
2418
+ mergedGoneBranch(w, "feature/a-first", "a work");
2419
+ mergedGoneBranch(w, "feature/b-second", "b work");
2420
+ mergedGoneBranch(w, "feature/c-third", "c work");
2421
+
2422
+ const { bin } = worktreeListFailsOnCall(t, "-eq 3");
2423
+
2424
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
2425
+
2426
+ assert.equal(code, 0);
2427
+ assert.deepEqual(
2428
+ json.reaped,
2429
+ ["feature/a-first", "feature/c-third"],
2430
+ "only the branch whose OWN lookup call failed is kept — a sticky/hoisted failure would keep all three",
2431
+ );
2432
+ assert.equal(json.kept.length, 1);
2433
+ assert.equal(json.kept[0].branch, "feature/b-second");
2434
+ assert.match(json.kept[0].reason, /^worktree lookup failed/);
2435
+ assert.equal(branchExists(w, "feature/a-first"), false);
2436
+ assert.equal(branchExists(w, "feature/b-second"), true);
2437
+ assert.equal(branchExists(w, "feature/c-third"), false);
2438
+ });
2439
+
2440
+ test("a `git worktree list` that fails at the holder check before the delete keeps that branch (#2219)", (t) => {
2441
+ // The delete's own re-read of the listing, which `wt_holding` needs because
2442
+ // `update-ref -d` consults no worktree. A read that fails there is a keep,
2443
+ // never a delete on a holder check that never ran. The second call is the
2444
+ // first branch's re-read: its lookup (call 1) was healthy.
2445
+ const w = repo(t);
2446
+ mergedGoneBranch(w, "feature/a-first", "a work");
2447
+ mergedGoneBranch(w, "feature/b-second", "b work");
2448
+
2449
+ const { bin } = worktreeListFailsOnCall(t, "-eq 2");
2450
+
2451
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
2452
+
2453
+ assert.equal(code, 0);
2454
+ assert.deepEqual(json.reaped, ["feature/b-second"]);
2455
+ assert.equal(json.kept.length, 1);
2456
+ assert.equal(json.kept[0].branch, "feature/a-first");
2457
+ assert.match(json.kept[0].reason, /^cannot re-read the worktree list .* not deleted: fatal: worktree list exploded/);
2458
+ assert.equal(branchExists(w, "feature/a-first"), true);
2459
+ });
2460
+
2461
+ test("quotes and backslashes in git's stderr still round-trip through the new reasons (#391, #119)", (t) => {
2462
+ // These three reasons now carry text neither this repo nor its operator
2463
+ // chose. `keep()` escapes through json.sh, which landed in #119 — before it,
2464
+ // routing git's stderr here would have emitted a payload no parser accepts.
2465
+ const w = repo(t);
2466
+ mergedGoneBranch(w, "feature/merged", "merged work");
2467
+ const bin = failOnlyShim(
2468
+ t,
2469
+ `[ "$1" = update-ref ] && case " $* " in *" -d "*) : ;; *) false ;; esac`,
2470
+ [`error: cannot lock ref "feat": Unable to create 'C:\\path\\to\\feat.lock'`],
2471
+ );
2472
+
2473
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
2474
+
2475
+ assert.equal(code, 0);
2476
+ assert.equal(
2477
+ json.kept[0].reason,
2478
+ `branch delete failed: error: cannot lock ref "feat": Unable to create 'C:\\path\\to\\feat.lock'`,
2479
+ "the quotes and backslashes survive as data — runReap JSON.parses stdout, so a raw splice fails before this assert",
2480
+ );
2481
+ });
2482
+
2483
+ test("an ordinary run's payload is byte-for-byte what it has always been (#391)", (t) => {
2484
+ // The false-positive half. Nothing here fails, so nothing has a cause to
2485
+ // quote and the payload must carry no reason at all — a fix that starts
2486
+ // decorating healthy reasons is as wrong as one that reports none.
2487
+ //
2488
+ // `worktreesRemoved` is the one field this healthy run does gain (#381), and
2489
+ // it is a statement of fact rather than a decoration: the branch sweep really
2490
+ // did remove that directory, and a key that named only the removals no branch
2491
+ // accounted for would leave a reader unable to tell an absent removal from an
2492
+ // unreported one.
2493
+ const w = repo(t);
2494
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
2495
+
2496
+ const { code, json, stderr } = runReap(w, ["--apply"]);
2497
+
2498
+ assert.equal(code, 0);
2499
+ assert.deepEqual(json, { applied: true, reaped: ["feature/merged"], worktreesRemoved: [wt], kept: [], warnings: [] });
2500
+ assert.doesNotMatch(stderr, /KEEP/);
2501
+ assert.doesNotMatch(stderr, /registration/, "a successful removal says nothing about registrations");
2502
+ assert.equal(existsSync(wt), false);
2503
+ });
2504
+
2505
+ test("the dry run removes nothing, and still cannot predict a refusal (#391)", (t) => {
2506
+ // The brief keeps this asymmetry deliberately: a dry run prints
2507
+ // `would remove worktree $wt` WITHOUT attempting the removal, so it cannot
2508
+ // foresee a refusal — performing it is the only way to know. This resembles
2509
+ // the dry/apply mismatch class of #86, #385 and #386 but is not an instance
2510
+ // of it, and the fix above must not have quietly turned it into one by
2511
+ // teaching the dry run to probe.
2512
+ //
2513
+ // BOTH fixtures are load-bearing. The locked one pins the unpredicted
2514
+ // refusal; the healthy one pins that no removal was attempted at all, and
2515
+ // only it can. Measured: with the locked worktree alone, a dry run taught to
2516
+ // call `git worktree remove` left this test green — the lock made the
2517
+ // attempt fail, so the fixture could not tell an attempt from an abstention.
2518
+ const w = repo(t);
2519
+ const healthy = mergedGoneBranchWithWorktree(w, "feature/a-healthy", "work that landed");
2520
+ const locked = mergedGoneBranchWithWorktree(w, "feature/b-locked", "work behind a lock");
2521
+ git(w, "worktree", "lock", locked);
2522
+
2523
+ const { code, json, stderr } = runReap(w, []);
2524
+
2525
+ assert.equal(code, 0);
2526
+ assert.deepEqual(
2527
+ json,
2528
+ {
2529
+ applied: false,
2530
+ reaped: ["feature/a-healthy", "feature/b-locked"],
2531
+ worktreesRemoved: [healthy, locked],
2532
+ kept: [],
2533
+ warnings: [],
2534
+ },
2535
+ "the dry run still promises the reap it cannot know will be refused",
2536
+ );
2537
+ assert.ok(stderr.includes(` would remove worktree ${healthy}`), `the dry run's own line is unchanged: ${stderr}`);
2538
+ assert.ok(stderr.includes(` would remove worktree ${locked}`));
2539
+ assert.ok(stderr.includes(" would reap feature/a-healthy"));
2540
+ assert.doesNotMatch(stderr, /KEEP/, "a dry run predicts no refusal — it never ran the removal");
2541
+ assert.doesNotMatch(stderr, /registration/, "and it probes no registry either");
2542
+
2543
+ // Nothing was touched: directories, registrations and branches all intact.
2544
+ assert.equal(existsSync(healthy), true, "a dry run must not remove the worktree it COULD have removed");
2545
+ assert.equal(existsSync(locked), true);
2546
+ const reg = git(w, "worktree", "list", "--porcelain");
2547
+ assert.match(reg, /feature\/a-healthy/);
2548
+ assert.match(reg, /feature\/b-locked/);
2549
+ assert.equal(branchExists(w, "feature/a-healthy"), true);
2550
+ assert.equal(branchExists(w, "feature/b-locked"), true);
2551
+ });
2552
+
2553
+ test("a registry probe that itself fails is reported as unknown, never as 'cleared' (#391)", (t) => {
2554
+ // The registration probe this fix adds is a git call of its own, and it can
2555
+ // fail. Spelling it `git worktree list … | grep -q` would take GREP's exit
2556
+ // status, never git's, and report a registry it never managed to read as
2557
+ // CLEARED — this ticket's own defect, reintroduced inside its own fix, and
2558
+ // pointed at the more alarming of the two states. Measured: that spelling
2559
+ // survived every other test in this file.
2560
+ //
2561
+ // The shim starves `worktree list` only from its SECOND call onward, so the
2562
+ // lookup at the top of the loop still finds the worktree and reaches the
2563
+ // removal; only the post-refusal probe is denied an answer. The lock makes
2564
+ // the removal refuse without disturbing anything, so the registration really
2565
+ // is intact — and the point is that the script must NOT claim to know that.
2566
+ const w = repo(t);
2567
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
2568
+ git(w, "worktree", "lock", wt);
2569
+
2570
+ // The counter needs its own tmpdir: `failOnlyShim` creates the shim dir
2571
+ // itself, so the path has to exist before the match string that writes to it
2572
+ // can be built. Putting the count in the match is what lets this reuse the
2573
+ // helper — the match runs exactly once per `git`, ahead of the shim's single
2574
+ // `exec`.
2575
+ const { bin, counter } = worktreeListFailsOnCall(t, "-ge 2");
2576
+
2577
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
2578
+
2579
+ assert.equal(code, 0);
2580
+ assert.deepEqual(json.reaped, []);
2581
+ // The worktree sweep below runs the starved `worktree list` again and reports
2582
+ // that it could not enumerate; the entry under test is still the registry
2583
+ // probe's, and the sweep's must not be mistaken for it.
2584
+ assert.equal(json.kept.length, 2);
2585
+ assert.match(json.kept[1].reason, /^cannot enumerate worktrees/);
2586
+ assert.match(
2587
+ json.kept[0].reason,
2588
+ /cannot tell whether the registration survived/,
2589
+ `an unread registry is unknown, not a measurement: ${json.kept[0].reason}`,
2590
+ );
2591
+ assert.doesNotMatch(json.kept[0].reason, /registration cleared/, "the alarming state must never be guessed");
2592
+ assert.doesNotMatch(json.kept[0].reason, /registration intact/, "nor the reassuring one");
2593
+ assert.match(json.kept[0].reason, /locked working tree/, "git's reason for the refusal still reaches the payload");
2594
+ assert.equal(branchExists(w, "feature/merged"), true);
2595
+ // The probe was reached and starved, which is what this fixture has to
2596
+ // establish. Not an exact figure: the worktree sweep at the foot of the
2597
+ // script runs `worktree list` again, so a pinned total would fail whenever a
2598
+ // part of the script unrelated to this refusal gains or loses a call.
2599
+ assert.ok(
2600
+ Number(readFileSync(counter, "utf8")) >= 2,
2601
+ "fixture: the probe really was a call that got starved, not the lookup that preceded it",
2602
+ );
2603
+ });
2604
+
2605
+ // Same reason as the cherry-probe pin above, and the same derivation: the
2606
+ // script-surface table is what a reader trusts about a script that
2607
+ // settings.json's autoMode allowlist lets run unattended, and #264 spent its
2608
+ // whole life with that table asserting the bug as the behaviour. The two state
2609
+ // phrases are the part a reader would otherwise have to guess at, so they are
2610
+ // taken from real runs rather than typed here — a hand-copied phrase drifts
2611
+ // exactly the way the row did.
2612
+ test("the design spec's script-surface row carries both refusal states this script emits (#391)", (t) => {
2613
+ const states = ["locked", "symlink"].map((shape) => {
2614
+ const w = repo(t, `w-${shape}`);
2615
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
2616
+ if (shape === "locked") git(w, "worktree", "lock", wt);
2617
+ else symlinkStandIn(wt);
2618
+
2619
+ const { json } = runReap(w, ["--apply"]);
2620
+ assert.equal(json.kept.length, 1, `fixture (${shape}) must reach the removal refusal`);
2621
+ // The parenthesised state only — the path and git's message are the
2622
+ // machine's to vary and no document can carry them.
2623
+ const m = /^worktree remove refused \(([^)]*?)(?: —.*)?\)/.exec(json.kept[0].reason);
2624
+ assert.ok(m, `fixture (${shape}) must produce the refusal reason: ${json.kept[0].reason}`);
2625
+ return m[1];
2626
+ });
2627
+
2628
+ assert.notEqual(states[0], states[1], "the two refusals must not report the same state");
2629
+
2630
+ const row = specRow();
2631
+ for (const state of states) {
2632
+ assert.ok(row.includes(state), `the spec row must quote the refusal state verbatim, and does not carry "${state}".\nrow: ${row}`);
2633
+ }
2634
+ });
2635
+
2636
+ // Detached-worktree coverage (#381). The [gone]-branch sweep above locates a
2637
+ // worktree by the `branch refs/heads/<name>` line `git worktree list
2638
+ // --porcelain` prints for it. A worktree at detached HEAD has no such line
2639
+ // (measured, git 2.50.1 Apple Git-155: it prints `worktree`, `HEAD <sha>` and
2640
+ // `detached`), so it was not refused — it was not considered, and the sweep
2641
+ // reaped the branch and walked past the directory with no `would remove
2642
+ // worktree` line and no `kept` entry to say so. What ROUTE leaves a fleet
2643
+ // worktree in that shape is not asserted here: the merge bot's server-side
2644
+ // rebase was blamed in an earlier draft and measured not to detach (see
2645
+ // reap.sh's comment on the same point). The shape is what these fixtures build,
2646
+ // and the shape is all the sweep decides on.
2647
+
2648
+ /**
2649
+ * A merged `[gone]` branch whose linked worktree has been moved off it onto a
2650
+ * bare sha. Returns the worktree's absolute path.
2651
+ *
2652
+ * `wt` overrides the `.worktrees/` home so a test can put a worktree OUTSIDE
2653
+ * it: that home is the sweep's ownership bound, and refusing everything beyond
2654
+ * it needs a fixture beyond it.
2655
+ */
2656
+ function detachedMergedWorktree(w, name, msg, wt = join(w, ".worktrees", name)) {
2657
+ const dir = mergedGoneBranchWithWorktree(w, name, msg, wt);
2658
+ git(dir, "checkout", "-q", "--detach", "HEAD");
2659
+ return dir;
2660
+ }
2661
+
2662
+ test("a detached worktree whose HEAD is merged is removed, not walked past (#381)", (t) => {
2663
+ const w = repo(t);
2664
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2665
+ assert.ok(existsSync(wt), "fixture");
2666
+ assert.match(git(w, "worktree", "list"), /\(detached HEAD\)/, "fixture: the worktree must really be detached");
2667
+
2668
+ const { code, json, stderr } = runReap(w, ["--apply"]);
2669
+
2670
+ assert.equal(code, 0);
2671
+ assert.equal(existsSync(wt), false, "the directory the branch sweep cannot see must still be removed");
2672
+ assert.deepEqual(json.worktreesRemoved, [wt]);
2673
+ assert.deepEqual(json.kept, [], "a removal is not a keep");
2674
+ assert.ok(stderr.includes(` REMOVED worktree ${wt}`), `the removal must be reported: ${stderr}`);
2675
+ // The registration goes with it, or the in-flight probe still reads the
2676
+ // ticket as taken — the whole cost this ticket exists to stop.
2677
+ assert.doesNotMatch(git(w, "worktree", "list", "--porcelain"), /79-brief/);
2678
+ });
2679
+
2680
+ test("a branchless sweep whose awk cannot read the listing declines, never sweeps silently (#993)", (t) => {
2681
+ // The enumeration's OTHER half. `git worktree list` dying is pinned by the
2682
+ // #391 test above ("cannot enumerate worktrees"); the awk that parses what it
2683
+ // printed was not, and the script's own comment at that arm calls it "this
2684
+ // ticket's own defect, committed inside its fix" — an awk that cannot run
2685
+ // leaves `$detached` empty, which is byte-identical to a repo holding no
2686
+ // branchless worktree at all. That is the silence #381 exists to end,
2687
+ // reachable by a route no test held. The fixture above is this one's control:
2688
+ // same repo, same detached worktree, and with a working awk it is REMOVED, so
2689
+ // the decline here is the awk's doing and not a fixture that was never
2690
+ // sweepable.
2691
+ const w = repo(t);
2692
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2693
+
2694
+ // Selected on the `/^bare$/` rule, which no other awk program in this script
2695
+ // carries — CONTENT, never argv position, the discipline IGNORED_PROBE states
2696
+ // the reason for. `/^worktree /` and `substr($0,10)` would not do: the branch
2697
+ // sweep's own worktree lookup carries both, so a match on either shims two
2698
+ // call sites at once and this arm stops being what answered. The shim reaches
2699
+ // the script under test only — `withShim` puts it on the PATH `runReap`
2700
+ // passes, while this file's fixtures run `git` at its own absolute path
2701
+ // through `ENV`.
2702
+ const bin = toolFailShim(
2703
+ t,
2704
+ "awk",
2705
+ REAL_AWK,
2706
+ `case "$1" in *'/^bare$/'*) : ;; *) false ;; esac`,
2707
+ ["awk: multibyte conversion failure"],
2708
+ 2,
2709
+ );
2710
+
2711
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
2712
+
2713
+ assert.equal(code, 0, "a listing that could not be parsed is a finding, not a script failure");
2714
+ assert.equal(json.kept.length, 1);
2715
+ assert.equal(json.kept[0].branch, null, "no worktree was ever named, so none can be blamed");
2716
+ assert.equal(
2717
+ json.kept[0].reason,
2718
+ "could not read the worktrees git listed — a branchless one would go unreported",
2719
+ );
2720
+ // The decline must be the WHOLE of the sweep: a removal alongside it would
2721
+ // mean the script acted on a listing it had just said it could not read.
2722
+ assert.deepEqual(json.worktreesRemoved, [], "a decline is not grounds for a partial sweep");
2723
+ assert.equal(existsSync(wt), true, "the worktree the control above removes must survive here");
2724
+ assert.match(stderr, /KEEP \(no branch\) — could not read the worktrees git listed/);
2725
+ assertToolShimFired(bin, "awk", "the awk shim must actually have fired for this fixture");
2726
+ });
2727
+
2728
+ test("a DIRTY detached worktree is kept with a reason, never removed (#381)", (t) => {
2729
+ const w = repo(t);
2730
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2731
+ writeFileSync(join(wt, "scratch.txt"), "uncommitted, exists nowhere else\n");
2732
+
2733
+ const { code, json, stderr } = runReap(w, ["--apply"]);
2734
+
2735
+ assert.equal(code, 0);
2736
+ assert.deepEqual(json.worktreesRemoved, []);
2737
+ assert.equal(existsSync(join(wt, "scratch.txt")), true, "the uncommitted file must survive the run");
2738
+ assert.equal(json.kept.length, 1);
2739
+ assert.equal(json.kept[0].branch, null, "there is no branch to name, and `` would claim there were one");
2740
+ assert.equal(json.kept[0].reason, `dirty worktree ${wt}`);
2741
+ assert.ok(stderr.includes("KEEP"), "silently skipping it is the defect, not the fix");
2742
+ });
2743
+
2744
+ test("a DIRTY detached worktree is kept under status.showUntrackedFiles=no (#730)", (t) => {
2745
+ // The third gate, and the one where the misread costs the FILES rather than
2746
+ // just a branch: this sweep's whole job is removing directories. The branch
2747
+ // sweep never reaches a detached worktree, so its own `-uall` does not cover
2748
+ // this arm — a fix applied to the two sites the ticket named leaves this one
2749
+ // blind, which is why it is pinned separately.
2750
+ const w = repo(t);
2751
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2752
+ writeFileSync(join(wt, "precious.txt"), "uncommitted, exists nowhere else\n");
2753
+ git(w, "config", "status.showUntrackedFiles", "no");
2754
+ assert.equal(git(wt, "status", "--porcelain"), "",
2755
+ "fixture: the config must really silence the unpinned probe, or this test measures nothing");
2756
+
2757
+ const { code, json } = runReap(w, ["--apply"]);
2758
+
2759
+ assert.equal(code, 0);
2760
+ assert.deepEqual(json.worktreesRemoved, []);
2761
+ assert.equal(json.kept.length, 1);
2762
+ assert.equal(json.kept[0].reason, `dirty worktree ${wt}`);
2763
+ assert.equal(readFileSync(join(wt, "precious.txt"), "utf8"), "uncommitted, exists nowhere else\n",
2764
+ "the uncommitted file must survive the run");
2765
+ });
2766
+
2767
+ test("a detached worktree holding commits that exist nowhere else is kept (#381)", (t) => {
2768
+ // The safety this sweep turns on. `git cherry`, not `merge-base
2769
+ // --is-ancestor`: the branch this worktree came from was rebased before it
2770
+ // merged, so a tip that is fully upstream is patch-equivalent rather than an
2771
+ // ancestor, and ancestry would keep every one of them. Here the commit
2772
+ // really is unique, and the probe has to say so.
2773
+ const w = repo(t);
2774
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2775
+ const sole = commit(wt, "sole copy, nowhere else");
2776
+
2777
+ const { code, json } = runReap(w, ["--apply"]);
2778
+
2779
+ assert.equal(code, 0);
2780
+ assert.deepEqual(json.worktreesRemoved, []);
2781
+ assert.equal(existsSync(wt), true);
2782
+ assert.equal(json.kept.length, 1);
2783
+ assert.equal(json.kept[0].reason, `worktree ${wt} holds commits that exist nowhere else`);
2784
+ assert.equal(git(wt, "rev-parse", "HEAD"), sole, "the commit is still reachable from the worktree");
2785
+ });
2786
+
2787
+ test("a detached worktree whose HEAD git cannot resolve is kept, never swept (#381, #179)", (t) => {
2788
+ // An absent `branch` line is what this sweep enumerates on, and a worktree
2789
+ // whose admin `HEAD` is unreadable has none either — git reports the null
2790
+ // object id instead (measured on four corruption routes for #179). Nothing
2791
+ // about such a worktree can be decided, so it is reported and left.
2792
+ //
2793
+ // Garbage content, not a `chmod`: identical signature in the porcelain, and
2794
+ // it reproduces as any user, so the fixture neither leaks a permission bit
2795
+ // on failure nor goes vacuous under euid 0.
2796
+ const w = repo(t);
2797
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2798
+ writeFileSync(join(adminEntry(w, wt), "HEAD"), "not an object id\n");
2799
+ assert.match(
2800
+ git(w, "worktree", "list", "--porcelain"),
2801
+ /HEAD 0{40}/,
2802
+ "fixture: git must report the null object id for this worktree",
2803
+ );
2804
+
2805
+ const { code, json } = runReap(w, ["--apply"]);
2806
+
2807
+ assert.equal(code, 0);
2808
+ assert.deepEqual(json.worktreesRemoved, []);
2809
+ assert.equal(existsSync(wt), true);
2810
+ // The worktree sweep's report, unchanged by #2078. The fixture's own
2811
+ // `[gone]` branch is kept too since #2078: the entry no longer says which
2812
+ // branch it held, so the branch sweep cannot clear any branch against it.
2813
+ const sweep = json.kept.filter((k) => k.branch === null);
2814
+ const branches = json.kept.filter((k) => k.branch !== null);
2815
+ assert.equal(sweep.length, 1);
2816
+ assert.equal(sweep[0].reason, `worktree ${wt} has an unresolvable HEAD — git cannot say what it holds`);
2817
+ assert.deepEqual(branches.map((k) => k.branch), ["docs/79-brief"]);
2818
+ assert.match(branches[0].reason, /^worktree registry inconsistent — git listed a linked worktree with a null HEAD/);
2819
+ assert.equal(branchExists(w, "docs/79-brief"), true);
2820
+ });
2821
+
2822
+ test("a detached worktree with a BISECT in progress is kept — git is no backstop here (#381)", (t) => {
2823
+ // Measured, git 2.50.1 (Apple Git-155): `git worktree remove` WITHOUT
2824
+ // `--force` removes this at exit 0. A bisect detaches and leaves the tree
2825
+ // clean, so the enumeration, the merged probe and the dirty check all pass it
2826
+ // through, and only the in-progress guard stands between it and a removal
2827
+ // that discards the bisect's state.
2828
+ const w = repo(t);
2829
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2830
+ git(wt, "bisect", "start", "HEAD", "HEAD~1");
2831
+ assert.ok(existsSync(join(adminEntry(w, wt), "BISECT_LOG")), "fixture: the bisect must really be running");
2832
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so only the in-progress guard can keep it");
2833
+
2834
+ const { code, json } = runReap(w, ["--apply"]);
2835
+
2836
+ assert.equal(code, 0);
2837
+ assert.deepEqual(json.worktreesRemoved, []);
2838
+ assert.equal(existsSync(wt), true);
2839
+ assert.equal(json.kept.length, 1);
2840
+ assert.match(json.kept[0].reason, /has a git operation in progress \(BISECT_LOG\)/);
2841
+ });
2842
+
2843
+ test("a detached worktree with an INTERRUPTED REBASE is kept — the shape that reaches this sweep (#381)", (t) => {
2844
+ // release-ticket.sh's prose already names the interrupted rebase as the way
2845
+ // a fleet worktree wanders off its branch, and this is where it lands. The
2846
+ // exec fails without moving HEAD, so the merged probe still reads clean and
2847
+ // the guard is what answers — the same discrimination the bisect case makes,
2848
+ // through the other sequencer directory.
2849
+ const w = repo(t);
2850
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2851
+ spawnSync("git", ["rebase", "-q", "-i", "--exec", "false", "HEAD~1"], {
2852
+ cwd: wt,
2853
+ env: { ...ENV, GIT_SEQUENCE_EDITOR: "true" },
2854
+ });
2855
+ assert.ok(existsSync(join(adminEntry(w, wt), "rebase-merge")), "fixture: the rebase must really be stopped");
2856
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so only the in-progress guard can keep it");
2857
+
2858
+ const { code, json } = runReap(w, ["--apply"]);
2859
+
2860
+ assert.equal(code, 0);
2861
+ assert.deepEqual(json.worktreesRemoved, []);
2862
+ assert.equal(existsSync(wt), true);
2863
+ assert.equal(json.kept.length, 1);
2864
+ assert.match(json.kept[0].reason, /has a git operation in progress \(rebase-merge\)/);
2865
+ });
2866
+
2867
+ test("a detached MAIN checkout is kept, with the reason that is true on this path (#381)", (t) => {
2868
+ // The main checkout has no `branch` line either once it is detached, so this
2869
+ // sweep enumerates it. Removing it is impossible and there is no branch of
2870
+ // ours checked out in it to delete, so the reason says only the first — and
2871
+ // it must be answered before the linkage guard below it, whose `-f` test
2872
+ // would call the main checkout's `.git` DIRECTORY a broken linkage (#82).
2873
+ const w = repo(t);
2874
+ git(w, "checkout", "-q", "--detach", "HEAD");
2875
+
2876
+ const { code, json } = runReap(w, ["--apply"]);
2877
+
2878
+ assert.equal(code, 0);
2879
+ assert.deepEqual(json.worktreesRemoved, []);
2880
+ assert.equal(json.kept.length, 1);
2881
+ assert.equal(json.kept[0].reason, `worktree ${w} is the main checkout — cannot remove it`);
2882
+ assert.doesNotMatch(json.kept[0].reason, /linkage/, "the linkage guard must not get to misdescribe it");
2883
+ assert.equal(existsSync(join(w, ".git")), true);
2884
+ });
2885
+
2886
+ test("a detached worktree whose .git file is gone is kept, never removed as clean (#381, #128)", (t) => {
2887
+ // Delete a worktree's `.git` and `git -C` does not fail: it walks UP to the
2888
+ // enclosing repo and answers about THAT at rc 0, which the status call would
2889
+ // otherwise believe is this worktree's own clean status.
2890
+ const w = repo(t);
2891
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2892
+ writeFileSync(join(wt, "precious.txt"), "untracked, and git can no longer see it\n");
2893
+ rmSync(join(wt, ".git"));
2894
+
2895
+ const { code, json } = runReap(w, ["--apply"]);
2896
+
2897
+ assert.equal(code, 0);
2898
+ assert.deepEqual(json.worktreesRemoved, []);
2899
+ assert.equal(json.kept.length, 1);
2900
+ assert.match(json.kept[0].reason, /^worktree .* has no \.git linkage — /);
2901
+ assert.equal(readFileSync(join(wt, "precious.txt"), "utf8"), "untracked, and git can no longer see it\n");
2902
+ });
2903
+
2904
+ test("a NON-FLEET detached worktree is kept, however removable it looks (#381)", (t) => {
2905
+ // The ownership bound, and the reason this sweep needs one. The branch sweep
2906
+ // deletes on evidence the PR merged — `%(upstream:track)` reads `[gone]`.
2907
+ // Here there is no such evidence to read: this fixture is branchless, clean
2908
+ // and patch-equivalent to origin/main, and so is a human's `git worktree add
2909
+ // --detach` scratch checkout that was never a ticket. Unbounded, `--apply`
2910
+ // DELETED it (measured, PR #985 review), ignored files and all — inside a
2911
+ // `.worktrees/` path the `--ignored` probe is skipped too.
2912
+ const w = repo(t);
2913
+ writeFileSync(join(w, ".gitignore"), ".env\n");
2914
+ git(w, "add", ".gitignore");
2915
+ commit(w, "ignore .env");
2916
+ git(w, "push", "-q", "origin", "main");
2917
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed", join(w, "..", "outside"));
2918
+ writeFileSync(join(wt, ".env"), "SECRET=exists nowhere else\n");
2919
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so nothing but the bound can keep it");
2920
+
2921
+ const { code, json } = runReap(w, ["--apply"]);
2922
+
2923
+ assert.equal(code, 0);
2924
+ assert.deepEqual(json.worktreesRemoved, []);
2925
+ assert.equal(json.kept.length, 1);
2926
+ assert.match(json.kept[0].reason, /^worktree .* is not a fleet worktree — outside \.worktrees\/, /, json.kept[0].reason);
2927
+ assert.ok(json.kept[0].reason.includes(wt), `the decline must name which worktree it left: ${json.kept[0].reason}`);
2928
+ assert.ok(existsSync(wt), "the directory must survive");
2929
+ assert.equal(readFileSync(join(wt, ".env"), "utf8"), "SECRET=exists nowhere else\n", "the precious file must survive");
2930
+ });
2931
+
2932
+ test("the same fixture INSIDE .worktrees/ is removed — the control for the bound above (#381)", (t) => {
2933
+ // Without this, the test above passes on a sweep that keeps every detached
2934
+ // worktree: it would pin nothing but a blanket refusal. Byte-identical
2935
+ // fixture, one difference — the path — so the bound is ownership and only
2936
+ // ownership.
2937
+ const w = repo(t);
2938
+ writeFileSync(join(w, ".gitignore"), ".env\n");
2939
+ git(w, "add", ".gitignore");
2940
+ commit(w, "ignore .env");
2941
+ git(w, "push", "-q", "origin", "main");
2942
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2943
+ writeFileSync(join(wt, ".env"), "machine-generated, and a fleet worktree's ignored files are all like this\n");
2944
+
2945
+ const { code, json } = runReap(w, ["--apply"]);
2946
+
2947
+ assert.equal(code, 0);
2948
+ assert.deepEqual(json.worktreesRemoved, [wt]);
2949
+ assert.deepEqual(json.kept, []);
2950
+ assert.equal(existsSync(wt), false);
2951
+ });
2952
+
2953
+ test("a detached worktree whose directory was deleted by hand still has its registration cleared (#381)", (t) => {
2954
+ // The registration is what inflight.sh reads as a live claim, and it outlives
2955
+ // the directory: `worktree list --porcelain` keeps the entry, annotated
2956
+ // prunable, after an `rm -rf`. `git worktree remove` accepts such an entry at
2957
+ // rc 0, so the established-absent case needs no branch of its own.
2958
+ const w = repo(t);
2959
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2960
+ rmSync(wt, { recursive: true, force: true });
2961
+ assert.match(git(w, "worktree", "list", "--porcelain"), /prunable/, "fixture: the stale registration must still be listed");
2962
+
2963
+ const { code, json } = runReap(w, ["--apply"]);
2964
+
2965
+ assert.equal(code, 0);
2966
+ assert.deepEqual(json.worktreesRemoved, [wt]);
2967
+ assert.deepEqual(json.kept, []);
2968
+ assert.doesNotMatch(git(w, "worktree", "list", "--porcelain"), /79-brief/);
2969
+ });
2970
+
2971
+ test("a detached worktree behind an unreadable parent is kept, never removed as absent (#381, #83)", (t) => {
2972
+ // `-e` is false both for a directory that is gone and for one inside a prefix
2973
+ // this script may not search, and only the first is nothing to protect. The
2974
+ // walk up to the nearest existing ancestor is what makes "not there" a
2975
+ // measurement — reused here, not re-answered, so the two sweeps cannot drift.
2976
+ if (process.getuid?.() === 0) return t.skip("root reads every directory");
2977
+ const w = repo(t);
2978
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
2979
+ writeFileSync(join(wt, "unpushed.txt"), "work behind the wall\n");
2980
+ const parent = join(w, ".worktrees");
2981
+
2982
+ // Restored inline, not in a teardown hook: `repo`'s own cleanup is
2983
+ // registered first and would run against a directory it still cannot enter.
2984
+ chmodSync(parent, 0o000);
2985
+ const { code, json } = runReap(w, ["--apply"]);
2986
+ chmodSync(parent, 0o755);
2987
+
2988
+ assert.equal(code, 0);
2989
+ assert.deepEqual(json.worktreesRemoved, []);
2990
+ assert.equal(json.kept.length, 1);
2991
+ assert.equal(json.kept[0].reason, `cannot tell whether worktree ${wt} exists`);
2992
+ });
2993
+
2994
+ test("a detached worktree under a path containing a space is found and removed whole (#381)", (t) => {
2995
+ // The porcelain prints the path raw, so the enumeration reads the whole rest
2996
+ // of the line and the shell splits the pair on the object id's single space
2997
+ // — never on the path's. Read any other way, this worktree is a different,
2998
+ // nonexistent path and every guard above runs against it.
2999
+ const w = repo(t, "work dir");
3000
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3001
+ assert.ok(wt.includes(" "), "fixture");
3002
+
3003
+ const { code, json, stderr } = runReap(w, ["--apply"]);
3004
+
3005
+ assert.equal(code, 0);
3006
+ assert.deepEqual(json.worktreesRemoved, [wt], "the path must arrive whole, not truncated at the space");
3007
+ assert.equal(existsSync(wt), false);
3008
+ assert.ok(stderr.includes(` REMOVED worktree ${wt}`));
3009
+ });
3010
+
3011
+ test("a detached worktree under a path containing a space is found DIRTY and kept (#381)", (t) => {
3012
+ // The other half of the pair above: truncation is not visible from the
3013
+ // removal alone, because a guard that ran against a nonexistent path passes
3014
+ // it. Here the guard has to see the real directory to answer at all.
3015
+ const w = repo(t, "work dir");
3016
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3017
+ writeFileSync(join(wt, "scratch.txt"), "uncommitted\n");
3018
+
3019
+ const { code, json } = runReap(w, ["--apply"]);
3020
+
3021
+ assert.equal(code, 0);
3022
+ assert.deepEqual(json.worktreesRemoved, []);
3023
+ assert.equal(json.kept.length, 1);
3024
+ assert.equal(json.kept[0].reason, `dirty worktree ${wt}`);
3025
+ assert.equal(existsSync(wt), true);
3026
+ });
3027
+
3028
+ test("the dry run reports the detached worktree it would remove, removes nothing, and exits 0 (#381, #265)", (t) => {
3029
+ // The exit-status control for everything this ticket added. #265's own
3030
+ // criterion is that no path in this script exits 1, and its fix works by
3031
+ // keeping the `apply` guard the LAST command of the file; a sweep spliced in
3032
+ // ahead of the payload is exactly the kind of edit that relocates that
3033
+ // defect onto the default mode nobody runs under test. Both fixtures are
3034
+ // load-bearing: the removable one pins that a dry run still promises the
3035
+ // removal, the kept one that a keep on this path is not what makes it exit 0.
3036
+ const w = repo(t);
3037
+ const removable = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3038
+ const dirty = detachedMergedWorktree(w, "docs/80-other", "more work that landed");
3039
+ writeFileSync(join(dirty, "scratch.txt"), "uncommitted\n");
3040
+
3041
+ const { code, json, stderr } = runReap(w, []);
3042
+
3043
+ assert.equal(code, 0, "the default dry run reports its verdict at 0, never a bare 1");
3044
+ assert.equal(json.applied, false);
3045
+ assert.deepEqual(json.worktreesRemoved, [removable], "the dry run still promises the removal");
3046
+ assert.equal(json.kept.length, 1);
3047
+ assert.equal(json.kept[0].reason, `dirty worktree ${dirty}`);
3048
+ assert.ok(stderr.includes(` would remove worktree ${removable}`));
3049
+ assert.doesNotMatch(stderr, /REMOVED worktree/, "a dry run removes nothing");
3050
+ assert.equal(existsSync(removable), true, "a dry run must not remove the worktree it COULD have removed");
3051
+ assert.equal(existsSync(dirty), true);
3052
+ });
3053
+
3054
+ test("an attached worktree is never touched by the branchless sweep (#381)", (t) => {
3055
+ // The accept side of the enumeration itself. A worktree on a branch carries a
3056
+ // `branch` line, so the sweep must not see it at all — including one on a
3057
+ // live branch that is not `[gone]`, which nothing in this script may remove.
3058
+ const w = repo(t);
3059
+ git(w, "worktree", "add", "-q", join(w, ".worktrees", "live"), "-b", "feature/live", "main");
3060
+ const live = join(w, ".worktrees", "live");
3061
+
3062
+ const { code, json, stderr } = runReap(w, ["--apply"]);
3063
+
3064
+ assert.equal(code, 0);
3065
+ assert.deepEqual(json, { applied: true, reaped: [], worktreesRemoved: [], kept: [], warnings: [] });
3066
+ assert.doesNotMatch(stderr, /KEEP/, "a worktree on a live branch is not a finding");
3067
+ assert.equal(existsSync(live), true);
3068
+ assert.equal(branchExists(w, "feature/live"), true);
3069
+ });
3070
+
3071
+ test("a locked detached worktree is kept, its registration reported intact and its path named (#381)", (t) => {
3072
+ // The branch sweep's refusal handling has this coverage; its structurally
3073
+ // duplicated copy in this sweep had NONE — swapping the two state strings, or
3074
+ // replacing the whole reason literal, left the suite at 62/62 (measured,
3075
+ // PR #985 review). A locked worktree exits 128 with the admin entry
3076
+ // untouched, so this is the `registration intact` arm.
3077
+ const w = repo(t);
3078
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3079
+ git(w, "worktree", "lock", wt);
3080
+
3081
+ const { code, json, stderr } = runReap(w, ["--apply"]);
3082
+
3083
+ assert.equal(code, 0, "a refusal is a finding, not a script failure");
3084
+ assert.deepEqual(json.worktreesRemoved, []);
3085
+ assert.equal(json.kept.length, 1);
3086
+ assert.equal(json.kept[0].branch, null, "there is no branch on this path to name");
3087
+ assert.match(
3088
+ json.kept[0].reason,
3089
+ /^worktree .* remove refused \(registration intact\): /,
3090
+ `a refusal that changed nothing must say so, and say which worktree: ${json.kept[0].reason}`,
3091
+ );
3092
+ assert.ok(json.kept[0].reason.includes(wt), `the reason must name the worktree: ${json.kept[0].reason}`);
3093
+ assert.doesNotMatch(json.kept[0].reason, /registration cleared/, "the two outcomes must not collapse into one reason");
3094
+ assert.match(json.kept[0].reason, /locked working tree/, "git's message names the fault");
3095
+ assert.match(json.kept[0].reason, /remove -f -f/, "and the remedy, which only git can supply");
3096
+ assert.doesNotMatch(json.kept[0].reason, /\n/, "git's stderr is multi-line; the reason must be flattened");
3097
+ assert.match(stderr, /KEEP \(no branch\) — worktree .* remove refused/);
3098
+ assert.equal(existsSync(wt), true, "a refused removal removes nothing");
3099
+ });
3100
+
3101
+ test("a refusal that DID clear the registration says cleared, on the branchless path too (#381)", (t) => {
3102
+ // The other arm of the same three-way state, and the reason it exists: a
3103
+ // non-zero exit is no proof the removal had no effect. A directory replaced
3104
+ // by a symlink to itself passes every guard ahead of the removal — `.git` is
3105
+ // a regular file and `git -C` follows the link — and git then deregisters the
3106
+ // entry before failing.
3107
+ const w = repo(t);
3108
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3109
+ const real = symlinkStandIn(wt);
3110
+
3111
+ const { code, json } = runReap(w, ["--apply"]);
3112
+
3113
+ assert.equal(code, 0);
3114
+ assert.deepEqual(json.worktreesRemoved, []);
3115
+ assert.equal(json.kept.length, 1);
3116
+ assert.match(
3117
+ json.kept[0].reason,
3118
+ /^worktree .* remove refused \(registration cleared\): /,
3119
+ `a refusal that unregistered the worktree must not read as a no-op: ${json.kept[0].reason}`,
3120
+ );
3121
+ assert.ok(json.kept[0].reason.includes(wt), `the reason must name the worktree: ${json.kept[0].reason}`);
3122
+ const reg = git(w, "worktree", "list", "--porcelain").split("\n");
3123
+ assert.ok(!reg.includes(`worktree ${wt}`), `the refused worktree's registration really is gone: ${reg.join(" | ")}`);
3124
+ assert.ok(lstatSync(wt).isSymbolicLink(), "the stand-in symlink must survive");
3125
+ assert.equal(existsSync(real), true, "the orphaned directory is not this script's to delete");
3126
+ });
3127
+
3128
+ test("TWO refused worktrees produce two distinguishable declines (#381)", (t) => {
3129
+ // One refusal cannot catch this, which is why 1316 green tests did not: the
3130
+ // branch field is `null` on this path and git's message for a locked worktree
3131
+ // carries no path, so before the reason interpolated `$wt` the two entries
3132
+ // were byte-identical and an operator could not tell which was which
3133
+ // (measured, PR #985 review).
3134
+ const w = repo(t);
3135
+ const alpha = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3136
+ const beta = detachedMergedWorktree(w, "docs/80-other", "more work that landed");
3137
+ git(w, "worktree", "lock", alpha);
3138
+ git(w, "worktree", "lock", beta);
3139
+
3140
+ const { code, json } = runReap(w, ["--apply"]);
3141
+
3142
+ assert.equal(code, 0);
3143
+ assert.deepEqual(json.worktreesRemoved, []);
3144
+ assert.equal(json.kept.length, 2);
3145
+ assert.notEqual(json.kept[0].reason, json.kept[1].reason, "two refusals must not read as one");
3146
+ const reasons = json.kept.map((k) => k.reason).join("\n");
3147
+ assert.ok(reasons.includes(alpha), `the declines must name alpha: ${reasons}`);
3148
+ assert.ok(reasons.includes(beta), `the declines must name beta: ${reasons}`);
3149
+ });
3150
+
3151
+ test("a `+` inside a cherry diagnostic does not strand a detached worktree (#381)", (t) => {
3152
+ // The anchor, pinned for this sweep's own separately-duplicated copy of the
3153
+ // check. Dropping the `^` from `grep -q '^+'` at the branchless cherry probe
3154
+ // left the suite at 62/62 (measured, PR #985 review) — none of the #381
3155
+ // fixtures put a `+` anywhere the capture could see one.
3156
+ //
3157
+ // The `+` has to come from STDERR, not from a commit subject: `git cherry`
3158
+ // without `-v` prints `+ <sha>` / `- <sha>` and no subject at all, so a
3159
+ // fixture message containing a `+` never reaches the value being matched
3160
+ // (measured). Same shim shape as the branch sweep's twin above — the warning
3161
+ // rides in the `match`, which then falls through to the real git, so the
3162
+ // check still reads a genuine cherry run's stdout.
3163
+ const w = repo(t);
3164
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3165
+ const bin = failOnlyShim(t, `[ "$1" = cherry ] && { printf '%s\\n' "warning: unable to access '/x/c++/lib/.gitattributes'" >&2; ${SHIM_FIRED}; false; }`, []);
3166
+
3167
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3168
+
3169
+ // `mergedGoneBranchWithWorktree` leaves `refs/heads/docs/79-brief` behind —
3170
+ // detaching the worktree's HEAD un-checks-out the branch, it doesn't delete
3171
+ // it — so the BRANCH sweep also sees this same name as `[gone]` and runs its
3172
+ // own `git cherry`, which the bare match above fires on too. Since #2219 that
3173
+ // probe targets the tip SHA it read, not `refs/heads/...`, and the tip is the
3174
+ // very commit this worktree's HEAD sits on, so the two argvs are identical.
3175
+ // The COUNT is what proves THIS sweep's own probe fired too: one line is the
3176
+ // branch sweep's alone. #759
3177
+ const CHERRY_SHA = /^cherry \S+ [0-9a-f]{40}$/;
3178
+ assertShimFired(bin, "no `+` ever reached this sweep's cherry probe — the rest of this arm passes on any fixture");
3179
+ assert.equal(
3180
+ readFileSync(join(bin, "git.fired"), "utf8").split("\n").filter((l) => CHERRY_SHA.test(l)).length,
3181
+ 2,
3182
+ "both sweeps' cherry probes fired — the branch sweep's and this one's",
3183
+ );
3184
+ assert.equal(code, 0);
3185
+ assert.deepEqual(json.kept, [], "a `+` inside a diagnostic is not an unmerged commit");
3186
+ assert.deepEqual(json.worktreesRemoved, [wt], "noisy stderr must not strand a merged worktree");
3187
+ assert.equal(existsSync(wt), false);
3188
+ });
3189
+
3190
+ // #1419. `grep -q` answers three ways and every call site in reap.sh read two:
3191
+ // rc 0 a line matched, rc 1 none did, rc 2+ grep could not finish the scan at
3192
+ // all. Under `-q` both POSIX and GNU reserve 0 for a match even when an error
3193
+ // also occurred, so an rc 2 means specifically "no match AND the scan broke" —
3194
+ // and a bare `if … | grep -q …; then` files that 2 under no-match, which at the
3195
+ // two merged-commit checks is the arm that authorizes `git branch -D` and
3196
+ // `git worktree remove`.
3197
+ //
3198
+ // Measured on `origin/main` with the shims below, all four sites: the branch
3199
+ // was REAPED, the worktree DIRECTORY removed, and both registry re-reads
3200
+ // reported `registration cleared` about a listing nothing had read — every one
3201
+ // at exit 0 with the fault plainly on stderr. Same misattribution as #789 and
3202
+ // #1413, one tool further down the same pipelines.
3203
+ //
3204
+ // The shims select on the PATTERN, never on a flag spelling or an argv
3205
+ // position. This fix respelled `-qxF` as `-q -xF -e …`, and a shim matching
3206
+ // `-xF` stopped firing on the new spelling and went green vacuously —
3207
+ // measured while writing these, on the `origin/main` comparison runs, which is
3208
+ // #730's lesson arriving in a third place.
3209
+
3210
+ /**
3211
+ * A PATH `grep` that exits `code` having matched nothing, whenever `match`
3212
+ * holds against its argv. `code` defaults to 2, the status a grep that could
3213
+ * not finish scanning leaves under `-q`; pass 1 for a scan that COMPLETED and
3214
+ * merely warned.
3215
+ */
3216
+ function grepFailShim(t, match, code = 2) {
3217
+ return toolFailShim(t, "grep", REAL_GREP, match, ["grep: illegal byte sequence"], code);
3218
+ }
3219
+
3220
+ // The two merged-commit checks. Both sweeps pass the same `^+`, so unlike the
3221
+ // `git cherry` shims above the recorded argv cannot say WHICH one fired — the
3222
+ // REASONS discriminate instead, and each test below asserts its own sweep's
3223
+ // wording rather than settling for presence.
3224
+ const CHERRY_SCAN = `case " $* " in *" ^+ "*) : ;; *) false ;; esac`;
3225
+
3226
+ // The two registry re-reads: the only greps in a run whose pattern begins
3227
+ // `worktree `.
3228
+ const REGISTRY_SCAN = `case " $* " in *" worktree "*) : ;; *) false ;; esac`;
3229
+
3230
+ test("a cherry scan that could not scan does not authorize `git branch -D` (#1419)", (t) => {
3231
+ const w = repo(t);
3232
+ mergedGoneBranch(w, "feature/merged", "merged work");
3233
+ const bin = grepFailShim(t, CHERRY_SCAN);
3234
+
3235
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3236
+
3237
+ assertToolShimFired(bin, "grep", "the cherry scan never ran — this arm passes on any fixture", /\^\+/);
3238
+ assert.equal(code, 0);
3239
+ assert.deepEqual(json.reaped, [], "a scan that never looked is not a clean merge verdict");
3240
+ assert.equal(branchExists(w, "feature/merged"), true,
3241
+ "the branch whose merge status no tool established must survive");
3242
+ assert.equal(json.kept.length, 1);
3243
+ assert.match(json.kept[0].reason, /cannot tell if merged/,
3244
+ `an unscanned cherry is unknown, not merged: ${json.kept[0].reason}`);
3245
+ assert.match(json.kept[0].reason, /illegal byte sequence/,
3246
+ "and the scan's own cause reaches the payload, per #625 at git_probe");
3247
+ assert.doesNotMatch(json.kept[0].reason, /unmerged commits/,
3248
+ "nor is it a positive unmerged verdict — nothing was read in either direction");
3249
+ });
3250
+
3251
+ test("a cherry scan that could not scan does not authorize removing the DIRECTORY (#1419)", (t) => {
3252
+ const w = repo(t);
3253
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3254
+ const bin = grepFailShim(t, CHERRY_SCAN);
3255
+
3256
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3257
+
3258
+ assertToolShimFired(bin, "grep", "this sweep's cherry scan never ran", /\^\+/);
3259
+ assert.equal(code, 0);
3260
+ assert.deepEqual(json.worktreesRemoved, [], "a directory is not deleted on a scan that never completed");
3261
+ assert.equal(existsSync(wt), true, "the only copy of that commit is still on disk");
3262
+ assert.deepEqual(json.reaped, []);
3263
+ // `detachedMergedWorktree` leaves refs/heads/docs/79-brief behind, so the
3264
+ // BRANCH sweep meets the same name as [gone] and its own scan fails too.
3265
+ // Two entries, and #985's ruling is that two refusals must not read as one.
3266
+ assert.equal(json.kept.length, 2);
3267
+ const wtEntry = json.kept.find((k) => k.branch === null);
3268
+ assert.ok(wtEntry, `the branchless sweep's own refusal must be present: ${JSON.stringify(json.kept)}`);
3269
+ assert.ok(wtEntry.reason.includes(`cannot tell if worktree ${wt} is merged`),
3270
+ `and must name the worktree it declined to remove: ${wtEntry.reason}`);
3271
+ assert.notEqual(json.kept[0].reason, json.kept[1].reason,
3272
+ "the two sweeps' refusals must stay distinguishable");
3273
+ });
3274
+
3275
+ test("a registry re-read whose scan fails is unknown, never 'registration cleared' (#1419)", (t) => {
3276
+ // The git-side half of this sentence is already pinned above (#391): a
3277
+ // `worktree list` that dies must not read as cleared. This is the GREP-side
3278
+ // half the same fix left open. The lock is what makes the fixture decisive —
3279
+ // the registration is provably INTACT, and `origin/main` reported it
3280
+ // `cleared`: the more alarming of the two states, asserted as a measurement,
3281
+ // about a listing nothing managed to read.
3282
+ const w = repo(t);
3283
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
3284
+ git(w, "worktree", "lock", wt);
3285
+ const bin = grepFailShim(t, REGISTRY_SCAN);
3286
+
3287
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3288
+
3289
+ assertToolShimFired(bin, "grep", "the registry scan never ran — this arm passes on any fixture", /worktree /);
3290
+ assert.equal(code, 0);
3291
+ assert.equal(json.kept.length, 1);
3292
+ assert.match(json.kept[0].reason, /cannot tell whether the registration survived/,
3293
+ `an unscanned registry is unknown, not a measurement: ${json.kept[0].reason}`);
3294
+ assert.doesNotMatch(json.kept[0].reason, /registration cleared/, "the alarming state must never be guessed");
3295
+ assert.doesNotMatch(json.kept[0].reason, /registration intact/, "nor the reassuring one");
3296
+ assert.match(json.kept[0].reason, /illegal byte sequence/, "and the scan's own cause reaches the operator");
3297
+ assert.match(json.kept[0].reason, /locked working tree/, "git's reason for the refusal still reaches the payload");
3298
+ });
3299
+
3300
+ test("the branchless sweep's OWN registry re-read is unknown too when its scan fails (#1419)", (t) => {
3301
+ // The fourth of four sites, and the one the ticket did not name: this sweep
3302
+ // carries its own copy of the registry re-read, byte-identical to the branch
3303
+ // sweep's. A fix that lands in one copy and not its twin is the shape this
3304
+ // file is full of second tickets for (#622, #985, #1441), so the twin gets a
3305
+ // fixture rather than a comment claiming the first one covers it.
3306
+ //
3307
+ // The leftover branch is deleted so ONLY this sweep sees the worktree:
3308
+ // `detachedMergedWorktree` leaves refs/heads behind, and the branch sweep
3309
+ // would otherwise reach the removal first and produce the entry the test
3310
+ // above already pins.
3311
+ const w = repo(t);
3312
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3313
+ git(w, "branch", "-D", "docs/79-brief");
3314
+ git(w, "worktree", "lock", wt);
3315
+ const bin = grepFailShim(t, REGISTRY_SCAN);
3316
+
3317
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3318
+
3319
+ assertToolShimFired(bin, "grep", "this sweep's registry scan never ran", /worktree /);
3320
+ assert.equal(code, 0);
3321
+ assert.deepEqual(json.reaped, []);
3322
+ assert.deepEqual(json.worktreesRemoved, []);
3323
+ assert.equal(json.kept.length, 1);
3324
+ assert.equal(json.kept[0].branch, null, "this sweep's entry names no branch");
3325
+ assert.match(json.kept[0].reason, /cannot tell whether the registration survived/,
3326
+ `the twin must answer the same way: ${json.kept[0].reason}`);
3327
+ assert.doesNotMatch(json.kept[0].reason, /registration cleared/, "the alarming state must never be guessed here either");
3328
+ assert.doesNotMatch(json.kept[0].reason, /registration intact/, "nor the reassuring one");
3329
+ });
3330
+
3331
+ test("a cherry scan that COMPLETES and merely warns still reaps (#1419)", (t) => {
3332
+ // What the new guard must not refuse, and the reason it reads grep's rc
3333
+ // rather than grep's stderr. `gp_cut_short`'s comment in reap.sh records the
3334
+ // measured cost of gating on "anything on stderr": an operator's broken
3335
+ // gitconfig makes tools warn at a SUCCESS status with their output complete,
3336
+ // and a stderr gate then strands every branch it guards for as long as the
3337
+ // config stays broken, blaming the branch for the fault. That wrong gate is
3338
+ // available one tool further down, so the rc-1 arm is pinned with a scan
3339
+ // that answers "no match" AND writes to stderr: the verdict is real, the
3340
+ // branch is merged, and the reap has to proceed.
3341
+ //
3342
+ // The fail-closed tests above cannot catch that mutation — they assert a
3343
+ // KEEP, which a stderr gate also produces. Only an ACCEPT can.
3344
+ const w = repo(t);
3345
+ mergedGoneBranch(w, "feature/merged", "merged work");
3346
+ const bin = grepFailShim(t, CHERRY_SCAN, 1);
3347
+
3348
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3349
+
3350
+ assertToolShimFired(bin, "grep", "the warning never reached a scan — this arm reaps on any fixture", /\^\+/);
3351
+ assert.equal(code, 0);
3352
+ assert.deepEqual(json.reaped, ["feature/merged"],
3353
+ "rc 1 is a verdict: no `+` line, so the branch is merged and reapable");
3354
+ assert.deepEqual(json.kept, [], "a warning is not a failure to scan");
3355
+ assert.equal(branchExists(w, "feature/merged"), false);
3356
+ });
3357
+
3358
+ test("a bare repo in the registry is not diagnosed as an unresolvable HEAD (#381)", (t) => {
3359
+ // `git worktree list --porcelain` prints `worktree <path>` then `bare` and
3360
+ // NOTHING else for a bare repo used as a worktree root — no HEAD line, no
3361
+ // branch line (measured, git 2.50.1 Apple Git-155). Without a case of its own
3362
+ // the parser emitted it with an empty object id, which the null-object-id arm
3363
+ // then reported as "has an unresolvable HEAD — git cannot say what it holds":
3364
+ // a false diagnosis, since git says exactly what it holds, no working tree at
3365
+ // all. The detached worktree alongside it is the positive control — the run
3366
+ // still does its job.
3367
+ const w = repo(t);
3368
+ const bare = join(w, "..", "origin.git");
3369
+ const wt = join(w, "..", ".worktrees", "off-bare");
3370
+ // reap.sh fetches before it reads anything, so the bare repo needs an
3371
+ // `origin` to fetch — itself, which is enough to make `origin/main` and keep
3372
+ // the fixture to one repo.
3373
+ git(bare, "remote", "add", "origin", ".");
3374
+ git(bare, "worktree", "add", "-q", "--detach", wt, "main");
3375
+ assert.match(git(wt, "worktree", "list", "--porcelain"), /^bare$/m, "fixture: the registry must carry a bare entry");
3376
+
3377
+ // Run from the bare root, not from `wt`: `--apply` removes `wt`, and from
3378
+ // inside it this sweep now refuses that removal as the working directory the
3379
+ // run itself was started in (#992) — a different subject, and one that would
3380
+ // leave this fixture's removal unasserted.
3381
+ //
3382
+ // No `BASE_REF` override: this arm passed `main` before #924's accept-list,
3383
+ // which refuses a local branch. The fetch above populates
3384
+ // `refs/remotes/origin/main` in the bare repo too — the comment on the
3385
+ // `remote add` says as much — so the default base is what this fixture always
3386
+ // had available, and the subject here is the registry's bare entry, not the
3387
+ // base.
3388
+ const { code, json } = runReap(bare, ["--apply"]);
3389
+
3390
+ assert.equal(code, 0);
3391
+ assert.deepEqual(json.kept, [], `the bare root is not a finding: ${JSON.stringify(json.kept)}`);
3392
+ assert.deepEqual(json.worktreesRemoved, [wt], "and the detached worktree beside it is still swept");
3393
+ });
3394
+
3395
+ // #992. `--apply` removes worktrees, and the fleet's `.worktrees/` home is
3396
+ // exactly where a member stands when it runs this — so the worktree the script
3397
+ // is running FROM was itself eligible for removal. Removing it deletes the
3398
+ // script's own cwd, and every git call after that dies with
3399
+ // `fatal: Unable to read current working directory`: measured (git 2.50.1,
3400
+ // Apple Git-155) as `REMOVED worktree …` followed by a failed
3401
+ // `git worktree prune` at exit 2, from a run whose every removal SUCCEEDED.
3402
+ //
3403
+ // Refusing that one directory, rather than chdir-ing somewhere durable before
3404
+ // the prune: the prune is the LAST call that needs a cwd, not the only one —
3405
+ // the removals of the worktrees enumerated after this one, and the branch
3406
+ // sweep's own `git branch -D`, need one too, and a chdir at the foot of the
3407
+ // file leaves all of those still broken. Both fixtures below therefore carry a
3408
+ // SECOND subject the run must still act on, so a blanket stand-down cannot
3409
+ // pass them.
3410
+ test("the branchless sweep refuses the worktree the run is standing in, and still exits 0 (#992)", (t) => {
3411
+ const w = repo(t);
3412
+ const here = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3413
+ const other = detachedMergedWorktree(w, "docs/80-other", "more work that landed");
3414
+
3415
+ const { code, json, stderr } = runReap(here, ["--apply"]);
3416
+
3417
+ assert.equal(code, 0, `every removal succeeded, so the run must exit 0: ${stderr}`);
3418
+ assert.equal(existsSync(here), true, "the directory this run was started in must survive");
3419
+ assert.deepEqual(json.worktreesRemoved, [other], "the refusal covers one directory, not the sweep");
3420
+ assert.equal(existsSync(other), false, "and the worktree beside it is still removed");
3421
+ assert.equal(json.kept.length, 1, `exactly one finding: ${JSON.stringify(json.kept)}`);
3422
+ assert.equal(json.kept[0].branch, null, "this sweep has no branch to name");
3423
+ assert.equal(
3424
+ json.kept[0].reason,
3425
+ `worktree ${here} holds the working directory this run was started in — removing it would delete the cwd every git call after it needs; rerun from outside it`,
3426
+ );
3427
+ assert.ok(stderr.includes("KEEP"), "silently walking past it is the defect, not the fix");
3428
+ assert.doesNotMatch(stderr, /Unable to read current working directory/, "the defect's own signature");
3429
+ assert.doesNotMatch(stderr, /prune failed/, "housekeeping that can run must not report a failure");
3430
+ });
3431
+
3432
+ // The same subject on the other sweep, and the shape the refuting vote in the
3433
+ // PR review measured against the pre-#381 script: a branch-carrying merged
3434
+ // `[gone]` worktree, which the branch sweep removes on its own. Here the branch
3435
+ // is checked out in that worktree, so keeping the directory keeps the branch
3436
+ // with it — the same pairing the main-checkout decline already states, and the
3437
+ // reason `git branch -D` would refuse it anyway.
3438
+ test("the branch sweep refuses the worktree the run is standing in, and keeps its branch with it (#992)", (t) => {
3439
+ const w = repo(t);
3440
+ const here = mergedGoneBranchWithWorktree(w, "feature/here", "work that landed");
3441
+ mergedGoneBranch(w, "feature/elsewhere", "also landed");
3442
+
3443
+ const { code, json, stderr } = runReap(here, ["--apply"]);
3444
+
3445
+ assert.equal(code, 0, `every removal succeeded, so the run must exit 0: ${stderr}`);
3446
+ assert.equal(existsSync(here), true, "the directory this run was started in must survive");
3447
+ assert.deepEqual(json.worktreesRemoved, []);
3448
+ assert.deepEqual(json.reaped, ["feature/elsewhere"], "the rest of the sweep still runs");
3449
+ assert.equal(branchExists(w, "feature/here"), true, "the branch checked out in that worktree is kept with it");
3450
+ assert.equal(json.kept.length, 1, `exactly one finding: ${JSON.stringify(json.kept)}`);
3451
+ assert.equal(json.kept[0].branch, "feature/here", "this sweep has a branch to name, and kept it");
3452
+ assert.match(json.kept[0].reason, /holds the working directory this run was started in/);
3453
+ assert.doesNotMatch(stderr, /Unable to read current working directory/, "the defect's own signature");
3454
+ assert.doesNotMatch(stderr, /prune failed/, "housekeeping that can run must not report a failure");
3455
+ });
3456
+
3457
+ // The dry run has to predict the refusal, for the reason #82 records for the
3458
+ // main-checkout decline: a `would remove worktree` line the following
3459
+ // `--apply` refuses is a promise this script cannot keep, and the two modes
3460
+ // disagreeing about a fixed structural fact is the defect that guard exists to
3461
+ // stop. Deterministic here in a way #391's refusals are not — the cwd is known
3462
+ // before anything is removed, so unlike git's own decline it CAN be predicted.
3463
+ test("the dry run predicts that refusal instead of promising a removal (#992)", (t) => {
3464
+ const w = repo(t);
3465
+ const here = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3466
+
3467
+ const { code, json, stderr } = runReap(here, []);
3468
+
3469
+ assert.equal(code, 0);
3470
+ assert.equal(json.applied, false);
3471
+ assert.deepEqual(json.worktreesRemoved, []);
3472
+ assert.equal(json.kept.length, 1, `exactly one finding: ${JSON.stringify(json.kept)}`);
3473
+ assert.match(json.kept[0].reason, /holds the working directory this run was started in/);
3474
+ assert.doesNotMatch(stderr, /would remove worktree/, "a dry run must not promise a removal --apply refuses (#82)");
3475
+ });
3476
+
3477
+ test("the design spec's script-surface row carries the two declines only this sweep emits (#381)", (t) => {
3478
+ // Same derivation as the pins above: read the label off a live run, then
3479
+ // require the document to carry it. These two are the ones a reader cannot
3480
+ // infer from the branch sweep — the ownership bound has no counterpart there
3481
+ // at all, and the refusal decline is the only one on this path where the
3482
+ // worktree path IS the identifier, since `branch` is null.
3483
+ const w = repo(t);
3484
+ const foreign = detachedMergedWorktree(w, "docs/79-brief", "work that landed", join(w, "..", "outside"));
3485
+ const locked = detachedMergedWorktree(w, "docs/80-other", "more work that landed");
3486
+ git(w, "worktree", "lock", locked);
3487
+
3488
+ const { json } = runReap(w, ["--apply"]);
3489
+
3490
+ const reasons = json.kept.map((k) => k.reason);
3491
+ const bound = /(is not a fleet worktree — outside \.worktrees\/)/.exec(reasons.join("\n"));
3492
+ const refused = /(remove refused) \(/.exec(reasons.join("\n"));
3493
+ assert.ok(bound, `fixture must reach the ownership decline: ${reasons.join(" | ")}`);
3494
+ assert.ok(refused, `fixture must reach the refusal decline: ${reasons.join(" | ")}`);
3495
+ assert.ok(reasons.some((r) => r.includes(foreign)) && reasons.some((r) => r.includes(locked)), reasons.join(" | "));
3496
+
3497
+ const row = specRow();
3498
+ for (const label of [bound[1], refused[1]]) {
3499
+ assert.ok(row.includes(label), `the spec row must quote this decline verbatim, and does not carry "${label}".\nrow: ${row}`);
3500
+ }
3501
+ });
3502
+
3503
+ // Same reason and the same derivation as the cherry-probe and refusal-state
3504
+ // pins above. This one guards the safety claim a reader is most likely to draw
3505
+ // wrong: git refuses a removal on modified and untracked files, so a reader who
3506
+ // knows that would assume it also refuses one mid-operation. It does not, and
3507
+ // the row has to say which decline covers that.
3508
+ test("the design spec's script-surface row carries the in-progress decline this sweep emits (#381)", (t) => {
3509
+ const w = repo(t);
3510
+ const wt = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3511
+ git(wt, "bisect", "start", "HEAD", "HEAD~1");
3512
+
3513
+ const { json } = runReap(w, ["--apply"]);
3514
+
3515
+ // Everything from the label up to the state git named: the path is the
3516
+ // caller's to vary and the state is one of several, so neither can be carried
3517
+ // by a document.
3518
+ const label = /(has a git operation in progress) \(/.exec(json.kept[0]?.reason ?? "");
3519
+ assert.ok(label, `fixture must reach the in-progress decline: ${json.kept[0]?.reason}`);
3520
+
3521
+ const row = specRow();
3522
+ assert.ok(
3523
+ row.includes(label[1]),
3524
+ `the spec row must quote this decline verbatim, and does not carry "${label[1]}".\nrow: ${row}`,
3525
+ );
3526
+ // The payload shape a reader parses against, stated where the reasons are.
3527
+ assert.ok(row.includes("worktreesRemoved[]"), `the row must state the key this sweep writes.\nrow: ${row}`);
3528
+ });
3529
+
3530
+ // Same derivation as the pins above, for the one decline in this script that
3531
+ // is not about its subject at all: it names where the run was INVOKED from,
3532
+ // and its remedy is to invoke it somewhere else. A reader who knows every
3533
+ // worktree guard above still cannot infer that a removable worktree survives a
3534
+ // run started inside it, so the row has to say so. #992
3535
+ test("the design spec's script-surface row carries the standing-in-it decline both sweeps emit (#992)", (t) => {
3536
+ const w = repo(t);
3537
+ const here = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3538
+
3539
+ const { json } = runReap(here, ["--apply"]);
3540
+
3541
+ // Up to the path only: the path is the caller's to vary, the label is what a
3542
+ // document can carry.
3543
+ const label = /(holds the working directory this run was started in)/.exec(json.kept[0]?.reason ?? "");
3544
+ assert.ok(label, `fixture must reach the standing-in-it decline: ${json.kept[0]?.reason}`);
3545
+
3546
+ const row = specRow();
3547
+ assert.ok(
3548
+ row.includes(label[1]),
3549
+ `the spec row must quote this decline verbatim, and does not carry "${label[1]}".\nrow: ${row}`,
3550
+ );
3551
+ });
3552
+
3553
+ // #1441 (finding 1). `self_wt` used to fold EVERY failure of this probe into
3554
+ // the same empty-string case as a genuine "not in a worktree" answer, via
3555
+ // `|| self_wt=`. That silently disabled both cwd-delete guards above whenever
3556
+ // the probe failed for any reason other than the two documented ones. This
3557
+ // shim fails ONLY `rev-parse --show-toplevel` — every other git call,
3558
+ // including `rev-parse --git-dir` at the top of the script, is real — with a
3559
+ // message that is neither known "not in a worktree" answer, reproducing the
3560
+ // exact defect #992 fixed: run from a worktree slated for removal, `--apply`
3561
+ // used to remove it.
3562
+ test("an unrecognised git rev-parse --show-toplevel failure fails the whole run closed, rather than disabling the cwd-delete guard (#1441)", (t) => {
3563
+ const w = repo(t);
3564
+ const here = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3565
+ const bin = failOnlyShim(
3566
+ t,
3567
+ `[ "$1" = rev-parse ] && [ "$2" = --show-toplevel ]`,
3568
+ ["fatal: unable to read current working directory: No such file or directory"],
3569
+ 128,
3570
+ );
3571
+
3572
+ const { code, json, stderr } = runReap(here, ["--apply"], withShim(bin));
3573
+
3574
+ assertShimFired(bin, "the probe never reached the script under test");
3575
+ assert.equal(code, 2, "an unrecognised probe failure must refuse loudly, not fall through to a silent pass");
3576
+ assert.equal(json, null, "a run that dies before the sweep must not also print a payload claiming one ran");
3577
+ assert.equal(existsSync(here), true, "the worktree this run is standing in must survive an unverified cwd guard");
3578
+ assert.match(stderr, /rev-parse --show-toplevel/, "the message must name the probe that broke, not just a downstream symptom");
3579
+ });
3580
+
3581
+ // #1441 (finding 2). Both cwd-delete guards compared `$wt` to `$self_wt` by
3582
+ // EXACT equality, so they missed the ANCESTOR case: cwd nested inside a
3583
+ // worktree slated for removal (SKILL.md:2407 — "a member can commit in a
3584
+ // nested worktree" — is the same real shape). `--apply` used to remove the
3585
+ // outer worktree, deleting the cwd, taking the nested worktree's uncommitted
3586
+ // file with it. `.gitignore` excludes the nested path so the outer worktree's
3587
+ // own dirty check (line 649/1004 above) does not see it — mirroring the
3588
+ // fleet's real layout, where a linked worktree's home is itself gitignored by
3589
+ // the enclosing checkout.
3590
+ function ignoreNestedWorktrees(w) {
3591
+ writeFileSync(join(w, ".gitignore"), "nested/\n");
3592
+ git(w, "add", ".gitignore");
3593
+ git(w, "commit", "-q", "-m", "ignore nested worktrees");
3594
+ }
3595
+
3596
+ test("the branch sweep keeps the outer worktree when cwd is a worktree NESTED inside it, not only when cwd equals it exactly (#1441)", (t) => {
3597
+ const w = repo(t);
3598
+ ignoreNestedWorktrees(w);
3599
+ const outer = mergedGoneBranchWithWorktree(w, "feature/outer", "work that landed");
3600
+ const inner = join(outer, "nested");
3601
+ git(w, "worktree", "add", "-q", "--detach", inner, "main");
3602
+ writeFileSync(join(inner, "wip.txt"), "work that exists nowhere else\n");
3603
+
3604
+ const { code, json, stderr } = runReap(inner, ["--apply"]);
3605
+
3606
+ assert.equal(code, 0, `every removal must still succeed: ${stderr}`);
3607
+ assert.equal(existsSync(outer), true, "the ancestor worktree holding cwd must survive, not only an exact-path match");
3608
+ assert.equal(existsSync(inner), true, "and the nested worktree, and its uncommitted file, along with it");
3609
+ assert.equal(readFileSync(join(inner, "wip.txt"), "utf8"), "work that exists nowhere else\n");
3610
+ assert.equal(branchExists(w, "feature/outer"), true, "the branch checked out in the surviving outer worktree is kept with it");
3611
+ assert.deepEqual(json.worktreesRemoved, [], "the ancestor guard must stop this removal before it starts");
3612
+ // Two independent findings, not one: the ancestor guard keeps `outer`
3613
+ // (this test's subject), and `inner` is separately kept by its OWN dirty
3614
+ // check — it holds the uncommitted `wip.txt` this fixture put there. That
3615
+ // second finding is orthogonal to the fix under test: it would fire even
3616
+ // with cwd elsewhere, and does not by itself stop `outer`'s removal from
3617
+ // deleting `inner` right along with it — only the ancestor guard does.
3618
+ const outerFinding = json.kept.find((k) => k.reason.startsWith(`worktree ${outer} `));
3619
+ assert.ok(outerFinding, `the outer worktree must be its own reported finding: ${JSON.stringify(json.kept)}`);
3620
+ assert.equal(outerFinding.branch, "feature/outer");
3621
+ assert.match(outerFinding.reason, /holds the working directory this run was started in/);
3622
+ });
3623
+
3624
+ test("the branchless sweep keeps the outer worktree when cwd is a worktree NESTED inside it, not only when cwd equals it exactly (#1441)", (t) => {
3625
+ const w = repo(t);
3626
+ ignoreNestedWorktrees(w);
3627
+ const outer = detachedMergedWorktree(w, "docs/79-brief", "work that landed");
3628
+ const inner = join(outer, "nested");
3629
+ git(w, "worktree", "add", "-q", "--detach", inner, "main");
3630
+ writeFileSync(join(inner, "wip.txt"), "work that exists nowhere else\n");
3631
+
3632
+ const { code, json, stderr } = runReap(inner, ["--apply"]);
3633
+
3634
+ assert.equal(code, 0, `every removal must still succeed: ${stderr}`);
3635
+ assert.equal(existsSync(outer), true, "the ancestor worktree holding cwd must survive, not only an exact-path match");
3636
+ assert.equal(existsSync(inner), true, "and the nested worktree, and its uncommitted file, along with it");
3637
+ assert.equal(readFileSync(join(inner, "wip.txt"), "utf8"), "work that exists nowhere else\n");
3638
+ assert.deepEqual(json.worktreesRemoved, [], "the ancestor guard must stop this removal before it starts");
3639
+ // See the branch sweep's copy of this test for why two findings, not one:
3640
+ // `inner`'s own dirty check keeps it independently of the ancestor guard,
3641
+ // which is what protects `outer` — the actual subject here.
3642
+ const outerFinding = json.kept.find((k) => k.reason.startsWith(`worktree ${outer} `));
3643
+ assert.ok(outerFinding, `the outer worktree must be its own reported finding: ${JSON.stringify(json.kept)}`);
3644
+ assert.equal(outerFinding.branch, null, "this sweep has no branch to name");
3645
+ assert.match(outerFinding.reason, /holds the working directory this run was started in/);
3646
+ });
3647
+
3648
+ test("a [gone] branch whose worktree path holds a newline is kept, never reaped (#551)", (t) => {
3649
+ // The branch sweep matched on the `branch` line, so the MATCH was never
3650
+ // affected — only the path it reported and acted on, which the plain
3651
+ // porcelain cut at the newline. Measured before the fix on this shape: the
3652
+ // dry run printed `would remove worktree …/33-slug`, a path not on disk, and
3653
+ // `reaped:["…"]` with it.
3654
+ const w = repo(t);
3655
+ mergedGoneBranchWithWorktree(w, "feature/newline", "merged work", join(w, ".worktrees", "33-slug\ntail"));
3656
+ // ACCEPT, in the SAME run and the same listing: an ordinary [gone] branch
3657
+ // must still be reaped. Without it a `nl_path` hard-wired true passes every
3658
+ // assertion below while stranding the whole sweep.
3659
+ const ok = mergedGoneBranchWithWorktree(w, "feature/ordinary", "merged work");
3660
+
3661
+ const { json } = runReap(w, []);
3662
+ assert.deepEqual(json.reaped, ["feature/ordinary"], "the ordinary branch is untouched by the refusal");
3663
+ assert.deepEqual(json.worktreesRemoved, [ok], "and its worktree is still the one predicted for removal");
3664
+ const kept = json.kept.find((k) => k.branch === "feature/newline");
3665
+ assert.ok(kept, `the newline branch must be reported, never silently walked past: ${JSON.stringify(json.kept)}`);
3666
+ assert.match(kept.reason, /holds a newline in its path/);
3667
+ assert.ok(branchExists(w, "feature/newline"), "and nothing about it may be deleted");
3668
+ });
3669
+
3670
+ test("a [gone] branch whose worktree is a dangling symlink is kept, never reaped (#725)", (t) => {
3671
+ // `gone()` followed the link, called the path established-absent, and this
3672
+ // sweep's own comment says an absent directory "holds no work" and falls
3673
+ // through to the removal. Measured before the fix: `would remove worktree`
3674
+ // and `reaped:["feature/dangling"]`. A dangling worktree link is also what
3675
+ // release-ticket.sh's rc-255 halt path leaves behind, with the branch and the
3676
+ // in-progress label still live — so this is a live claim, not residue (#728).
3677
+ const w = repo(t);
3678
+ const wt = mergedGoneBranchWithWorktree(w, "feature/dangling", "merged work");
3679
+ rmSync(wt, { recursive: true, force: true });
3680
+ symlinkSync(join(w, "nowhere"), wt);
3681
+
3682
+ const { json } = runReap(w, []);
3683
+ assert.deepEqual(json.reaped, [], "nothing may be reaped over a path that is occupied");
3684
+ assert.deepEqual(json.worktreesRemoved, []);
3685
+ assert.match(json.kept.find((k) => k.branch === "feature/dangling").reason, /cannot tell whether worktree/);
3686
+ assert.ok(branchExists(w, "feature/dangling"));
3687
+ assert.equal(lstatSync(wt).isSymbolicLink(), true, "and the link itself is untouched");
3688
+ });
3689
+
3690
+ // --- #789: three `awk` substitutions that used to end the run in awk's own
3691
+ // voice (or, at the ignored-files site, in a masked one) instead of a
3692
+ // `reap:`-prefixed refusal, plus the git stage in front of the first of them.
3693
+ // Four of the six tests below inject those `awk`/`paste` faults by shimming
3694
+ // `awk` or `paste` on PATH, distinguished by the ARGUMENT this file's own awk
3695
+ // programs carry, never by position — the same discipline IGNORED_PROBE above
3696
+ // states the reason for. The other two shim `git` itself instead, at the
3697
+ // enumeration's own git_probe call: one proves that stage's failure is now
3698
+ // read on its own rather than masked by awk finishing an empty scan at rc 0,
3699
+ // the other proves an rc-0 warning that stage still captures is forwarded to
3700
+ // the operator rather than dropped.
3701
+
3702
+ test("an unenumerable [gone] sweep is kept, not silently read as a clean no-op (#789)", (t) => {
3703
+ // Before this fix, a command substitution used as a `for … in` word list
3704
+ // swallowed the failure completely: the loop ran zero iterations and the
3705
+ // run reported `{"reaped":[],"kept":[]}`, byte-identical to a sweep that
3706
+ // genuinely found nothing to reap.
3707
+ const w = repo(t);
3708
+ mergedGoneBranch(w, "feature/merged", "merged work");
3709
+ const bin = toolFailShim(
3710
+ t,
3711
+ "awk",
3712
+ REAL_AWK,
3713
+ `case "$1" in *'[gone]'*) : ;; *) false ;; esac`,
3714
+ ["awk: multibyte conversion failure"],
3715
+ 2,
3716
+ );
3717
+
3718
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
3719
+
3720
+ assert.equal(code, 0, "an unanswerable enumeration is a finding, not a script failure");
3721
+ assert.deepEqual(json.reaped, [], "nothing can be reaped from a sweep that never enumerated anything");
3722
+ assert.equal(json.kept.length, 1);
3723
+ assert.equal(json.kept[0].branch, null, "no branch was ever named, so none can be blamed");
3724
+ assert.match(json.kept[0].reason, /^could not enumerate \[gone\] branches/);
3725
+ assert.match(stderr, /KEEP \(no branch\) — could not enumerate \[gone\] branches/);
3726
+ assert.equal(branchExists(w, "feature/merged"), true, "a genuinely merged branch survives an enumeration that could not see it");
3727
+ assertToolShimFired(bin, "awk", "the awk shim must actually have fired for this fixture");
3728
+ });
3729
+
3730
+ test("a `git for-each-ref` that dies is kept, never read as a clean no-op that just found nothing (#789)", (t) => {
3731
+ // The awk-only guard above catches awk's own failure, but the pipeline has
3732
+ // a first stage too: `git for-each-ref | awk …`, under `set -eu` with no
3733
+ // `pipefail`. Before this fix only awk's exit status reached the `if !`,
3734
+ // so a `git for-each-ref` that died still left awk scanning EMPTY input —
3735
+ // and awk finishes that scan at rc 0, the identical exit a genuinely
3736
+ // branchless repo produces. The run reported `{"reaped":[],"kept":[]}`,
3737
+ // silently indistinguishable from a clean sweep. Shimming `git` itself,
3738
+ // not `awk`, is what proves the git-side status is now read on its own.
3739
+ const w = repo(t);
3740
+ mergedGoneBranch(w, "feature/merged", "merged work");
3741
+ const bin = failOnlyShim(
3742
+ t,
3743
+ `[ "$1" = for-each-ref ]`,
3744
+ ["fatal: for-each-ref: unable to read refs (simulated)"],
3745
+ 129,
3746
+ );
3747
+
3748
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
3749
+
3750
+ assert.equal(code, 0, "an unanswerable enumeration is a finding, not a script failure");
3751
+ assert.deepEqual(json.reaped, [], "nothing can be reaped from a sweep whose git stage never ran");
3752
+ assert.equal(json.kept.length, 1);
3753
+ assert.equal(json.kept[0].branch, null, "no branch was ever named, so none can be blamed");
3754
+ assert.match(json.kept[0].reason, /^could not enumerate \[gone\] branches/);
3755
+ assert.match(json.kept[0].reason, /for-each-ref: unable to read refs/, "git's own diagnosis must reach the reason, not just a label");
3756
+ assert.match(stderr, /KEEP \(no branch\) — could not enumerate \[gone\] branches/);
3757
+ assert.equal(branchExists(w, "feature/merged"), true, "a genuinely merged branch survives an enumeration that could not see it");
3758
+ assertShimFired(bin, "the git shim must actually have fired for this fixture", /^for-each-ref\b/);
3759
+ });
3760
+
3761
+ test("git_probe's captured stderr on a successful `for-each-ref` still reaches the operator (#789)", (t) => {
3762
+ // git_probe (above) captures git's stderr into $gp_err instead of leaving
3763
+ // it on the real fd — #625, the whole reason it exists — and every OTHER
3764
+ // git_probe call site in reap.sh reads $gp_err back out through a targeted
3765
+ // check (gp_cut_short, gp_why) before falling through. This enumeration's
3766
+ // SUCCESS path did neither until this fix (PR #1413 review): an rc-0
3767
+ // `for-each-ref` that still warns used to reach the operator directly,
3768
+ // back when this was a plain `git … | awk …` pipeline with git's stderr
3769
+ // inherited, and reached no one once captured through git_probe unguarded.
3770
+ // Shimmed to warn but still exec the real git afterward, so the sweep
3771
+ // completes exactly as it would unshimmed — only the warning's presence on
3772
+ // stderr is under test here.
3773
+ const w = repo(t);
3774
+ mergedGoneBranch(w, "feature/merged", "merged work");
3775
+ const bin = mkdtempSync(join(tmpdir(), "reap-shim-"));
3776
+ t.after(() => rmSync(bin, { recursive: true, force: true }));
3777
+ writeFileSync(
3778
+ join(bin, "git"),
3779
+ `#!/bin/sh\n` +
3780
+ `if [ "$1" = for-each-ref ]; then\n` +
3781
+ ` echo "warning: unable to access '/some/broken/config': Permission denied" >&2\n` +
3782
+ `fi\n` +
3783
+ `exec ${REAL_GIT} "$@"\n`,
3784
+ { mode: 0o755 },
3785
+ );
3786
+
3787
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
3788
+
3789
+ assert.equal(code, 0);
3790
+ assert.equal(json.reaped.length, 1, "a genuinely gone branch is still reaped — the warning does not fail the enumeration");
3791
+ assert.match(
3792
+ stderr,
3793
+ /warning: unable to access '\/some\/broken\/config': Permission denied/,
3794
+ "git's own rc-0 warning must still reach the operator, not be silently captured and dropped by git_probe",
3795
+ );
3796
+ });
3797
+
3798
+ test("a worktree lookup whose awk stage fails is kept, never treated as having no worktree (#789)", (t) => {
3799
+ // Before this fix this was a bare assignment: an awk that could not finish
3800
+ // scanning `$wt_list` failed the whole substitution, and because it is a
3801
+ // plain `wt=$(...)` command, `set -e` ended the ENTIRE script right there,
3802
+ // on awk's own diagnostic — never reaching `git branch -D` for this branch
3803
+ // at all, let alone any later one in the sweep.
3804
+ const w = repo(t);
3805
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
3806
+ writeFileSync(join(wt, "scratch.txt"), "would be lost if the worktree were removed blind\n");
3807
+ const bin = toolFailShim(
3808
+ t,
3809
+ "awk",
3810
+ REAL_AWK,
3811
+ `[ "$1" = "-v" ] && case "$3" in *'$2==b'*) : ;; *) false ;; esac`,
3812
+ ["awk: multibyte conversion failure"],
3813
+ 2,
3814
+ );
3815
+
3816
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3817
+
3818
+ assert.equal(code, 0, "an unanswerable worktree lookup is a finding, not a script failure");
3819
+ assert.deepEqual(json.reaped, []);
3820
+ assert.deepEqual(json.worktreesRemoved, []);
3821
+ assert.equal(json.kept.length, 1);
3822
+ assert.equal(json.kept[0].branch, "feature/merged");
3823
+ assert.match(json.kept[0].reason, /^could not scan the worktree listing for feature\/merged/);
3824
+ assert.equal(branchExists(w, "feature/merged"), true, "the branch must survive an unanswerable worktree lookup");
3825
+ assert.equal(existsSync(wt), true, "the worktree and its uncommitted work must survive untouched");
3826
+ assert.equal(
3827
+ readFileSync(join(wt, "scratch.txt"), "utf8"),
3828
+ "would be lost if the worktree were removed blind\n",
3829
+ );
3830
+ assertToolShimFired(bin, "awk", "the awk shim must actually have fired for this fixture");
3831
+ });
3832
+
3833
+ test("an ignored-files scan whose awk stage fails is kept, not silently read as clean (#789)", (t) => {
3834
+ // Before this fix `paste`, not `awk`, was this substitution's last stage,
3835
+ // so an awk that could not finish scanning `$gp_out` was masked completely:
3836
+ // the captured pipeline still succeeded (paste has nothing to fail on) and
3837
+ // the worktree was reaped as though it held no ignored files at all.
3838
+ // Injecting the fault at `awk` alone is only meaningful because the two are
3839
+ // now captured separately — proved by the sibling test below, which shows
3840
+ // the un-restructured pipeline's failure mode still exists at `paste`.
3841
+ const w = repo(t);
3842
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "outside"));
3843
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so only the ignored-files scan is on the critical path");
3844
+ const bin = toolFailShim(
3845
+ t,
3846
+ "awk",
3847
+ REAL_AWK,
3848
+ `case "$1" in *'/^!! /'*) : ;; *) false ;; esac`,
3849
+ ["awk: multibyte conversion failure"],
3850
+ 2,
3851
+ );
3852
+
3853
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3854
+
3855
+ assert.equal(code, 0, "an unanswerable ignored-files scan is a finding, not a script failure");
3856
+ assert.deepEqual(json.reaped, []);
3857
+ assert.equal(json.kept.length, 1);
3858
+ assert.equal(json.kept[0].branch, "feature/merged");
3859
+ assert.match(json.kept[0].reason, /^worktree .* ignored-files scan failed/);
3860
+ assert.equal(branchExists(w, "feature/merged"), true);
3861
+ assert.equal(existsSync(wt), true, "the worktree must survive untouched");
3862
+ assertToolShimFired(bin, "awk", "the awk shim must actually have fired for this fixture");
3863
+ });
3864
+
3865
+ test("an ignored-files list whose paste stage fails is kept, never silently read as clean (#789)", (t) => {
3866
+ // The other half of the restructure: awk succeeds and reports a real
3867
+ // ignored file, and it is `paste`'s own join that cannot finish. Injecting
3868
+ // this fault at `awk` would prove nothing — the un-restructured pipeline
3869
+ // reported only `paste`'s status, which is exactly the masking #789 filed.
3870
+ const w = repo(t);
3871
+ writeFileSync(join(w, ".gitignore"), ".env\n");
3872
+ git(w, "add", ".gitignore");
3873
+ commit(w, "ignore .env");
3874
+ git(w, "push", "-q", "origin", "main");
3875
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work", join(w, "..", "outside"));
3876
+ writeFileSync(join(wt, ".env"), "SECRET=exists nowhere else\n");
3877
+ assert.equal(git(wt, "status", "--porcelain"), "", "fixture: tracked-clean, so only the ignored-files probe is on the critical path");
3878
+ const bin = toolFailShim(
3879
+ t,
3880
+ "paste",
3881
+ REAL_PASTE,
3882
+ `case "$*" in *'-sd,'*) : ;; *) false ;; esac`,
3883
+ ["paste: cannot allocate memory"],
3884
+ 1,
3885
+ );
3886
+
3887
+ const { code, json } = runReap(w, ["--apply"], withShim(bin));
3888
+
3889
+ assert.equal(code, 0, "an unanswerable ignored-files join is a finding, not a script failure");
3890
+ assert.deepEqual(json.reaped, []);
3891
+ assert.equal(json.kept.length, 1);
3892
+ assert.equal(json.kept[0].branch, "feature/merged");
3893
+ assert.match(json.kept[0].reason, /^worktree .* ignored-files list could not be joined/);
3894
+ assert.equal(branchExists(w, "feature/merged"), true);
3895
+ assert.equal(
3896
+ readFileSync(join(wt, ".env"), "utf8"),
3897
+ "SECRET=exists nowhere else\n",
3898
+ "the precious file must survive the run",
3899
+ );
3900
+ assertToolShimFired(bin, "paste", "the paste shim must actually have fired for this fixture");
3901
+ });
3902
+
3903
+ // --- #1020: the ambient git variables, one fixture each.
3904
+ //
3905
+ // Deliberately NOT one fixture setting both. PR #1015 measured the cost of
3906
+ // that shortcut on release-ticket.sh: a case overriding only one of the pair
3907
+ // leaves the other half of `unset GIT_DIR GIT_WORK_TREE` unpinned and green.
3908
+ // Here the two halves are not even the same severity — GIT_WORK_TREE costs a
3909
+ // `kept` reason, GIT_DIR moves the deletions into another repository — so one
3910
+ // detector could not speak for both even if it caught both.
3911
+
3912
+ test("an ambient GIT_WORK_TREE does not make a dirty worktree reapable (#1020)", (t) => {
3913
+ // The silent-failure half. GIT_WORK_TREE outranks `-C`, so the worktree
3914
+ // sweep's `git -C "$wt" status --porcelain` reads the ambient tree against
3915
+ // $wt's index and answers EMPTY at rc 0 — the same false clean #730's
3916
+ // `showUntrackedFiles=no` produced, reached through the environment.
3917
+ //
3918
+ // Blast radius is bounded and that bound is deliberate, not luck: the
3919
+ // downstream `git worktree remove` runs without `--force`, so it refuses on
3920
+ // the real dirt and nothing is lost. What IS lost is the `kept` reason the
3921
+ // operator acts on, and a DRY RUN — where no `worktree remove` ever runs to
3922
+ // refuse — promising a removal that `--apply` cannot deliver. So this case
3923
+ // asserts the verdict, which is the part that actually breaks.
3924
+ //
3925
+ // `.gitignore` naming `.worktrees/` is load-bearing, not scenery: it is the
3926
+ // fleet's own layout, and it is what makes the leaked answer an EMPTY one
3927
+ // rather than a noisy `?? .worktrees/`. Committed before the worktree
3928
+ // branches off main, so $wt's index carries it too — otherwise the poisoned
3929
+ // status reports `?? .gitignore`, no false clean forms, and this fixture
3930
+ // would pass pre-fix while pinning nothing.
3931
+ const w = repo(t);
3932
+ writeFileSync(join(w, ".gitignore"), ".worktrees/\n");
3933
+ git(w, "add", ".gitignore");
3934
+ commit(w, "ignore worktrees");
3935
+ git(w, "push", "-q", "origin", "main");
3936
+ const wt = mergedGoneBranchWithWorktree(w, "feature/merged", "merged work");
3937
+ writeFileSync(join(wt, "scratch.txt"), "work that exists nowhere else\n");
3938
+
3939
+ // The fixture's own positive control, both directions. Without the first, a
3940
+ // case where the worktree was never dirty passes while measuring nothing;
3941
+ // without the second, a git that stopped honouring GIT_WORK_TREE leaves this
3942
+ // green over a leak that no longer exists.
3943
+ assert.equal(git(wt, "status", "--porcelain"), "?? scratch.txt",
3944
+ "fixture: the worktree must really be dirty, or this case measures nothing");
3945
+ assert.equal(
3946
+ execFileSync("git", ["-C", wt, "status", "--porcelain"], {
3947
+ cwd: w, env: { ...ENV, GIT_WORK_TREE: w }, encoding: "utf8",
3948
+ }),
3949
+ "",
3950
+ "fixture: the ambient GIT_WORK_TREE must really silence that answer, or the leak this pins no longer exists",
3951
+ );
3952
+
3953
+ const { code, json, stderr } = runReap(w, [], { GIT_WORK_TREE: w });
3954
+
3955
+ assert.equal(code, 0, stderr);
3956
+ assert.deepEqual(json.worktreesRemoved, [],
3957
+ "a dry run must not promise to remove a worktree `--apply` would be refused on");
3958
+ assert.deepEqual(json.reaped, []);
3959
+ assert.equal(json.kept.length, 1, `expected exactly the dirty-worktree keep: ${JSON.stringify(json.kept)}`);
3960
+ assert.equal(json.kept[0].branch, "feature/merged");
3961
+ assert.equal(json.kept[0].reason, `dirty worktree ${wt}`,
3962
+ "an ambient GIT_WORK_TREE must not turn the dirty-worktree keep into a reap");
3963
+ });
3964
+
3965
+ test("an ambient GIT_DIR does not move the deletions into another repository (#1020)", (t) => {
3966
+ // The correctness half, and the destructive one. Not one git call in either
3967
+ // sweep carries a `-C`, so an ambient GIT_DIR does not merely misreport —
3968
+ // `git worktree remove` and `git branch -D` both land over there. Measured
3969
+ // pre-fix: rc 0, a receipt naming the other repository's worktree and
3970
+ // branch, and this checkout's own [gone] branch never looked at.
3971
+ const w = repo(t);
3972
+ const wt = mergedGoneBranchWithWorktree(w, "feature/here", "work here");
3973
+ const other = repo(t, "other");
3974
+ const otherWt = mergedGoneBranchWithWorktree(other, "feature/there", "work there");
3975
+
3976
+ const { code, json, stderr } = runReap(w, ["--apply"], { GIT_DIR: join(other, ".git") });
3977
+
3978
+ assert.equal(code, 0, stderr);
3979
+ // Three assertions, three distinct failures, and no two are redundant: the
3980
+ // first says the run did its own job, the second and third say it did not do
3981
+ // it somewhere else. A merely truncated sweep reds only the first; a
3982
+ // retargeted one reds all three.
3983
+ assert.deepEqual(json.reaped, ["feature/here"],
3984
+ "an ambient GIT_DIR must not stop this checkout's own [gone] branch being reaped");
3985
+ assert.equal(branchExists(other, "feature/there"), true,
3986
+ "an ambient GIT_DIR must not reach into another repository's branches");
3987
+ assert.equal(existsSync(otherWt), true,
3988
+ "and must not remove another repository's worktree");
3989
+ assert.equal(existsSync(wt), false, "this checkout's own worktree is the one that was due for removal");
3990
+ });
3991
+
3992
+ // --- #1108: the exit-2 cause census.
3993
+ //
3994
+ // The five pins above each ask "does the row mention THIS cause?", every one of
3995
+ // them taking its label off a real refusal. None asked "does the row mention
3996
+ // EVERY cause?", so a PR that gave a script a new refusal left the row's
3997
+ // `exit 2 only` list asserting an enumeration the script had outgrown with the
3998
+ // suite green — measured twice in one fleet run (#1104/#525, #1105/#482). On `main`
3999
+ // this row was silent about three refusals reap.sh reaches: the
4000
+ // worktree-readers library guard, any of the three libraries failing to load,
4001
+ // and the #1441 cwd-delete-guard probe refusing to proceed unverified.
4002
+ //
4003
+ // Two pins, closing opposite directions:
4004
+ //
4005
+ // TOO NARROW — the script grows a refusal the row does not carry. `CAUSES`
4006
+ // binds every `die` site to the phrase that represents it, and the census
4007
+ // test asserts that binding is EXACTLY the set of sites the script has. Add
4008
+ // a `die` and it reds on an unbound site; delete one and it reds on a
4009
+ // binding whose cause the script can no longer produce. The set is derived
4010
+ // from the script, so the binding cannot rot silently the way the row did.
4011
+ //
4012
+ // TOO BROAD — the row grows a cause no `die` produces. The census cannot see
4013
+ // that; a phrase added to the cell binds to nothing and no assert notices.
4014
+ // `EXIT2_ENUMERATION` is the pin that does: the whole closed list, byte for
4015
+ // byte, in the `UNKNOWN_LINE`/`ORPHAN_LINE` verbatim-constant discipline
4016
+ // no-undo-audit.test.mjs already uses on this same table.
4017
+ //
4018
+ // The span pin's cost is deliberate, and it was #1108's ruling: it reds on
4019
+ // EVERY edit to the enumeration, a legitimate rewording included. A structural
4020
+ // assertion loose enough to survive rewording cannot red on a rewrite that
4021
+ // quietly drops a real cause, which is the defect that was measured twice.
4022
+ //
4023
+ // Scoped to this script's own suite beside the five pins above rather than
4024
+ // lifted into one shared table over every row: `.out-of-scope/cli-guard-test-
4025
+ // consolidation.md` refuses that consolidation for the CLI-guard pins, and its
4026
+ // reason holds unchanged here — a file no single script's suite runs recreates
4027
+ // the blind spot these pins exist to close.
4028
+
4029
+ /** The `Non-zero when` cell of this script's row, and no more of the row. */
4030
+ const exit2Cell = () => specRow().split("|")[4];
4031
+
4032
+ /**
4033
+ * The row's exit-2 enumeration, verbatim: from `exit 2 only` to the end of the
4034
+ * sentence that closes the list. Everything after it in the cell states the
4035
+ * exit-0 findings — the kept-branch reasons the pins above read — so the span
4036
+ * stops where the closed list does. The slice is the size of the claim.
4037
+ */
4038
+ const EXIT2_ENUMERATION =
4039
+ "exit 2 only — more than one argument, an unrecognised argument (#250), not a repository, `json.sh`, `net.sh` or `worktree.sh` missing, unreadable or failed to load (all three guards sit above the fetch, so nothing is deleted first), `git rev-parse --show-toplevel` failed with an error that is neither of the two known “not in a worktree” answers, so the cwd-delete guard could not be verified (#1441), the fetch failed or did not finish inside its budget and was killed (#347), `BASE_REF must be a remote-tracking ref` — the accept-list this script had none of, and the precondition that makes qualifying the base to its `refs/remotes/` spelling sound rather than a guess (#924) — the qualified `${BASE_REF:-origin/main}` does not resolve, which is also how a base that resolves only as a local TAG named `origin/main` refuses here instead of answering the merge probe with the wrong commit (#924), or, under `--apply`, `git worktree prune` failed, quoting git's own captured message (#992) — that last one prints the record before the prune runs, so it says the branches were reaped and the housekeeping failed, never that nothing happened.";
4040
+
4041
+ /**
4042
+ * The clause that collapses this script's six library refusals into one cause.
4043
+ * Named because six bindings below share it and a phrase typed six times
4044
+ * drifts five ways.
4045
+ */
4046
+ const LIBRARY_CLAUSE = "`json.sh`, `net.sh` or `worktree.sh` missing, unreadable or failed to load";
4047
+
4048
+ /**
4049
+ * Every `die` site in reap.sh, bound to the phrase in the row that represents
4050
+ * it.
4051
+ *
4052
+ * The KEY is the message as the script spells it, interpolations and all.
4053
+ * `die` is this script's only exit-2 path — `dieSites` asserts that of the
4054
+ * definition itself — so the message set IS the cause set, and keying on it is
4055
+ * what makes this derived rather than a third hand-written copy of the
4056
+ * contract sitting beside the script and the row.
4057
+ *
4058
+ * Sites share a phrase where the ROW collapses them, which is the row's
4059
+ * editorial call and not a looseness here: a reader who meets any of the six
4060
+ * library refusals, or either fetch refusal, does the same thing about it. The
4061
+ * phrases are the short load-bearing labels; their exact wording is
4062
+ * `EXIT2_ENUMERATION`'s job.
4063
+ */
4064
+ const CAUSES = new Map([
4065
+ ["cannot read $json_lib — refusing to reap without the JSON escaping helpers", LIBRARY_CLAUSE],
4066
+ ["$json_lib failed to load", LIBRARY_CLAUSE],
4067
+ ["cannot read $net_lib — refusing to reap without the bounded git transport", LIBRARY_CLAUSE],
4068
+ ["$net_lib failed to load", LIBRARY_CLAUSE],
4069
+ ["cannot read $wt_lib — refusing to reap without the worktree readers", LIBRARY_CLAUSE],
4070
+ ["$wt_lib failed to load", LIBRARY_CLAUSE],
4071
+ ["usage: reap.sh [--apply]", "more than one argument"],
4072
+ ["unrecognised argument '$1' — usage: reap.sh [--apply]", "an unrecognised argument (#250)"],
4073
+ ["BASE_REF must be a remote-tracking ref, got '$base'", "`BASE_REF must be a remote-tracking ref`"],
4074
+ ["not inside a git repository", "not a repository"],
4075
+ [
4076
+ "cannot tell whether this run is standing in a worktree slated for removal — 'git rev-parse --show-toplevel' failed with an unrecognised error (${self_wt_err:-exit $self_wt_rc}) instead of one of the two known 'not in a worktree' messages; refusing to reap with the cwd-delete guard unverified",
4077
+ "so the cwd-delete guard could not be verified (#1441)",
4078
+ ],
4079
+ ["git fetch did not finish within ${fetch_budget}s and was killed — refusing to reap on stale refs", "the fetch failed or did not finish inside its budget and was killed (#347)"],
4080
+ ["fetch failed — refusing to reap on stale refs", "the fetch failed or did not finish inside its budget and was killed (#347)"],
4081
+ ["$base does not resolve", "the qualified `${BASE_REF:-origin/main}` does not resolve"],
4082
+ ["git worktree prune failed: $(printf '%s' \"$prune_err\" | tr '\\n' ' ')", "`git worktree prune` failed"],
4083
+ ]);
4084
+
4085
+ /**
4086
+ * The message of every `die` call in the script, read off the script.
4087
+ *
4088
+ * Comment lines are dropped: prose quoting a `die "…"` is not a call site, and
4089
+ * minting a cause out of one would red this suite over a comment. Greedy to
4090
+ * the last quote on the line, so the `prune` message's own nested `"$…"`
4091
+ * substitution arrives whole rather than truncated at its first inner quote.
4092
+ */
4093
+ function dieSites() {
4094
+ const src = readFileSync(SCRIPT, "utf8");
4095
+ assert.match(
4096
+ src,
4097
+ /^die\(\) \{ printf '%s: %s\\n' "\$NAME" "\$1" >&2; exit 2; \}$/m,
4098
+ "the census derives its cause set from one `die` that exits 2 — that definition has changed, so re-derive before trusting this file",
4099
+ );
4100
+ const sites = src
4101
+ .split("\n")
4102
+ .filter((l) => !/^\s*#/.test(l))
4103
+ .flatMap((l) => [...l.matchAll(/(?:^|[;&|(\s])die "(.*)"/g)].map((m) => m[1]));
4104
+ assert.ok(sites.length > 1, `the scan found ${sites.length} die sites, so its spelling has drifted off the script`);
4105
+ assert.equal(new Set(sites).size, sites.length, `two die sites share a message, so one of them cannot be bound: ${sites.join(" / ")}`);
4106
+ return sites;
4107
+ }
4108
+
4109
+ test("the design spec's row represents every exit-2 cause this script can reach, and none it cannot (#1108)", () => {
4110
+ // Both directions in one equality: an unbound site is a cause the row may be
4111
+ // silent about, and a binding with no site is a cause the row claims while
4112
+ // the script can no longer produce it.
4113
+ assert.deepEqual([...dieSites()].sort(), [...CAUSES.keys()].sort());
4114
+
4115
+ const cell = exit2Cell();
4116
+ for (const phrase of new Set(CAUSES.values())) {
4117
+ assert.equal(
4118
+ cell.split(phrase).length - 1,
4119
+ 1,
4120
+ `the \`Non-zero when\` cell must carry "${phrase}" exactly once.\ncell: ${cell}`,
4121
+ );
4122
+ }
4123
+ });
4124
+
4125
+ test("the design spec's row states this script's exit-2 causes as a closed list, byte for byte (#1108)", () => {
4126
+ // A prefix, not a search: a cause smuggled in ahead of the list would sit
4127
+ // outside an `includes`, and this cell opens on the list.
4128
+ assert.equal(exit2Cell().trim().slice(0, EXIT2_ENUMERATION.length), EXIT2_ENUMERATION);
4129
+ });
4130
+
4131
+ // The worktree-readers guard had no fixture at all before #1108, which is how
4132
+ // its absence from the row survived: the missing-json.sh case above reaches the
4133
+ // json guard, which fires first, so a lone copy of this script can never reach
4134
+ // this one. json.sh and net.sh travel with the copy; worktree.sh does not.
4135
+ test("a missing worktree.sh is exit 2, and the design spec's row names the library it blames (#1108)", (t) => {
4136
+ const w = repo(t);
4137
+ mergedGoneBranch(w, "chore/landed", "work that landed");
4138
+ const lone = mkdtempSync(join(tmpdir(), "reap-nowtlib-"));
4139
+ t.after(() => rmSync(lone, { recursive: true, force: true }));
4140
+ copyFileSync(SCRIPT, join(lone, "reap.sh"));
4141
+ for (const lib of ["json.sh", "net.sh"]) {
4142
+ copyFileSync(fileURLToPath(new URL(`./${lib}`, import.meta.url)), join(lone, lib));
4143
+ }
4144
+
4145
+ const r = spawnSync("sh", [join(lone, "reap.sh"), "--apply"], { cwd: w, env: ENV, encoding: "utf8" });
4146
+
4147
+ assert.equal(r.status, 2, `a missing library is a refusal — this script has no exit 1 to be confused with: ${r.stderr}`);
4148
+ assert.equal(r.stdout, "", "no payload: nothing happened");
4149
+ assert.match(r.stderr, /refusing to reap without the worktree readers/,
4150
+ "the fixture must reach the worktree-readers guard rather than either guard above it");
4151
+ assert.ok(branchExists(w, "chore/landed"),
4152
+ "and the branch is still there — this guard sits above the fetch, so it is a clean refusal");
4153
+
4154
+ // The library NAME off the real refusal, never typed here: the path around it
4155
+ // is the machine's to vary and no document can carry it. Pre-#1108 this row
4156
+ // named json.sh and net.sh alone, so this assert is what demonstrates the
4157
+ // omission by running the script rather than by reading it.
4158
+ const blamed = /^reap: cannot read \S*\/([^/ ]+) —/m.exec(r.stderr);
4159
+ assert.ok(blamed, `the refusal must name the library it could not read: ${r.stderr}`);
4160
+ assert.ok(
4161
+ exit2Cell().includes(`\`${blamed[1]}\``),
4162
+ `the spec row must name the library this refusal blames, and does not carry \`${blamed[1]}\`.\ncell: ${exit2Cell()}`,
4163
+ );
4164
+ });
4165
+
4166
+ // #1039. The bounded-fetch pattern's coverage used to stop at the shared
4167
+ // helper: net.sh's budget, its stalled-signal arm and its kill-tree walk are
4168
+ // each pinned, and unattended-git-sweep.test.mjs pins that this script still
4169
+ // sources net.sh and still reaches net_git — but nothing ever ran this
4170
+ // script's OWN stalled-versus-failed wrapper. Measured on #1030's head:
4171
+ // replacing `${fetch_budget}` in the stalled branch with an unbound variable,
4172
+ // so `set -eu` aborts where `die` was meant to render, left this suite and
4173
+ // unattended-git-sweep.test.mjs at their baseline pass counts, byte-identical.
4174
+ //
4175
+ // One pair, the shape net.test.mjs uses for verify-sha.sh and
4176
+ // inflight.test.mjs for probe 2: one real slow transport, a budget above its
4177
+ // delay and a budget under it. The WORDING is the assertion target, because
4178
+ // `die` gives a killed fetch and a refused one the same exit 2 — the status
4179
+ // alone cannot tell them apart, which is the whole reason the branch exists.
4180
+ test("a slow but working fetch still reaps the merged [gone] branch — the budget is not a stopwatch on success", (t) => {
4181
+ const w = repo(t);
4182
+ mergedGoneBranch(w, "feature/merged", "merged work");
4183
+ // mergedGoneBranch's own `git push --delete` above already left this
4184
+ // clone's local `refs/remotes/origin/feature/merged` gone — `[gone]` would
4185
+ // already be true before the bounded fetch below ever runs. Planting the
4186
+ // tracking ref back makes the verdict below reachable only through a fetch
4187
+ // that genuinely lands, not through the fixture's own prior pushes (#1039
4188
+ // review, finding 3).
4189
+ git(w, "update-ref", "refs/remotes/origin/feature/merged", git(w, "rev-parse", "feature/merged"));
4190
+ // Rewired only now: every push this fixture makes needs `receive-pack`, and
4191
+ // the stub serves `upload-pack` alone.
4192
+ const origin = git(w, "remote", "get-url", "origin");
4193
+ const sshCommand = slowTransport(origin);
4194
+ git(w, "remote", "set-url", "origin", SSH_URL);
4195
+
4196
+ const { code, json, stderr, error } = runReap(
4197
+ w,
4198
+ ["--apply"],
4199
+ { GIT_SSH_COMMAND: sshCommand, FLEET_NET_TIMEOUT: "20" },
4200
+ 60_000,
4201
+ );
4202
+
4203
+ assert.equal(error, undefined, `the run did not come back: ${stderr}`);
4204
+ assert.equal(code, 0, `a budget above the delay must leave the verdict alone: ${stderr}`);
4205
+ assert.deepEqual(json.reaped, ["feature/merged"],
4206
+ "the refs really came back, so the delete is the one an unbounded fetch authorizes");
4207
+ assert.deepEqual(json.kept, []);
4208
+ assert.doesNotMatch(stderr, /did not finish within/,
4209
+ "and nothing claims a budget elapsed, which is the wording the failure path owns");
4210
+ });
4211
+
4212
+ test("a fetch killed by its budget refuses to reap on stale refs, in this script's own words", (t) => {
4213
+ const w = repo(t);
4214
+ mergedGoneBranch(w, "feature/merged", "merged work");
4215
+ const origin = git(w, "remote", "get-url", "origin");
4216
+ const sshCommand = slowTransport(origin);
4217
+ git(w, "remote", "set-url", "origin", SSH_URL);
4218
+
4219
+ const { code, json, stderr, error } = runReap(
4220
+ w,
4221
+ ["--apply"],
4222
+ { GIT_SSH_COMMAND: sshCommand, FLEET_NET_TIMEOUT: "1" },
4223
+ 60_000,
4224
+ );
4225
+
4226
+ assert.equal(error, undefined, `the run did not come back: ${stderr}`);
4227
+ assert.equal(code, 2, `a refusal — this script has no exit 1 to be confused with: ${stderr}`);
4228
+ assert.match(
4229
+ stderr,
4230
+ /reap: git fetch did not finish within 1s and was killed — refusing to reap on stale refs/,
4231
+ "this script's own decline, rendered, with the budget named in it: collapsing the stalled arm into the generic `fetch failed` decline keeps the same exit 2, so only this wording — not the status check — catches it",
4232
+ );
4233
+ assert.doesNotMatch(stderr, /fetch failed — refusing to reap/,
4234
+ "and not the refused-fetch wording, which names a cause this run never observed");
4235
+ assert.equal(json, null, "no payload: nothing was decided");
4236
+ assert.ok(branchExists(w, "feature/merged"),
4237
+ "and the branch a working fetch would have reaped is still there — a refusal that deleted anything would be reaping on exactly the stale refs it declined to trust");
4238
+ });
4239
+
4240
+ /**
4241
+ * #2078's fixture: two merged `[gone]` branches in one pass. `feature/held`
4242
+ * is checked out in a linked worktree holding an untracked file — work that
4243
+ * exists nowhere else — and `feature/free` has no worktree at all.
4244
+ * Alphabetical, so `for-each-ref`'s refname sort visits `feature/free` FIRST:
4245
+ * a guard that only protected the tampered branch would reap it before ever
4246
+ * looking at `feature/held`.
4247
+ */
4248
+ function heldAndFree(t) {
4249
+ const w = repo(t);
4250
+ const wt = mergedGoneBranchWithWorktree(w, "feature/held", "held work");
4251
+ writeFileSync(join(wt, "untracked.txt"), "work that exists nowhere else\n");
4252
+ mergedGoneBranch(w, "feature/free", "free work");
4253
+ return { w, wt, admin: adminEntry(w, wt) };
4254
+ }
4255
+
4256
+ const keptFor = (json, branch) => json.kept.filter((k) => k.branch === branch);
4257
+
4258
+ // Each measured family that leaves `git worktree list --porcelain -z` at rc 0
4259
+ // while it drops the held entry's `branch` line, or the entry itself — and
4260
+ // fools `git branch -D`'s own "used by worktree" refusal the same way, since
4261
+ // both read the same admin state (git 2.50.1, #2078's table). `cause` is the
4262
+ // reason reap now gives; `chmod` marks the fixtures euid 0 reads straight
4263
+ // through, and `restore` puts the permission bit back so `t.after` can clean up.
4264
+ // The `gitdir chmod 000` restore checks first: reap's closing `git worktree
4265
+ // prune` reads an unreadable `gitdir` as prunable and removes the entry, which
4266
+ // is git's own housekeeping and outside what this guard decides.
4267
+ const UNSAFE_REGISTRY = [
4268
+ { name: "HEAD garbage", cause: /linked worktree with a null HEAD and no branch/,
4269
+ fault: ({ admin }) => writeFileSync(join(admin, "HEAD"), "not an object id\n") },
4270
+ { name: "HEAD empty", cause: /linked worktree with a null HEAD and no branch/,
4271
+ fault: ({ admin }) => writeFileSync(join(admin, "HEAD"), "") },
4272
+ { name: "HEAD missing", cause: /linked worktree with a null HEAD and no branch/,
4273
+ fault: ({ admin }) => rmSync(join(admin, "HEAD")) },
4274
+ { name: "HEAD chmod 000", chmod: true, cause: /linked worktree with a null HEAD and no branch/,
4275
+ fault: ({ admin }) => chmodSync(join(admin, "HEAD"), 0o000),
4276
+ restore: ({ admin }) => chmodSync(join(admin, "HEAD"), 0o644) },
4277
+ { name: "gitdir missing", cause: /git listed 0 linked worktrees for 1 registry entries/,
4278
+ fault: ({ admin }) => rmSync(join(admin, "gitdir")) },
4279
+ { name: "gitdir chmod 000", chmod: true, cause: /git listed 0 linked worktrees for 1 registry entries/,
4280
+ fault: ({ admin }) => chmodSync(join(admin, "gitdir"), 0o000),
4281
+ restore: ({ admin }) => existsSync(join(admin, "gitdir")) && chmodSync(join(admin, "gitdir"), 0o644) },
4282
+ { name: "admin dir chmod 000", chmod: true, cause: /git listed 0 linked worktrees for 1 registry entries/,
4283
+ fault: ({ admin }) => chmodSync(admin, 0o000),
4284
+ restore: ({ admin }) => chmodSync(admin, 0o755) },
4285
+ { name: ".git/worktrees replaced by a file", cause: /worktree registry .* could not be read/,
4286
+ fault: ({ w }) => {
4287
+ const reg = join(w, ".git", "worktrees");
4288
+ renameSync(reg, join(w, ".git", "worktrees.moved"));
4289
+ // Mode 755: a file `-r` and `-x` both pass, so only the `-d` arm
4290
+ // refuses it — the tightening over inflight.sh's copy this row pins.
4291
+ writeFileSync(reg, "not a directory\n", { mode: 0o755 });
4292
+ } },
4293
+ ];
4294
+
4295
+ for (const f of UNSAFE_REGISTRY) {
4296
+ test(`an rc-0 listing inconsistent with the registry keeps the whole pass: ${f.name} (#2078)`, (t) => {
4297
+ if (f.chmod && process.getuid?.() === 0) return t.skip("root reads every file");
4298
+ const fx = heldAndFree(t);
4299
+ f.fault(fx);
4300
+ let r;
4301
+ try {
4302
+ r = runReap(fx.w, ["--apply"]);
4303
+ } finally {
4304
+ f.restore?.(fx);
4305
+ }
4306
+ const { json, stderr } = r;
4307
+
4308
+ assert.ok(json, `a payload, not a bare failure: ${stderr}`);
4309
+ assert.deepEqual(json.reaped, [], "nothing is reaped against a registry the listing does not match");
4310
+ assert.equal(branchExists(fx.w, "feature/held"), true, "the branch a live worktree holds survives");
4311
+ assert.equal(branchExists(fx.w, "feature/free"), true,
4312
+ "and so does the healthy one: a dropped entry names no branch, so it could have been hiding this one too");
4313
+ for (const b of ["feature/free", "feature/held"]) {
4314
+ const k = keptFor(json, b);
4315
+ assert.equal(k.length, 1, `${b} is kept exactly once: ${JSON.stringify(json.kept)}`);
4316
+ assert.match(k[0].reason, f.cause);
4317
+ assert.match(k[0].reason, /kept until a pass that reads a consistent registry/);
4318
+ assert.doesNotMatch(k[0].reason, /branch delete failed/, "`git branch -D` is never reached");
4319
+ }
4320
+ assert.equal(existsSync(join(fx.wt, "untracked.txt")), true);
4321
+ });
4322
+ }
4323
+
4324
+ // The control rows: no fault, and the three faults #2078 measured git itself
4325
+ // still answering safely — the listing keeps the held entry's `branch` line,
4326
+ // so the counts agree, no HEAD is null, and the registry guard must not fire.
4327
+ // This is the half that pins what the guard must ACCEPT: `feature/free` is
4328
+ // still reaped, and `feature/held` is kept for what its worktree actually
4329
+ // holds, exactly as before the guard.
4330
+ //
4331
+ // `gitdir garbage` is the exception on `feature/held`, and not one this guard
4332
+ // decides: the listing names the held branch at the garbage path, which reap's
4333
+ // own absent-worktree arm reads as a removed checkout — measured before and
4334
+ // after #2078 alike, it clears the registration and reaps the branch. The row
4335
+ // stays to pin that the guard leaves `feature/free` alone there.
4336
+ const SAFE_REGISTRY = [
4337
+ { name: "baseline (no fault)", heldKept: true, fault: () => {} },
4338
+ { name: "gitdir garbage", heldKept: false, fault: ({ admin }) => writeFileSync(join(admin, "gitdir"), "not a path\n") },
4339
+ { name: "commondir missing", heldKept: true, fault: ({ admin }) => rmSync(join(admin, "commondir")) },
4340
+ { name: "lock file present", heldKept: true, fault: ({ admin }) => writeFileSync(join(admin, "locked"), "held by a test\n") },
4341
+ ];
4342
+
4343
+ for (const f of SAFE_REGISTRY) {
4344
+ test(`a registry the listing still matches keeps reaping as before: ${f.name} (#2078)`, (t) => {
4345
+ const fx = heldAndFree(t);
4346
+ f.fault(fx);
4347
+
4348
+ const { json, stderr } = runReap(fx.w, ["--apply"]);
4349
+
4350
+ assert.ok(json, `a payload, not a bare failure: ${stderr}`);
4351
+ for (const k of json.kept) assert.doesNotMatch(k.reason, /worktree registry inconsistent/);
4352
+ assert.equal(json.reaped[0], "feature/free", "the guard does not refuse a registry the listing matches");
4353
+ assert.equal(branchExists(fx.w, "feature/free"), false);
4354
+ if (f.heldKept) {
4355
+ assert.deepEqual(json.reaped, ["feature/free"]);
4356
+ assert.equal(keptFor(json, "feature/held").length, 1);
4357
+ assert.equal(branchExists(fx.w, "feature/held"), true);
4358
+ }
4359
+ });
4360
+ }
4361
+
4362
+ // The recount-before-refuse (#1408/#1421, inflight.sh's order): a sibling's
4363
+ // `worktree add` or `remove` landing between the registry count and git's
4364
+ // listing makes the two disagree with nothing wrong. The shim lands exactly
4365
+ // that mutation on the FIRST `worktree list` call, ahead of the real listing,
4366
+ // so the first pair disagrees in the named direction and only the recount can
4367
+ // reach the healthy answer. Without it, `feature/free` is kept on a false
4368
+ // "registry inconsistent", once per direction.
4369
+ const SIBLING_MUTATIONS = [
4370
+ { name: "a sibling's `worktree add`", pre: false, mutate: (sib) => `worktree add -q --detach "${sib}" main` },
4371
+ { name: "a sibling's `worktree remove`", pre: true, mutate: (sib) => `worktree remove "${sib}"` },
4372
+ ];
4373
+
4374
+ for (const m of SIBLING_MUTATIONS) {
4375
+ test(`${m.name} landing between the registry count and the listing is absorbed by the recount (#2078)`, (t) => {
4376
+ const w = repo(t);
4377
+ mergedGoneBranch(w, "feature/free", "free work");
4378
+ const sib = join(w, "..", "sibling");
4379
+ if (m.pre) git(w, "worktree", "add", "-q", "--detach", sib, "main");
4380
+ const bin = failOnlyShim(
4381
+ t,
4382
+ `[ "$1" = worktree ] && [ "$2" = list ] && [ ! -e "$0.fired" ] && ` +
4383
+ `{ ${SHIM_FIRED}; "${REAL_GIT}" ${m.mutate(sib)} >/dev/null 2>&1; false; }`,
4384
+ [],
4385
+ );
4386
+
4387
+ const { code, json, stderr } = runReap(w, ["--apply"], withShim(bin));
4388
+
4389
+ assertShimFired(bin, "the mutation must land inside the window the recount closes", /^worktree list/);
4390
+ assert.equal(code, 0, stderr);
4391
+ assert.deepEqual(json.reaped, ["feature/free"], JSON.stringify(json.kept));
4392
+ for (const k of json.kept) assert.doesNotMatch(k.reason, /worktree registry inconsistent/);
4393
+ assert.equal(branchExists(w, "feature/free"), false);
4394
+ });
4395
+ }