@feigi/fleet-ctl 3.23.36 → 3.23.37

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