@feigi/fleet-ctl 3.23.36 → 3.23.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/package.json +1 -1
  2. package/scripts/cell-readout.mjs +38 -11
  3. package/scripts/main-checkout.mjs +1 -1
  4. package/scripts/member-write-guard.mjs +1 -1
  5. package/scripts/repo-root.mjs +1 -1
  6. package/skills/run-team/references/reaping.md +1 -1
  7. package/scripts/agent-test-dir-prose.test.mjs +0 -59
  8. package/scripts/agent-test.test.mjs +0 -1640
  9. package/scripts/ambient-git-vars-mjs-prose.test.mjs +0 -397
  10. package/scripts/ambient-git-vars-prose.test.mjs +0 -192
  11. package/scripts/ancestry-check-position-prose.test.mjs +0 -175
  12. package/scripts/apply-ruleset.test.mjs +0 -421
  13. package/scripts/arg-header-probes-prose.test.mjs +0 -394
  14. package/scripts/arg.test.mjs +0 -1354
  15. package/scripts/board-cli.test.mjs +0 -710
  16. package/scripts/board-identity.test.mjs +0 -429
  17. package/scripts/board-liveness-banner.test.mjs +0 -119
  18. package/scripts/board-prev-shape.test.mjs +0 -228
  19. package/scripts/board-tryparse-null.test.mjs +0 -119
  20. package/scripts/board.test.mjs +0 -3121
  21. package/scripts/brief-after-cut-prose.test.mjs +0 -53
  22. package/scripts/candidates-exit3-prose.test.mjs +0 -302
  23. package/scripts/candidates.test.mjs +0 -2312
  24. package/scripts/caveat-unification-prose.test.mjs +0 -98
  25. package/scripts/cell-readout.test.mjs +0 -615
  26. package/scripts/ci-comment-rot-prose.test.mjs +0 -2025
  27. package/scripts/ci-completes-premise-prose.test.mjs +0 -257
  28. package/scripts/ci-state-prose.test.mjs +0 -113
  29. package/scripts/ci-state.test.mjs +0 -1933
  30. package/scripts/ci-vacuous-green.test.mjs +0 -368
  31. package/scripts/citation-sweep-prose.test.mjs +0 -1712
  32. package/scripts/claim-lifecycle.test.mjs +0 -187
  33. package/scripts/claim-ticket.test.mjs +0 -1122
  34. package/scripts/closing-keyword-prose.test.mjs +0 -193
  35. package/scripts/cockpit-launch-idempotent-prose.test.mjs +0 -165
  36. package/scripts/cockpit-tick-nonblocking.test.mjs +0 -210
  37. package/scripts/compute-board.test.mjs +0 -1214
  38. package/scripts/compute-spend.test.mjs +0 -517
  39. package/scripts/consumer-technology-prose.test.mjs +0 -126
  40. package/scripts/cross-repo-citation-prose.test.mjs +0 -155
  41. package/scripts/cwd-isolation-pins.mjs +0 -83
  42. package/scripts/dedupe-guard-prose.test.mjs +0 -243
  43. package/scripts/delete-merged-branch.test.mjs +0 -576
  44. package/scripts/derive-testcmd.test.mjs +0 -595
  45. package/scripts/diff-stats.test.mjs +0 -404
  46. package/scripts/dispatch-block-golden-prose.test.mjs +0 -1130
  47. package/scripts/dispatch-block-pins-prose.test.mjs +0 -615
  48. package/scripts/dispositions-check.test.mjs +0 -936
  49. package/scripts/dispositions-gate-prose.test.mjs +0 -129
  50. package/scripts/drop-merged-label.test.mjs +0 -479
  51. package/scripts/exec-stub.mjs +0 -93
  52. package/scripts/exec-stub.test.mjs +0 -69
  53. package/scripts/expected-jobs-prose.test.mjs +0 -80
  54. package/scripts/fan-out-authorization-prose.test.mjs +0 -80
  55. package/scripts/filing-bar-seat-prose.test.mjs +0 -242
  56. package/scripts/filing-claim-bar-prose.test.mjs +0 -166
  57. package/scripts/finisher-died-prose.test.mjs +0 -31
  58. package/scripts/finisher-dispatch-premise-prose.test.mjs +0 -312
  59. package/scripts/finisher-halt-prose.test.mjs +0 -106
  60. package/scripts/finisher-name-prose.test.mjs +0 -134
  61. package/scripts/finisher-own-tree-prose.test.mjs +0 -299
  62. package/scripts/finisher-pin-race-prose.test.mjs +0 -339
  63. package/scripts/finisher-test-verdict-prose.test.mjs +0 -102
  64. package/scripts/fix-applier-correction-rules-prose.test.mjs +0 -202
  65. package/scripts/fix-applier-result-file-prose.test.mjs +0 -149
  66. package/scripts/fleet-bootstrap.test.mjs +0 -75
  67. package/scripts/fleet-heartbeat.test.mjs +0 -450
  68. package/scripts/fleet-provenance.test.mjs +0 -138
  69. package/scripts/fleet-run.test.mjs +0 -90
  70. package/scripts/fleet-state.test.mjs +0 -460
  71. package/scripts/fleet-tick-prose.test.mjs +0 -300
  72. package/scripts/fleet-tick.test.mjs +0 -2444
  73. package/scripts/force-with-lease-reason-prose.test.mjs +0 -184
  74. package/scripts/frontmatter-check.test.mjs +0 -436
  75. package/scripts/git-env.test.mjs +0 -149
  76. package/scripts/git-status-untracked-mode-sweep.test.mjs +0 -216
  77. package/scripts/gone-walk.test.mjs +0 -213
  78. package/scripts/gp-sep-invariant-prose.test.mjs +0 -188
  79. package/scripts/head-moved-after-label-prose.test.mjs +0 -233
  80. package/scripts/immutable-body-claim-prose.test.mjs +0 -204
  81. package/scripts/implementer-model-tier.test.mjs +0 -235
  82. package/scripts/inflight-citation-prose.test.mjs +0 -144
  83. package/scripts/inflight-exit2-prose.test.mjs +0 -81
  84. package/scripts/inflight-probe-guard-prose.test.mjs +0 -109
  85. package/scripts/inflight-scan-scope-prose.test.mjs +0 -57
  86. package/scripts/inflight.test.mjs +0 -2882
  87. package/scripts/injection-control-prose.test.mjs +0 -404
  88. package/scripts/install-root-audit.test.mjs +0 -464
  89. package/scripts/instrument-check-prose.test.mjs +0 -235
  90. package/scripts/instruments.test.mjs +0 -787
  91. package/scripts/is-cli.test.mjs +0 -99
  92. package/scripts/issue-tracker-prose.test.mjs +0 -71
  93. package/scripts/json.test.mjs +0 -364
  94. package/scripts/ledger-dispatch.test.mjs +0 -927
  95. package/scripts/ledger-grammar.test.mjs +0 -227
  96. package/scripts/ledger-read-require-file.test.mjs +0 -197
  97. package/scripts/ledger-rotate.test.mjs +0 -142
  98. package/scripts/ledger.test.mjs +0 -3436
  99. package/scripts/line-distance-prose.test.mjs +0 -245
  100. package/scripts/liveness-rationale-prose.test.mjs +0 -83
  101. package/scripts/locale-pin-prose.test.mjs +0 -189
  102. package/scripts/main-checkout.test.mjs +0 -332
  103. package/scripts/member-outcome-prose.test.mjs +0 -167
  104. package/scripts/member-outcomes-header.test.mjs +0 -129
  105. package/scripts/member-outcomes-prose.test.mjs +0 -63
  106. package/scripts/member-outcomes.test.mjs +0 -638
  107. package/scripts/member-prompt-prose.test.mjs +0 -165
  108. package/scripts/member-record.test.mjs +0 -541
  109. package/scripts/member-write-guard.test.mjs +0 -214
  110. package/scripts/merge-commit-probe-prose.test.mjs +0 -122
  111. package/scripts/merge-gate.test.mjs +0 -613
  112. package/scripts/muted-git-guard-sweep.test.mjs +0 -493
  113. package/scripts/net-ssh-precedence-prose.test.mjs +0 -91
  114. package/scripts/net-watchdog-prose.test.mjs +0 -79
  115. package/scripts/net.test.mjs +0 -211
  116. package/scripts/no-ci-gate-prose.test.mjs +0 -108
  117. package/scripts/no-undo-audit.test.mjs +0 -3961
  118. package/scripts/no-wave.test.mjs +0 -138
  119. package/scripts/node-floor-sweep.test.mjs +0 -611
  120. package/scripts/pointer-target-prose.test.mjs +0 -186
  121. package/scripts/pr-cost.test.mjs +0 -521
  122. package/scripts/pr-overlap.test.mjs +0 -692
  123. package/scripts/printf-die-sweep.test.mjs +0 -384
  124. package/scripts/prompt-renderer.mjs +0 -40
  125. package/scripts/prompt-renderer.test.mjs +0 -68
  126. package/scripts/prose-pin.mjs +0 -807
  127. package/scripts/prose-pin.test.mjs +0 -1034
  128. package/scripts/prove-merge.test.mjs +0 -995
  129. package/scripts/pull-table-relabel-prose.test.mjs +0 -60
  130. package/scripts/quiet-payload-prose.test.mjs +0 -222
  131. package/scripts/reap-cherry-check-prose.test.mjs +0 -80
  132. package/scripts/reap.test.mjs +0 -4432
  133. package/scripts/reaping-prose.test.mjs +0 -239
  134. package/scripts/reaping-reap-authorizers-prose.test.mjs +0 -112
  135. package/scripts/reaping-release-authorizers-prose.test.mjs +0 -85
  136. package/scripts/recipe-derivation-prose.test.mjs +0 -112
  137. package/scripts/recipe-prove.test.mjs +0 -1042
  138. package/scripts/refuter-scratch-prose.test.mjs +0 -135
  139. package/scripts/release-label-required-prose.test.mjs +0 -71
  140. package/scripts/release-label-split-prose.test.mjs +0 -184
  141. package/scripts/release-ticket-reap-pairing-prose.test.mjs +0 -63
  142. package/scripts/release-ticket.test.mjs +0 -5099
  143. package/scripts/renovate-release-contract.test.mjs +0 -379
  144. package/scripts/repo-root.test.mjs +0 -873
  145. package/scripts/reporter-output-rule-prose.test.mjs +0 -208
  146. package/scripts/review-agent-report-only.test.mjs +0 -49
  147. package/scripts/review-core-booking.test.mjs +0 -35
  148. package/scripts/review-core-cwd-isolation.test.mjs +0 -374
  149. package/scripts/review-core-reads.test.mjs +0 -478
  150. package/scripts/review-core-refuter-scratch.test.mjs +0 -148
  151. package/scripts/review-core-scratch-refusal.test.mjs +0 -64
  152. package/scripts/review-core-shared-test-run.test.mjs +0 -275
  153. package/scripts/review-core-snapshot-path.test.mjs +0 -830
  154. package/scripts/review-core-specialist-scratch.test.mjs +0 -191
  155. package/scripts/review-core-testcmd.test.mjs +0 -335
  156. package/scripts/review-core-unrun.test.mjs +0 -566
  157. package/scripts/review-core-unverified-discriminant.test.mjs +0 -208
  158. package/scripts/review-eval-resolver-path.test.mjs +0 -55
  159. package/scripts/review-host-fixture.mjs +0 -89
  160. package/scripts/review-in-run-retry.test.mjs +0 -211
  161. package/scripts/review-no-vendor-dispatch.test.mjs +0 -45
  162. package/scripts/review-path-default.test.mjs +0 -796
  163. package/scripts/review-runner-spawns.test.mjs +0 -95
  164. package/scripts/review-runner.test.mjs +0 -166
  165. package/scripts/review-tier-audit.test.mjs +0 -140
  166. package/scripts/run-artifact-pr-prose.test.mjs +0 -341
  167. package/scripts/run-merge-bot-prose.test.mjs +0 -1413
  168. package/scripts/run-team-local-hook.test.mjs +0 -442
  169. package/scripts/scratch-partition-invariant-prose.test.mjs +0 -74
  170. package/scripts/scripts-path-citation-sweep.test.mjs +0 -73
  171. package/scripts/section-between-guard-prose.test.mjs +0 -379
  172. package/scripts/select-dimensions.test.mjs +0 -674
  173. package/scripts/shared-refusal.test.mjs +0 -388
  174. package/scripts/shell-traps-prose.test.mjs +0 -504
  175. package/scripts/shortlist.test.mjs +0 -380
  176. package/scripts/slow-transport.mjs +0 -72
  177. package/scripts/snapshot-repo.test.mjs +0 -1006
  178. package/scripts/snapshot-runner-audience-prose.test.mjs +0 -130
  179. package/scripts/spend-view.test.mjs +0 -312
  180. package/scripts/staleness-qualifier-prose.test.mjs +0 -251
  181. package/scripts/staleness-verdict-prose.test.mjs +0 -142
  182. package/scripts/staleness.test.mjs +0 -893
  183. package/scripts/stalled-member-liveness-prose.test.mjs +0 -219
  184. package/scripts/stash-prohibition-prose.test.mjs +0 -313
  185. package/scripts/strip-comments.mjs +0 -44
  186. package/scripts/temp-dir.mjs +0 -47
  187. package/scripts/ticket-router.test.mjs +0 -981
  188. package/scripts/tier-check.test.mjs +0 -828
  189. package/scripts/tier-outcomes-header.test.mjs +0 -518
  190. package/scripts/tier-outcomes.test.mjs +0 -572
  191. package/scripts/tier-roles.test.mjs +0 -535
  192. package/scripts/tracker-block-copy-prose.test.mjs +0 -288
  193. package/scripts/triage-labels-gloss-prose.test.mjs +0 -97
  194. package/scripts/unattended-git-sweep.test.mjs +0 -142
  195. package/scripts/verify-sha-exit2-prose.test.mjs +0 -269
  196. package/scripts/verify-sha.test.mjs +0 -692
  197. package/scripts/watcher-degraded-block.test.mjs +0 -369
  198. package/scripts/watcher-key-prose.test.mjs +0 -106
  199. package/scripts/within-run-pair-prose.test.mjs +0 -212
  200. package/scripts/worktree-audit.test.mjs +0 -1408
  201. package/scripts/worktree-head-prose.test.mjs +0 -276
  202. package/scripts/worktree-listing-sweep.test.mjs +0 -217
  203. package/scripts/worktree-model-prose.test.mjs +0 -216
  204. package/scripts/worktree-porcelain.mjs +0 -35
  205. package/scripts/worktree-porcelain.test.mjs +0 -102
@@ -1,3961 +0,0 @@
1
- // Regression gate for no-undo-audit.sh, all three of its outcomes. Zero deps:
2
- // `node --test plugin/scripts/no-undo-audit.test.mjs`.
3
- //
4
- // The audit answers one question — is this worktree safe to rebase — and the
5
- // only thing that makes it refuse is uncommitted work in the worktree. It used
6
- // to also refuse on a nonzero repo-global stash count, which is unrelated to
7
- // that question: a rebase never consumes a pre-existing entry, so the count
8
- // refused every run in a repo holding any entry while proving nothing about the
9
- // branch. Both directions are pinned, because a fix for a false refusal is one
10
- // keystroke from deleting the true one.
11
- //
12
- // The refusal is only half of it. A clean worktree exits 0 while still
13
- // answering "what would a careless resolution eat", and everything below the
14
- // `conflicts[] and atRisk[]` banner pins that half — the half that had no
15
- // coverage at all while this file called itself the regression gate.
16
- //
17
- // Exit 2 is its own outcome: the question could not be answered. Its rule is
18
- // that no payload is emitted, because a payload is an answer, and every exit-2
19
- // test asserts that as well as the code. Reported safe on a question never
20
- // asked is the one failure this script exists to prevent, so a shape it cannot
21
- // answer must exit 2 rather than exit 0 with an empty `atRisk`.
22
- //
23
- // Real git throughout: a shell script that reasons about git state can only be
24
- // tested against real git state.
25
-
26
- import { test } from "node:test";
27
- import assert from "node:assert/strict";
28
- import { execFileSync, spawnSync } from "node:child_process";
29
- import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
30
- import { tmpdir } from "node:os";
31
- import { dirname, join } from "node:path";
32
- import { fileURLToPath } from "node:url";
33
- import { between, phrase, stripHashGutter } from "./prose-pin.mjs";
34
- import { writeExecStub } from "./exec-stub.mjs";
35
-
36
- const SCRIPT = fileURLToPath(new URL("./no-undo-audit.sh", import.meta.url));
37
-
38
- // Pin identity and cut the developer's ~/.gitconfig out of the fixtures, so a
39
- // local pull.rebase or hook cannot change what these repos look like. BASE_REF
40
- // is unset because the fleet harness is exactly the caller that would have it
41
- // set, and inheriting it would point every fixture at a local main while the
42
- // suite stayed green.
43
- const ENV = {
44
- ...process.env,
45
- BASE_REF: undefined,
46
- GIT_DIR: undefined,
47
- GIT_WORK_TREE: undefined,
48
- GIT_TEMPLATE_DIR: undefined,
49
- GIT_INDEX_FILE: undefined,
50
- GIT_AUTHOR_NAME: "t",
51
- GIT_AUTHOR_EMAIL: "t@example.com",
52
- GIT_COMMITTER_NAME: "t",
53
- GIT_COMMITTER_EMAIL: "t@example.com",
54
- GIT_CONFIG_GLOBAL: "/dev/null",
55
- GIT_CONFIG_SYSTEM: "/dev/null",
56
- // GIT_CONFIG_GLOBAL alone does not isolate: these two carry config in through
57
- // a separate door and outrank the files. A suite run from inside a git hook
58
- // inherits whatever set them, which is a false red nobody can reproduce by
59
- // hand.
60
- GIT_CONFIG_COUNT: undefined,
61
- GIT_CONFIG_PARAMETERS: undefined,
62
- };
63
-
64
- const git = (cwd, ...args) =>
65
- execFileSync("git", args, { cwd, env: ENV, encoding: "utf8" }).trim();
66
-
67
- /** Bare origin + clone with `main` and a pushed feature branch, checked out. */
68
- function repo(t, branch = "fix/1-thing", prefix = "no-undo-audit-") {
69
- const root = mkdtempSync(join(tmpdir(), prefix));
70
- t.after(() => rmSync(root, { recursive: true, force: true }));
71
- const origin = join(root, "origin.git");
72
- const w = join(root, "w");
73
- execFileSync("git", ["-c", "init.defaultBranch=main", "init", "-q", "--bare", origin], { env: ENV });
74
- execFileSync("git", ["clone", "-q", origin, w], { env: ENV });
75
- writeFileSync(join(w, "f.txt"), "root\n");
76
- git(w, "add", "f.txt");
77
- git(w, "commit", "-q", "-m", "root");
78
- git(w, "branch", "-M", "main");
79
- git(w, "push", "-q", "-u", "origin", "main");
80
- git(w, "checkout", "-q", "-b", branch);
81
- writeFileSync(join(w, "g.txt"), "branch work\n");
82
- git(w, "add", "g.txt");
83
- git(w, "commit", "-q", "-m", "branch work");
84
- git(w, "push", "-q", "-u", "origin", branch);
85
- return { w, branch };
86
- }
87
-
88
- /** Leave a stash entry behind without leaving the worktree dirty. */
89
- function stashSomething(w, name = "h.txt") {
90
- writeFileSync(join(w, name), "stashed\n");
91
- git(w, "add", name);
92
- git(w, "stash", "push", "-q", "-m", `pre-existing ${name}`);
93
- }
94
-
95
- /** Add/add conflict on `path`, with main holding the later commit that made it. */
96
- // Two decoys make `atRisk` discriminating rather than merely nonempty. Without
97
- // them every main commit since the fork touches the conflicting path and the
98
- // root commit touches nothing else, so "filtered by path", "filtered by range"
99
- // and "not filtered at all" all return exactly one line — and dropping either
100
- // filter from the script leaves the suite green. DECOY_OLD is on the path but
101
- // before the fork; DECOY_NEW is after the fork but on another file.
102
- // `branch` and `prefix` pass straight through to `repo`, so a case can plant a
103
- // marker in the branch name or in the worktree path — the two values #431's
104
- // escape block renders, and the only two a content-selected shim can address
105
- // there. Both default through `repo`'s own defaults, so every existing caller
106
- // is unchanged.
107
- function conflictRepo(t, path, branch, prefix) {
108
- const c = repo(t, branch, prefix);
109
- git(c.w, "checkout", "-q", "main");
110
- writeFileSync(join(c.w, path), "older, already shared\n");
111
- git(c.w, "add", "--", `:(literal)${path}`);
112
- git(c.w, "commit", "-q", "-m", "DECOY_OLD before the fork");
113
- git(c.w, "push", "-q", "origin", "main");
114
- git(c.w, "checkout", "-q", c.branch);
115
- git(c.w, "merge", "-q", "main", "-m", "carry main into the branch");
116
- writeFileSync(join(c.w, path), "branch side\n");
117
- git(c.w, "add", "--", `:(literal)${path}`);
118
- git(c.w, "commit", "-q", "-m", "branch edits the file");
119
- git(c.w, "push", "-q", "origin", c.branch);
120
- git(c.w, "checkout", "-q", "main");
121
- writeFileSync(join(c.w, "decoy.txt"), "untouched by the conflict\n");
122
- git(c.w, "add", "--", "decoy.txt");
123
- git(c.w, "commit", "-q", "-m", "DECOY_NEW after the fork");
124
- writeFileSync(join(c.w, path), "MAIN SIDE\n");
125
- git(c.w, "add", "--", `:(literal)${path}`);
126
- git(c.w, "commit", "-q", "-m", "MAIN COMMIT AT RISK");
127
- git(c.w, "push", "-q", "origin", "main");
128
- git(c.w, "checkout", "-q", c.branch);
129
- return c;
130
- }
131
-
132
- /** Both sides add `path`; nothing else. Used where the decoys would be noise. */
133
- function bareConflictRepo(t, path) {
134
- const c = repo(t);
135
- writeFileSync(join(c.w, path), "branch side\n");
136
- git(c.w, "add", "--", `:(literal)${path}`);
137
- git(c.w, "commit", "-q", "-m", "branch edits the file");
138
- git(c.w, "push", "-q", "origin", c.branch);
139
- git(c.w, "checkout", "-q", "main");
140
- writeFileSync(join(c.w, path), "MAIN SIDE\n");
141
- git(c.w, "add", "--", `:(literal)${path}`);
142
- git(c.w, "commit", "-q", "-m", "MAIN COMMIT AT RISK");
143
- git(c.w, "push", "-q", "origin", "main");
144
- git(c.w, "checkout", "-q", c.branch);
145
- return c;
146
- }
147
-
148
- /**
149
- * Both sides add a path spelled as a `printf` FORMAT, plus `plain.txt`, so
150
- * merge-tree reports TWO conflicting paths, and main's later commit is
151
- * `MAIN COMMIT AT RISK` — the same shape `conflictRepo` builds, reached without
152
- * ever naming the path in JavaScript.
153
- *
154
- * The name has to be produced by the SHELL. `execFileSync` re-encodes every JS
155
- * string as UTF-8, so a JS `"\xFF"` arrives as the two bytes `\303\277` — valid
156
- * UTF-8, which reproduces nothing. `printf 'b\377ad.txt'` is the only way to get
157
- * the raw byte across, and it keeps this file pure ASCII.
158
- *
159
- * The commits go in through a THROWAWAY `GIT_INDEX_FILE` and are pushed straight
160
- * to origin, so neither the real index nor the filesystem ever has to hold the
161
- * name — APFS refuses it outright (`touch $(printf 'b\377ad.txt')` → `Illegal
162
- * byte sequence`, status 1), which is what makes `--cacheinfo` load-bearing
163
- * rather than a shortcut. Nothing needs checking out either: the audit reads
164
- * `origin/main` and `origin/<branch>` and compares neither against local HEAD,
165
- * so the local branch stays one commit behind and `status --porcelain` stays
166
- * clean. That is also why no sparse-checkout is needed to keep it clean.
167
- */
168
- function byteConflictRepo(t, printfPath) {
169
- const c = repo(t);
170
- execFileSync("sh", ["-c", `
171
- set -eu
172
- w=$1; idx=$2; branch=$3; p=$(printf "$4")
173
- cd "$w"
174
- side() {
175
- parent=$(git rev-parse "$1")
176
- blob=$(printf '%s\\n' "$2" | git hash-object -w --stdin)
177
- GIT_INDEX_FILE=$idx git read-tree "$parent"
178
- GIT_INDEX_FILE=$idx git update-index --add --cacheinfo "100644,$blob,$p" --cacheinfo "100644,$blob,plain.txt"
179
- tree=$(GIT_INDEX_FILE=$idx git write-tree)
180
- git commit-tree "$tree" -p "$parent" -m "$3"
181
- }
182
- git push -q origin "$(side "origin/$branch" 'branch side' 'branch edits the file')":"refs/heads/$branch"
183
- git push -q origin "$(side origin/main 'MAIN SIDE' 'MAIN COMMIT AT RISK')":refs/heads/main
184
- `, "sh", c.w, join(c.w, "..", "idx"), c.branch, printfPath], { env: ENV, encoding: "utf8" });
185
- return c;
186
- }
187
-
188
- /**
189
- * Add/add conflicts on 20 paths, introduced on main by TWO distinct commits
190
- * that INTERLEAVE through the pathspec list: the even-numbered paths come
191
- * from one, the odd-numbered from the other, and the audit hands them to
192
- * `git log` in sorted order. So a batch — always a contiguous run of that
193
- * list — holds paths from both commits and reports both, and the
194
- * concatenation across batches is `B A B A …` rather than `A A B B`.
195
- *
196
- * Every part of that shape is load-bearing, and one commit pinned none of it:
197
- * with a single commit each batch emits the same line, so all duplicates are
198
- * adjacent and a merely-ADJACENT dedupe (`uniq`) passes; interleaved, `uniq`
199
- * has nothing adjacent to collapse and returns one line per batch. The two
200
- * subjects share a first word so a dedupe keyed on `$2` — the subject's first
201
- * word rather than `$1`, the SHA that is the actual commit identity —
202
- * collapses them to one and fails. And two DISTINCT commits are what pin that
203
- * the dedupe drops only true duplicates: both must survive the split.
204
- *
205
- * Returns `paths` so the test asserts against the fixture's own count instead
206
- * of a literal repeated at the call site.
207
- *
208
- * Real ARG_MAX needs thousands of ordinary-length paths to split on its own —
209
- * the exact figure is ambient-environment-size dependent, since xargs' budget
210
- * is the limit minus the inherited environment — so `withSplitXargs` below
211
- * forces the split at 20 instead.
212
- */
213
- function manyConflictsTwoCommits(t) {
214
- const c = repo(t);
215
- const paths = Array.from({ length: 20 }, (_, i) => `conflict-${String(i).padStart(2, "0")}.txt`);
216
- const evens = paths.filter((_, i) => i % 2 === 0);
217
- const odds = paths.filter((_, i) => i % 2 === 1);
218
- git(c.w, "checkout", "-q", "main");
219
- for (const [subject, batch] of [["MAIN COMMIT AT RISK, even paths", evens], ["MAIN COMMIT AT RISK, odd paths", odds]]) {
220
- for (const p of batch) writeFileSync(join(c.w, p), "MAIN SIDE\n");
221
- git(c.w, "add", "--", ...batch);
222
- git(c.w, "commit", "-q", "-m", subject);
223
- }
224
- git(c.w, "push", "-q", "origin", "main");
225
- git(c.w, "checkout", "-q", c.branch);
226
- for (const p of paths) writeFileSync(join(c.w, p), "branch side\n");
227
- git(c.w, "add", "--", ...paths);
228
- git(c.w, "commit", "-q", "-m", "branch edits every file");
229
- git(c.w, "push", "-q", "origin", c.branch);
230
- return { ...c, paths };
231
- }
232
-
233
- /**
234
- * Shadows `xargs` on PATH with a wrapper that inserts `-s size` ahead of
235
- * whatever args the script passes, forcing the ARG_MAX split #148 describes
236
- * on an ordinary small fixture instead of a ~1 MiB pathspec list — the same
237
- * technique the ticket used to measure the bug. Both wrappers resolve the real
238
- * binary once up front — outside the shadowed PATH, so the lookup cannot
239
- * recurse into the wrapper — and then `exec` it, so nothing else changes.
240
- *
241
- * `git` is shadowed too, and only to COUNT the batches: it records every
242
- * invocation carrying a `:(literal)` pathspec, which is the one call xargs
243
- * drives, so the count IS the number of batches. Without it the split is an
244
- * unasserted side condition and the test is only conditionally a test — an
245
- * xargs that clamps or ignores a small `-s` runs the whole fixture in one
246
- * batch, and then every assertion below passes with the dedupe DELETED,
247
- * measured end to end. `batches()` is what makes that platform fail red
248
- * instead of green-on-nothing.
249
- */
250
- function withSplitXargs(t, size = 300) {
251
- const bin = mkdtempSync(join(tmpdir(), "no-undo-audit-xargs-"));
252
- t.after(() => rmSync(bin, { recursive: true, force: true }));
253
- const log = join(bin, "batches");
254
- const shim = (name, body) => {
255
- const real = execFileSync("sh", ["-c", `command -v ${name}`], { encoding: "utf8" }).trim();
256
- writeExecStub(join(bin, name), `#!/bin/sh\n${body}exec ${real} "$@"\n`);
257
- };
258
- shim("xargs", `set -- -s ${size} "$@"\n`);
259
- shim("git", `case " $* " in *':(literal)'*) echo x >>"${log}" ;; esac\n`);
260
- return {
261
- path: `${bin}:${process.env.PATH}`,
262
- batches: () => (existsSync(log) ? readFileSync(log, "utf8").split("\n").length - 1 : 0),
263
- };
264
- }
265
-
266
- /**
267
- * A wrapper factory for the two shims below: resolves the real binary once, up
268
- * front and outside the shadowed PATH so the lookup cannot recurse into the
269
- * wrapper, then writes an executable of the given body. Same technique as
270
- * `withSplitXargs`, kept separate because these two need a whole script rather
271
- * than a prefix ahead of a trailing `exec`.
272
- */
273
- function shimDir(t, prefix) {
274
- const bin = mkdtempSync(join(tmpdir(), prefix));
275
- t.after(() => rmSync(bin, { recursive: true, force: true }));
276
- return {
277
- bin,
278
- real: (name) => execFileSync("sh", ["-c", `command -v ${name}`], { encoding: "utf8" }).trim(),
279
- write: (name, body) => {
280
- writeExecStub(join(bin, name), `#!/bin/sh\n${body}`);
281
- },
282
- path: () => `${bin}:${process.env.PATH}`,
283
- };
284
- }
285
-
286
- /**
287
- * Makes the file holding merge-tree's `-z` output unreadable at the moment the
288
- * audit reads it, and not one step earlier: the `git` wrapper chmods it only
289
- * after the real `merge-tree` has written and exited, so the emptiness guard
290
- * that sits between the write and the read still sees a non-empty file and
291
- * passes. That ordering is the whole point — the fault has to land on the stage
292
- * that READS, which is the stage a pipeline's exit status does not report.
293
- *
294
- * `chmod 000` rather than `rm` for the same reason: a removed file fails the
295
- * emptiness guard instead, and the test would then be green on a refusal raised
296
- * by a different guard about a different fault, proving nothing about this one.
297
- *
298
- * The `mktemp` wrapper exists only to learn the name of a temporary that is
299
- * otherwise private to the script. It records the FIRST one, which is the file
300
- * merge-tree writes; a later temporary is left alone.
301
- */
302
- function withUnreadableMergeTreeOutput(t) {
303
- const s = shimDir(t, "no-undo-audit-mtout-");
304
- const recorded = join(s.bin, "first-temp-path");
305
- s.write("mktemp", `f=$(${s.real("mktemp")} "$@") || exit $?
306
- [ -e "${recorded}" ] || printf '%s\\n' "$f" >"${recorded}"
307
- printf '%s\\n' "$f"
308
- `);
309
- s.write("git", `case " $* " in
310
- *" merge-tree "*)
311
- ${s.real("git")} "$@"
312
- rc=$?
313
- chmod 000 "$(cat "${recorded}")"
314
- exit $rc ;;
315
- esac
316
- exec ${s.real("git")} "$@"
317
- `);
318
- return s.path();
319
- }
320
-
321
- /**
322
- * Fails every `mktemp` after the first, leaving merge-tree's own temporary
323
- * intact so the run reaches the point where a second one is asked for. A full
324
- * TMPDIR or a TMPDIR that has gone missing does this for real.
325
- *
326
- * The path the first call handed back is recorded, not merely the fact that a
327
- * call happened, because the abort this injects is also the abort that has to
328
- * clean up after itself: the caller reads `firstTemp` to check the file is gone
329
- * once the run has exited. Recording it is what lets the assertion name a real
330
- * path rather than trusting the trap.
331
- */
332
- function withLaterMktempFailing(t) {
333
- const s = shimDir(t, "no-undo-audit-mktemp-");
334
- const firstTemp = join(s.bin, "first-temp-path");
335
- s.write("mktemp", `if [ -e "${firstTemp}" ]; then
336
- echo "mktemp: failed to create file" >&2
337
- exit 1
338
- fi
339
- f=$(${s.real("mktemp")} "$@") || exit $?
340
- printf '%s\n' "$f" >"${firstTemp}"
341
- printf '%s\n' "$f"
342
- `);
343
- return { path: s.path(), firstTemp };
344
- }
345
-
346
- /**
347
- * Add/add conflicts on enough paths, each named long enough, that merge-tree's PROSE tail — the
348
- * `Auto-merging`/`CONFLICT` section that follows the empty record, and the part
349
- * of the output the audit deliberately never wants — is larger than a pipe
350
- * buffer.
351
- *
352
- * That size is the whole fixture. The reader stops at the empty record by
353
- * design, so on any conflicted run it leaves the tail unread; once the tail no
354
- * longer fits in the buffer, whatever is upstream of the reader is still trying
355
- * to write when the reader goes away. A `tr | tr | awk` reads back
356
- * `141 141 0 0` there — two stages killed by SIGPIPE on a run whose answer is
357
- * completely CORRECT. Anything that adopts a prefix stage's status as the
358
- * pipeline's own, `set -o pipefail` most obviously, converts exactly this run
359
- * into a refusal. So the fixture is a control: it must keep answering.
360
- *
361
- * One main commit, not `manyConflictsTwoCommits`' two — the dedupe across xargs
362
- * batches is that fixture's claim and not this one's.
363
- */
364
- function longTailConflictRepo(t) {
365
- const c = repo(t);
366
- const paths = Array.from({ length: 200 }, (_, i) => `${String(i).padStart(3, "0")}-${"x".repeat(220)}.txt`);
367
- git(c.w, "checkout", "-q", "main");
368
- for (const p of paths) writeFileSync(join(c.w, p), "MAIN SIDE\n");
369
- git(c.w, "add", "--", ...paths);
370
- git(c.w, "commit", "-q", "-m", "MAIN COMMIT AT RISK");
371
- git(c.w, "push", "-q", "origin", "main");
372
- git(c.w, "checkout", "-q", c.branch);
373
- for (const p of paths) writeFileSync(join(c.w, p), "branch side\n");
374
- git(c.w, "add", "--", ...paths);
375
- git(c.w, "commit", "-q", "-m", "branch edits every file");
376
- git(c.w, "push", "-q", "origin", c.branch);
377
- return { ...c, paths };
378
- }
379
-
380
- /** Bytes of merge-tree's output after the empty record — the part left unread. */
381
- function unreadTailBytes({ w, branch }) {
382
- const mt = spawnSync("git", ["-C", w, "merge-tree", "--write-tree", "--name-only", "-z", "origin/main", `origin/${branch}`],
383
- { env: ENV, maxBuffer: 1 << 27 });
384
- const end = mt.stdout.indexOf(Buffer.from([0, 0]));
385
- assert.notEqual(end, -1, "merge-tree must emit the empty record that ends the filename section");
386
- return mt.stdout.length - (end + 2);
387
- }
388
-
389
- /**
390
- * A linked worktree NESTED inside the clone, `.worktrees/` gitignored — the
391
- * fleet's own layout, and the only one where breaking the linkage is dangerous:
392
- * an enclosing repo is standing by to answer in the worktree's place, and being
393
- * clean it answers "nothing uncommitted here". A worktree with no repo above it
394
- * has nothing to walk up to, so git fails there and the script already refuses.
395
- * `precious.txt` is the uncommitted work that exists nowhere else.
396
- *
397
- * The directory is made BEFORE `worktree add`, not left for `git` to create
398
- * it: a leaf `git` creates itself comes back reprecomposed under
399
- * `core.precomposeunicode` even when `name` is passed decomposed (measured),
400
- * so a caller wanting an on-disk NFD leaf (#2095) needs the directory to
401
- * already exist — `git` then uses it as-is, byte for byte.
402
- */
403
- function nestedWorktree(t, name = "9-x") {
404
- const branch = "fix/9-nested";
405
- const c = repo(t);
406
- writeFileSync(join(c.w, ".gitignore"), ".worktrees/\n");
407
- git(c.w, "add", ".gitignore");
408
- git(c.w, "commit", "-q", "-m", "ignore the nested worktree");
409
- const w = join(c.w, ".worktrees", name);
410
- mkdirSync(w, { recursive: true });
411
- git(c.w, "worktree", "add", "-q", "-b", branch, w);
412
- git(w, "push", "-q", "-u", "origin", branch);
413
- writeFileSync(join(w, "precious.txt"), "work that exists nowhere else\n");
414
- return { parent: c.w, w, branch };
415
- }
416
-
417
- /**
418
- * `nestedWorktree` plus a SECOND linked worktree under the same parent,
419
- * named `8-y` to match the ticket's own repro. `sibling` is where it lives;
420
- * `siblingAdmin` is its admin dir — the thing #189's spoof names in place of
421
- * $wt's own.
422
- */
423
- function nestedWorktreePair(t) {
424
- const c = nestedWorktree(t);
425
- const sibling = join(c.parent, ".worktrees", "8-y");
426
- git(c.parent, "worktree", "add", "-q", "-b", "fix/8-sibling", sibling);
427
- // Asked of git itself, not built with `join`: on macOS `tmpdir()` sits under
428
- // a `/var` that is itself a symlink to `/private/var`, and git's own
429
- // `--git-dir` answers with the resolved form. A hand-joined path would
430
- // still WORK if spoofed into a `.git` file — the filesystem resolves either
431
- // spelling — but comparing it against a later `--git-dir` call in a test
432
- // assertion needs the same spelling git itself produces.
433
- const siblingAdmin = git(sibling, "rev-parse", "--git-dir");
434
- return { ...c, sibling, siblingAdmin };
435
- }
436
-
437
- // The payload is parsed here rather than at the call site: "the audit passed and
438
- // then the caller crashed on its own stdout" is a distinct outcome from "the
439
- // audit refused", and a test cannot tell them apart if the parse throws inside
440
- // the helper that also reports the exit code.
441
- // `cwd` defaults to `$wt`, which is what every fixture predating #376 wants.
442
- // The real caller runs from its own directory; the cwd-independence test below
443
- // passes that in rather than relying on the two happening to coincide.
444
- const audit = ({ w, branch }, env = ENV, cwd = w) => {
445
- const r = spawnSync("sh", [SCRIPT, w, branch], { cwd, env, encoding: "utf8" });
446
- const out = r.stdout.trim();
447
- let json = null;
448
- let jsonError = null;
449
- if (out) {
450
- try {
451
- json = JSON.parse(out);
452
- } catch (e) {
453
- jsonError = e;
454
- }
455
- }
456
- return { ...r, json, jsonError };
457
- };
458
-
459
- /**
460
- * Runs the audit with its own stderr piped to a reader that exits after one
461
- * line — a genuine SIGPIPE (#1571), not the closed-fd-before-launch shape
462
- * `2>&-` gives the tests above it: here the descriptor is live and writable
463
- * right up until the reader goes away mid run.
464
- *
465
- * `spawnSync`'s own `status`/`signal` fields cannot carry this: node reads
466
- * the child's stdio through its OWN pipes, and destroying node's end races
467
- * the child's writes without ever reproducing a real reader closing a real
468
- * pipe (measured — it left the unfixed script un-killed as often as not).
469
- * A `head -1` in a real shell pipeline is what actually closes the
470
- * descriptor, and what is left to report the audit's exit code is `sh`
471
- * itself, the same way an unattended caller would read it — `$?` — not
472
- * node's process object. `printf … >&3` carries that `$?` around the pipe
473
- * that would otherwise discard it: `3>&1` on the outer group aliases fd 3 to
474
- * the descriptor `spawnSync` is already reading as `r.stdout`, and the
475
- * pipeline's left-hand brace group inherits that alias directly — `$0`,
476
- * `$1`, `$2` are already this `sh -c`'s own positionals, so nothing needs
477
- * re-passing into a second shell.
478
- */
479
- function earlyClosingStderrReaderStatus({ w, branch }, cwd = w) {
480
- const wrapper = '{ { sh "$0" "$1" "$2" 2>&1 >/dev/null; printf "RC=%s" "$?" >&3; } '
481
- + '| head -1 >/dev/null; } 3>&1';
482
- const r = spawnSync("sh", ["-c", wrapper, SCRIPT, w, branch], { cwd, env: ENV, encoding: "utf8" });
483
- const m = /^RC=(\d+)$/.exec(r.stdout);
484
- assert.ok(m, `wrapper must report the audit's own exit code; got ${JSON.stringify(r)}`);
485
- return Number(m[1]);
486
- }
487
-
488
- /** `atRisk` with the abbreviated SHA stripped, so a test can pin the exact set. */
489
- const subjects = (r) => r.json.atRisk.map((l) => l.replace(/^\S+ /, ""));
490
-
491
- /**
492
- * The audit's own stash line, pulled out of stderr whole. Pinned as a literal
493
- * rather than a substring match: #304 appends git's diagnostic to this line,
494
- * and the thing that must not happen is a separator appended with nothing
495
- * after it — which every `/unknown/` match above would still pass.
496
- */
497
- const UNKNOWN_LINE =
498
- " stash entries (repo-global, not gated): unknown — the list came back empty but refs/stash is not absent (an unreadable ref or reflog, or a ref pointing at a missing object)";
499
- /**
500
- * #376's line, and deliberately NOT the one above: there `refs/stash` is
501
- * present and unreadable, here it is gone while its reflog is not. Reusing
502
- * UNKNOWN_LINE would tell the operator "refs/stash is not absent" about a
503
- * state whose whole shape is that it IS, and send them to `ls -l` on a file
504
- * that no longer exists.
505
- */
506
- const ORPHAN_LINE =
507
- " stash entries (repo-global, not gated): unknown — refs/stash is absent but its reflog is not, and still names entries no ref points at";
508
- /**
509
- * #482's line, and the third of the three: the two above are reached with an
510
- * EMPTY list, this one with entries printed and a nonzero rc. Literal for the
511
- * same reason they are — `/unknown/` passes on any wording, so a reword naming
512
- * the wrong call as the one that failed would go unseen. git's own diagnostic
513
- * is appended after it, so what is pinned here is the prefix, not the line.
514
- */
515
- const RC_FAILED_LINE =
516
- " stash entries (repo-global, not gated): unknown — the list call itself failed, so what it printed cannot be read as a count";
517
- /**
518
- * #570's line, and the fourth. Of the three above only ORPHAN_LINE is reached
519
- * with the reflog path in hand: the resolution is guarded on an empty list AND
520
- * an absent ref, so UNKNOWN_LINE (ref present) and RC_FAILED_LINE (entries
521
- * printed) never ask for the path at all — measured. This one is reached
522
- * because asking for it FAILED. So it says only that the reflog could not be
523
- * reached and nothing about what it holds — ORPHAN_LINE's claim that the
524
- * reflog "still names entries no ref points at" is a claim about contents this
525
- * state has not read and cannot make.
526
- */
527
- const UNREACHED_LINE =
528
- " stash entries (repo-global, not gated): unknown — the reflog path could not be resolved, so the reflog could not be read";
529
- const stashLine = (r) => r.stderr.split("\n").find((l) => l.includes("stash entries (repo-global"));
530
- /**
531
- * `stashLine`'s sibling: every matching line, not just the first. `.find()`
532
- * above answers "what is the first sentence", and nothing built on it can
533
- * therefore see a SECOND stash-entry line appear — so a future edit that
534
- * breaks the if/elif/elif/else below into independent `if`s, letting two
535
- * arms fire for one state, would go unnoticed. The design rule for that
536
- * chain is one sentence per state — each `elif` branch names its own state
537
- * and prints exactly one line for it (no-undo-audit.sh:424-431, 490-505);
538
- * the length-1 assertions below are what actually enforces it. #1210.
539
- */
540
- const stashLines = (r) => r.stderr.split("\n").filter((l) => l.includes("stash entries (repo-global"));
541
-
542
- // `$wt` is caller-supplied and reaches the operator through a step header.
543
- // Under `#!/bin/sh` an `echo` operand expands escapes, so a worktree whose
544
- // name holds `\c` truncated that header and the next stderr line landed on
545
- // top of it. No corrupt repo needed — which makes this a strictly more
546
- // reachable instance of the same hazard as the stash line's, and the reason
547
- // `printf` is used at both sites.
548
- test("a worktree path holding a backslash escape reaches the operator whole", (t) => {
549
- const c = repo(t, "fix/1-thing", "no-undo-audit-back\\clue-");
550
- assert.match(c.w, /back\\clue/, "fixture must actually put a `\\c` in the path");
551
-
552
- const r = audit(c);
553
- assert.equal(r.status, 0, `fixture must be clean; got ${r.status} ${r.stderr}`);
554
- assert.ok(
555
- r.stderr.includes(`$ git -C ${c.w} status --porcelain`),
556
- "`echo` truncates the header at the `\\c` — it must name the worktree verbatim",
557
- );
558
- });
559
-
560
- // The same hazard on the refusal path. `die` interpolates `$wt` into 11 of
561
- // its messages and is the single place they all route through, so one `printf`
562
- // covers every one of them.
563
- test("a die message naming an unreachable worktree keeps the path whole", (t) => {
564
- const c = repo(t);
565
- const notARepo = `${c.w}-back\\clue-notarepo`;
566
- mkdirSync(notARepo);
567
-
568
- const r = audit({ w: notARepo, branch: c.branch });
569
- assert.equal(r.status, 2, `a non-worktree is unanswerable, not a refusal; got ${r.status} ${r.stderr}`);
570
- assert.ok(
571
- r.stderr.includes(`${notARepo} is not a git worktree`),
572
- `\`echo\` truncates the refusal at the \`\\c\`; got ${JSON.stringify(r.stderr)}`,
573
- );
574
- });
575
-
576
- // `$porcelain` carries the uncommitted file list — the audit's whole subject,
577
- // and the lines it prints when it REFUSES. A filename is free to hold `\c`.
578
- test("an uncommitted path holding a backslash escape survives the refusal listing", (t) => {
579
- const c = repo(t);
580
- writeFileSync(join(c.w, "back\\clue.txt"), "work that exists nowhere else\n");
581
-
582
- const r = audit(c);
583
- assert.equal(r.status, 1, `uncommitted work must refuse; got ${r.status} ${r.stderr}`);
584
- // git C-quotes a path holding a backslash, so the bytes on the wire are `\\`.
585
- // `echo` collapses that pair to one, silently rewriting the quoted path into
586
- // a different one — corruption rather than truncation here, but on the very
587
- // line the refusal prints. `-z` turns the same quoting OFF for the conflict
588
- // list below, which is why that one truncates outright instead.
589
- assert.ok(
590
- r.stderr.includes('?? "back\\\\clue.txt"'),
591
- `the C-quoted path must keep its doubled backslash; got ${JSON.stringify(r.stderr)}`,
592
- );
593
- });
594
-
595
- test("a pre-existing stash does not refuse a clean worktree", (t) => {
596
- const c = repo(t);
597
- stashSomething(c.w);
598
- assert.equal(git(c.w, "status", "--porcelain"), "", "fixture must leave the worktree clean");
599
- assert.equal(git(c.w, "stash", "list").split("\n").filter(Boolean).length, 1, "fixture must leave one stash");
600
-
601
- const r = audit(c);
602
- assert.equal(r.status, 0, `a stash the rebase will not consume must not refuse; got ${r.status} ${r.stderr}`);
603
- assert.equal(r.json.clean, true);
604
- assert.equal(r.json.stash, 1, "the count is still reported, just not gated on");
605
- assert.doesNotMatch(r.stderr, /REFUSED/);
606
- });
607
-
608
- test("several pre-existing stashes still do not refuse", (t) => {
609
- const c = repo(t);
610
- stashSomething(c.w, "h1.txt");
611
- stashSomething(c.w, "h2.txt");
612
- stashSomething(c.w, "h3.txt");
613
-
614
- const r = audit(c);
615
- assert.equal(r.status, 0, "the refusal must not scale with the count either");
616
- assert.equal(r.json.stash, 3);
617
- });
618
-
619
- test("a dirty worktree still refuses, and names the worktree not the stash", (t) => {
620
- const c = repo(t);
621
- writeFileSync(join(c.w, "uncommitted.txt"), "work that exists nowhere else\n");
622
-
623
- const r = audit(c);
624
- assert.equal(r.status, 1, "uncommitted work is the whole point of this audit");
625
- assert.equal(r.json.clean, false);
626
- assert.match(r.stderr, /REFUSED/);
627
- assert.match(r.stderr, /commit the worktree before rebasing/);
628
- // The old message told the caller to clear the stash list and forbade
629
- // `git stash drop` in the same refusal. Removing the gate must remove the
630
- // instruction, or the contradiction outlives the bug.
631
- assert.doesNotMatch(r.stderr, /stash-list-clear/);
632
- // `git stash`, not `git stash drop`: stashing to clear a dirty worktree now
633
- // leaves `clean` true, so this line is the only thing in the repo forbidding
634
- // a maneuver nothing detects. Narrowing it back to `drop` reads like a
635
- // consistency fix and silently reopens the hole.
636
- assert.match(r.stderr, /`git stash` to make a rebase start/);
637
- });
638
-
639
- // #730 (see reap.sh's branch sweep for the full explanation) — a bare
640
- // `--porcelain` reads `clean` over a dirty tree under
641
- // `status.showUntrackedFiles = no`. Load-bearing here beyond a reap: the
642
- // merge bot leans on this audit to authorize a REBASE, and the work a
643
- // rebase replays over may exist nowhere else.
644
- test("a dirty worktree still refuses under status.showUntrackedFiles=no (#730)", (t) => {
645
- const c = repo(t);
646
- writeFileSync(join(c.w, "uncommitted.txt"), "work that exists nowhere else\n");
647
- git(c.w, "config", "status.showUntrackedFiles", "no");
648
- assert.equal(git(c.w, "status", "--porcelain"), "",
649
- "fixture: the config must really silence the unpinned probe, or this test measures nothing");
650
-
651
- const r = audit(c);
652
- assert.equal(r.status, 1, `a silenced probe must not become a clean verdict; got ${r.status} ${r.stderr}`);
653
- assert.equal(r.json.clean, false);
654
- assert.match(r.stderr, /REFUSED/);
655
- assert.match(r.stderr, /commit the worktree before rebasing/);
656
- // Exit 1 is the refusal that means dirty; exit 2 means unanswerable. A fix
657
- // that turned the silenced answer into a refusal-to-answer would satisfy a
658
- // bare "not 0" and report the wrong thing about a worktree git can read.
659
- assert.match(r.stderr, /uncommitted\.txt/, "the file git could only see with the mode pinned must be named");
660
- });
661
-
662
- test("a dirty worktree refuses with an empty stash stack", (t) => {
663
- const c = repo(t);
664
- writeFileSync(join(c.w, "uncommitted.txt"), "work\n");
665
- assert.equal(git(c.w, "stash", "list"), "", "fixture must leave no stash");
666
-
667
- const r = audit(c);
668
- assert.equal(r.status, 1, "clean is the sole gate — it must fire on its own");
669
- assert.equal(r.json.stash, 0);
670
- });
671
-
672
- test("a clean worktree with no stash passes", (t) => {
673
- const c = repo(t);
674
- const r = audit(c);
675
- assert.equal(r.status, 0);
676
- assert.equal(r.json.clean, true);
677
- assert.equal(r.json.stash, 0);
678
- });
679
-
680
- // #147: `git stash list` prints nothing at rc 0 when the reflog behind
681
- // `refs/stash` cannot be read — no error to catch, so this used to report
682
- // `stash: 0`, indistinguishable from the case right above, where there really
683
- // is nothing. `show-ref` still finds `refs/stash` here (rc 0), which is what
684
- // tells the two apart.
685
- test("stash entries present but the reflog is unreadable reports unknown, not zero", (t) => {
686
- if (process.getuid?.() === 0) return t.skip("root reads a 000 file regardless");
687
- const c = repo(t);
688
- stashSomething(c.w);
689
- assert.equal(git(c.w, "stash", "list").split("\n").filter(Boolean).length, 1, "fixture must leave one stash");
690
- chmodSync(join(c.w, ".git", "logs", "refs", "stash"), 0o000);
691
-
692
- const r = audit(c);
693
- assert.equal(r.status, 0, `unknown must not gate the audit; got ${r.status} ${r.stderr}`);
694
- assert.equal(r.json.stash, null, "an unreadable reflog must report unknown, not the zero this used to silently report");
695
- assert.match(r.stderr, /unknown/);
696
- });
697
-
698
- // The third trap, and the one a `rev-parse --verify` cross-check cannot see:
699
- // the `refs/stash` FILE itself unreadable. The list comes back empty at rc 0
700
- // exactly as above, but this time the ref does not resolve either — so
701
- // rev-parse takes the genuinely-empty branch and prints the confident `0`
702
- // that #147 exists to remove. `show-ref` returns 1 only for a ref that is
703
- // genuinely ABSENT, and 128 for one that is there but unreadable, which is
704
- // what keeps the two apart.
705
- test("stash entries present but refs/stash is unreadable reports unknown, not zero", (t) => {
706
- if (process.getuid?.() === 0) return t.skip("root reads a 000 file regardless");
707
- const c = repo(t);
708
- stashSomething(c.w);
709
- assert.equal(git(c.w, "stash", "list").split("\n").filter(Boolean).length, 1, "fixture must leave one stash");
710
- chmodSync(join(c.w, ".git", "refs", "stash"), 0o000);
711
-
712
- const r = audit(c);
713
- assert.equal(r.status, 0, `unknown must not gate the audit; got ${r.status} ${r.stderr}`);
714
- assert.equal(r.json.stash, null, "an unreadable refs/stash must report unknown, not the zero a rev-parse cross-check reports");
715
- assert.match(r.stderr, /unknown/);
716
- });
717
-
718
- // The second, different trap: a corrupted stash ref (missing object) makes
719
- // `git stash list` itself fail — `fatal: bad object refs/stash`, rc 1 — but
720
- // the pipeline's exit status was always `wc`'s, never git's, so an rc capture
721
- // on the old pipeline would not have caught this either. `show-ref` fails
722
- // here at rc 128 rather than the rc 1 that means genuinely absent, so the
723
- // same cross-check catches this case too.
724
- test("a corrupted stash ref reports unknown, not zero", (t) => {
725
- const c = repo(t);
726
- stashSomething(c.w);
727
- const sha = git(c.w, "rev-parse", "refs/stash");
728
- rmSync(join(c.w, ".git", "objects", sha.slice(0, 2), sha.slice(2)));
729
-
730
- const r = audit(c);
731
- assert.equal(r.status, 0, `unknown must not gate the audit; got ${r.status} ${r.stderr}`);
732
- assert.equal(r.json.stash, null, "a corrupted stash object must report unknown, not zero");
733
- assert.match(r.stderr, /unknown/);
734
- });
735
-
736
- // #304: of the states above, exactly one has git saying anything —
737
- // `fatal: bad object refs/stash`. The counting pipeline's `2>/dev/null` threw
738
- // it away, so the operator got the guess in place of the answer git had
739
- // already named. Appended, never substituted: in the other states git is
740
- // silent, and the generic line is all there is.
741
- test("a corrupted stash ref passes git's own diagnostic through to the operator", (t) => {
742
- const c = repo(t);
743
- stashSomething(c.w);
744
- const sha = git(c.w, "rev-parse", "refs/stash");
745
- rmSync(join(c.w, ".git", "objects", sha.slice(0, 2), sha.slice(2)));
746
-
747
- const r = audit(c);
748
- assert.equal(r.status, 0, `unknown must not gate the audit; got ${r.status} ${r.stderr}`);
749
- assert.equal(r.json.stash, null, "the diagnostic is stderr only — the payload still says unknown");
750
- // The whole line, not `startsWith` plus a substring match: those two leave
751
- // the text between them unconstrained, so `msg="$msg$diag"` — separator
752
- // dropped entirely — satisfies both, as does any other joiner.
753
- assert.equal(
754
- stashLine(r),
755
- `${UNKNOWN_LINE} — fatal: bad object refs/stash`,
756
- "git named the fault; the audit must append it to the generic line, ` — ` and all, not substitute for it and not run it together",
757
- );
758
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
759
- });
760
-
761
- // #376: the fourth `show-ref` state, and the only one that used to print a
762
- // number. The three above all leave `refs/stash` resolvable, so they land on
763
- // rc 0 or rc 128 and trip the `-ne 1` guard. Delete the ref FILE and leave
764
- // `.git/logs/refs/stash` behind and `show-ref` exits **1** — the exact rc that
765
- // guard defines as genuine absence — while both stash commits are still named
766
- // in the reflog and still reachable. `git stash list` is empty at rc 0, so
767
- // nothing contradicts the `0`, and `0` is the value the runbook reads as
768
- // nothing to look at before an irreversible rebase.
769
- test("a deleted refs/stash with an intact reflog reports unknown, not zero", (t) => {
770
- const c = repo(t);
771
- stashSomething(c.w, "h1.txt");
772
- stashSomething(c.w, "h2.txt");
773
- rmSync(join(c.w, ".git", "refs", "stash")); // the ref file only — the reflog is untouched
774
-
775
- // The three conditions that make this indistinguishable from an empty stash
776
- // by everything the script asked before this change.
777
- const reflog = readFileSync(join(c.w, ".git", "logs", "refs", "stash"), "utf8").split("\n").filter(Boolean);
778
- assert.equal(reflog.length, 2, "fixture must leave both reflog entries behind");
779
- const showRef = spawnSync("git", ["show-ref", "refs/stash"], { cwd: c.w, env: ENV, encoding: "utf8" });
780
- assert.equal(showRef.status, 1, "the whole defect is this rc — the same one a genuinely empty stash gives");
781
- assert.equal(git(c.w, "stash", "list"), "", "and the list agrees with it, at rc 0");
782
-
783
- const r = audit(c);
784
- assert.equal(r.status, 0, `an orphaned stash reflog is a report, not a refusal; got ${r.status} ${r.stderr}`);
785
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
786
- assert.equal(r.json.stash, null, "two recoverable stash commits are still named in the reflog — `0` is not a claim the audit can make");
787
- assert.equal(stashLine(r), ORPHAN_LINE);
788
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
789
- });
790
-
791
- // The reflog path has to come from the repo's REAL gitdir. `$wt` is routinely a
792
- // linked worktree — the fleet's own layout, which is where this script actually
793
- // runs — and there `.git` is a FILE, so `$wt/.git/logs/refs/stash` reaches
794
- // nothing. A probe built on that path reads "no reflog", takes the accept
795
- // branch, and prints the same confident `0` this fix exists to remove, in the
796
- // one layout that matters. The stash stack is repo-global, so the entries are
797
- // created in the parent and seen from the worktree.
798
- test("the orphaned-reflog probe resolves against the shared gitdir, not $wt/.git", (t) => {
799
- const c = nestedWorktree(t);
800
- rmSync(join(c.w, "precious.txt")); // this fixture is otherwise dirty, and dirty refuses at exit 1
801
- stashSomething(c.parent, "h1.txt");
802
- rmSync(join(c.parent, ".git", "refs", "stash"));
803
-
804
- assert.ok(!existsSync(join(c.w, ".git", "logs", "refs", "stash")), "a naive $wt/.git path must find nothing here — that is what this test discriminates");
805
- assert.ok(existsSync(join(c.parent, ".git", "logs", "refs", "stash")), "the reflog lives in the shared gitdir");
806
- assert.equal(git(c.w, "status", "--porcelain"), "", "fixture must leave the worktree clean");
807
-
808
- const r = audit(c);
809
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
810
- assert.equal(r.json.stash, null, "the reflog is one directory up, and the probe has to follow git there");
811
- assert.equal(stashLine(r), ORPHAN_LINE);
812
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
813
- });
814
-
815
- // Every other fixture in this file spawns the script with `cwd === $wt`, which
816
- // is not how it is called: `run-merge-bot.md` runs `no-undo-audit.sh <worktree>
817
- // <branch>` from wherever the operator's shell already sits. `--git-path`
818
- // answers relative to `-C` in a main checkout, so a probe that keeps that
819
- // answer looks for the reflog under the CALLER's cwd, finds nothing, takes the
820
- // accept branch and prints the confident `0` this fix exists to remove — in the
821
- // one invocation that actually happens. Pinned as behaviour, not mechanism: the
822
- // probe has to resolve from anywhere, and how the path is made absolute is
823
- // git's business, not this test's.
824
- test("the orphaned-reflog probe resolves from a cwd that is not $wt", (t) => {
825
- const c = repo(t);
826
- stashSomething(c.w, "h1.txt");
827
- rmSync(join(c.w, ".git", "refs", "stash")); // the ref file only — the reflog is untouched
828
-
829
- const r = audit(c, ENV, tmpdir());
830
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
831
- assert.equal(r.json.stash, null, "the reflog is under $wt — resolved against the caller's cwd instead, it reads as absent and reports the `0` #376 removes");
832
- assert.equal(stashLine(r), ORPHAN_LINE);
833
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
834
- });
835
-
836
- // #570: the reflog path is resolved lazily, and resolving it needs search
837
- // permission on every ancestor directory. An unsearchable `logs/refs` makes
838
- // that call fail, and the `|| die` behind it turned a fault in a field the
839
- // script declares "reported, not gated" into a refusal of the WHOLE audit —
840
- // exit 2 with a zero-byte payload, withholding the `clean`, `conflicts` and
841
- // `atRisk` answers the audit exists to give before an irreversible rebase.
842
- // The suite already pins that rule twice above, with `unknown must not gate
843
- // the audit`, for the unreadable-reflog FILE and unreadable-ref FILE faults;
844
- // the unsearchable DIRECTORY is the same class.
845
- //
846
- // Both rows reach the probe: it is entered on an empty list plus a genuinely
847
- // absent ref, which is what a never-stashed repo looks like and what an
848
- // orphaned reflog looks like. So the common state — a repo that never stashed
849
- // at all — is one of them, and needed no stash history to refuse.
850
- //
851
- // The die's stated rationale was that a failure here means the repo went away
852
- // mid-run. These fixtures falsify it: the repository is entirely present, and
853
- // the worktree status and three earlier revision resolutions have already
854
- // succeeded on it. A repo that really goes away still refuses from the steps
855
- // that need it — the status and merge-tree probes both die on their own.
856
- for (const [why, prepare] of [
857
- ["a repository that never stashed", () => {}],
858
- ["a stash ref deleted while its reflog survived", (w) => { stashSomething(w); rmSync(join(w, ".git", "refs", "stash")); }],
859
- ]) {
860
- test(`an unsearchable reflog directory reports unknown rather than refusing the whole audit — ${why}, #570`, (t) => {
861
- if (process.getuid?.() === 0) return t.skip("root searches a 000 directory regardless");
862
- const c = repo(t);
863
- prepare(c.w);
864
- const dir = join(c.w, ".git", "logs", "refs");
865
- mkdirSync(dir, { recursive: true });
866
- assert.equal(git(c.w, "stash", "list"), "", "both fixtures must leave the list empty — that is what reaches the probe");
867
- chmodSync(dir, 0o000);
868
- const probe = spawnSync("git", ["-C", c.w, "rev-parse", "--path-format=absolute", "--git-path", "logs/refs/stash"], { env: ENV, encoding: "utf8" });
869
- assert.notEqual(probe.status, 0, "fixture must actually defeat the path resolution — that failure is the whole subject");
870
-
871
- const r = audit(c);
872
- // Restored here, not in a `t.after`: `repo` registers its own teardown
873
- // first and node runs them in that order, so an rmSync that cannot recurse
874
- // into a 000 directory fires before any later hook could reopen it.
875
- chmodSync(dir, 0o755);
876
- assert.equal(r.status, 0, `unknown must not gate the audit; got ${r.status} ${r.stderr}`);
877
- assert.equal(r.jsonError, null, `payload must parse — this used to be zero bytes; got ${r.jsonError?.message}\n${r.stdout}`);
878
- assert.equal(r.json.stash, null, "the probe could not look, so a number is not a claim it can make");
879
- assert.equal(stashLine(r), UNREACHED_LINE);
880
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — the ticket's own measured mutation (elif -> fi/if) doubles this state, #1210");
881
- // The other half of the ruling: this state must not borrow the sentence
882
- // that asserts what the reflog CONTAINS.
883
- assert.notEqual(stashLine(r), ORPHAN_LINE);
884
- // Degrading must not fall through to the confident `0` either: with the
885
- // path unresolved, the `-s` test that guards the orphan branch is false
886
- // against an empty string and the trailing branch prints the count.
887
- assert.doesNotMatch(r.stderr, /stash entries \(repo-global, not gated\): 0$/m);
888
- // git's own `fatal:` naming the path and the errno is the operator's whole
889
- // lead on WHICH directory to reopen — the audit's own sentence names none.
890
- // Unpinned, a `2>/dev/null` on that `rev-parse` deletes it silently: the
891
- // mutation leaves every other assertion here green (measured).
892
- assert.match(
893
- r.stderr,
894
- /fatal: .*logs\/refs\/stash.*Permission denied/,
895
- "git's unwrapped diagnostic is the only thing naming the directory",
896
- );
897
- // The audit's real subject still answers, which is the point of degrading.
898
- assert.equal(r.json.clean, true);
899
- assert.deepEqual(r.json.conflicts, []);
900
- });
901
- }
902
-
903
- // The control that keeps the guard above honest in the other direction, and
904
- // the one state it must NOT reach. Not by the count: an unsearchable
905
- // `logs/refs` empties `git stash list` too — it prints nothing at rc 0
906
- // (measured) — so `$stash` is 0 here exactly as in the rows above. What keeps
907
- // this state off #570's probe is `show-ref refs/stash` still answering rc 0,
908
- // which fails the probe's `sr_rc = 1` guard, so an unsearchable directory
909
- // lands on the existing empty-list unknown line, unchanged.
910
- test("a healthy stash under an unsearchable reflog directory keeps the sentence it already printed, #570", (t) => {
911
- if (process.getuid?.() === 0) return t.skip("root searches a 000 directory regardless");
912
- const c = repo(t);
913
- stashSomething(c.w);
914
- const dir = join(c.w, ".git", "logs", "refs");
915
- chmodSync(dir, 0o000);
916
-
917
- const r = audit(c);
918
- chmodSync(dir, 0o755); // see the sibling above — `repo`'s teardown runs before any `t.after` here
919
- assert.equal(r.status, 0, `unknown must not gate the audit; got ${r.status} ${r.stderr}`);
920
- assert.equal(r.json.stash, null);
921
- assert.equal(stashLine(r), UNKNOWN_LINE, "this state never reaches #570's probe — its line must not move");
922
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
923
- });
924
-
925
- // The other half of #376, and the more expensive one to get wrong. This script
926
- // gates an irreversible action; an operator who sees `unknown` on every run
927
- // stops reading it, and then the three states above go unread too. So the
928
- // accept case is pinned explicitly, across every way a stack empties honestly.
929
- //
930
- // Measured, git 2.50.1: `pop`, `drop`, `clear` and `update-ref -d` each remove
931
- // `.git/logs/refs/stash` outright — there is no lifecycle that empties the
932
- // stack and leaves the reflog behind, which is why the probe can be this
933
- // blunt. The zero-byte row is not reachable that way; it is here because
934
- // `-s` and `-e` differ on exactly it, and a probe testing mere existence
935
- // would turn it into `unknown` for nothing.
936
- for (const [why, prepare] of [
937
- ["never stashed at all", () => {}],
938
- // `pop` restores the entry staged, so the fixture has to put the worktree
939
- // back itself — the audit refuses a dirty one at exit 1 before it ever
940
- // reaches the stash line.
941
- ["stashed and popped", (w) => { stashSomething(w); git(w, "stash", "pop", "-q"); git(w, "rm", "-q", "-f", "h.txt"); }],
942
- ["stashed and dropped", (w) => { stashSomething(w); git(w, "stash", "drop", "-q"); }],
943
- ["stashed twice and cleared", (w) => { stashSomething(w, "h1.txt"); stashSomething(w, "h2.txt"); git(w, "stash", "clear"); }],
944
- ["the ref deleted with update-ref, which takes the reflog with it", (w) => { stashSomething(w); git(w, "update-ref", "-d", "refs/stash"); }],
945
- ["a zero-byte reflog left behind with no ref", (w) => { stashSomething(w); git(w, "stash", "clear"); mkdirSync(join(w, ".git", "logs", "refs"), { recursive: true }); writeFileSync(join(w, ".git", "logs", "refs", "stash"), ""); }],
946
- ]) {
947
- test(`an honestly empty stash still reports a confident zero — ${why}`, (t) => {
948
- const c = repo(t);
949
- prepare(c.w);
950
- assert.equal(git(c.w, "status", "--porcelain"), "", "fixture must leave the worktree clean");
951
- assert.equal(git(c.w, "stash", "list"), "", "fixture must leave no stash");
952
-
953
- const r = audit(c);
954
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
955
- assert.equal(r.json.stash, 0, "nothing is recoverable here — reporting `unknown` would be a worse bug than the one #376 fixes");
956
- assert.equal(stashLine(r), " stash entries (repo-global, not gated): 0");
957
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
958
- });
959
- }
960
-
961
- // #306: CHARACTERIZATION TEST, not a spec. The three tests above close every
962
- // unreadable-reflog case that fails LOUDLY enough for the `show-ref`
963
- // cross-check to notice. A reflog that is merely TRUNCATED — some lines
964
- // gone, the rest still parses — is the one case left open, named in-line,
965
- // right above the stash-counting pipeline this exercises, as "a remaining
966
- // ceiling" (grep the phrase rather than a line number — those drift). This
967
- // pins that known undercount so a later change to the block cannot silently
968
- // move it. It does NOT assert desired behavior, and no detection logic is
969
- // being added here — that was ruled out on the issue. If the gap is ever
970
- // closed for real, this test goes red and whoever closed it deletes it
971
- // deliberately; that is the point, not a regression.
972
- test("a truncated-but-parseable stash reflog reports the too-low count as exact — pins a known ceiling, not desired behaviour, #306", (t) => {
973
- // The citation above is an anchor, not decoration: the phrase it sends the
974
- // next reader to grep for has to still be in the script.
975
- assert.match(readFileSync(SCRIPT, "utf8"), /a remaining ceiling/, "no-undo-audit.sh no longer names the ceiling this test cites by phrase");
976
- const c = repo(t);
977
- stashSomething(c.w, "h1.txt");
978
- stashSomething(c.w, "h2.txt");
979
- stashSomething(c.w, "h3.txt");
980
- assert.equal(git(c.w, "stash", "list").split("\n").filter(Boolean).length, 3, "fixture must leave three stashes");
981
-
982
- // Drop the oldest reflog line — one per stash push, oldest first. The
983
- // remaining lines still parse, so `stash list` resolves the ref and
984
- // returns a shorter-but-nonempty list instead of failing loudly.
985
- const reflogPath = join(c.w, ".git", "logs", "refs", "stash");
986
- const lines = readFileSync(reflogPath, "utf8").split("\n").filter(Boolean);
987
- writeFileSync(reflogPath, lines.slice(1).join("\n") + "\n");
988
-
989
- // The two conditions that make the undercount invisible to the script's own
990
- // cross-check: the list call itself does not fail, and `show-ref` still
991
- // finds the ref. Neither signature the three tests above rely on fires.
992
- const list = spawnSync("git", ["stash", "list"], { cwd: c.w, env: ENV, encoding: "utf8" });
993
- assert.equal(list.status, 0, `truncation must not make the list call itself fail; got ${list.status} ${list.stderr}`);
994
- assert.equal(list.stdout.split("\n").filter(Boolean).length, 2, "fixture must leave a nonempty, undercounted list");
995
- const showRef = spawnSync("git", ["show-ref", "refs/stash"], { cwd: c.w, env: ENV, encoding: "utf8" });
996
- assert.equal(showRef.status, 0, `refs/stash must still resolve — this is why the cross-check sees no disagreement; got ${showRef.status} ${showRef.stderr}`);
997
-
998
- const r = audit(c);
999
- assert.equal(r.status, 0, `a truncated reflog must not gate the audit; got ${r.status} ${r.stderr}`);
1000
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1001
- assert.equal(r.json.stash, 2, "known-wrong: the true count is 3, and this pins the undercount printing as exact rather than `unknown`");
1002
- assert.doesNotMatch(r.stderr, /unknown/, "the cross-check misses this state, which is the whole ceiling");
1003
- assert.equal(stashLine(r), " stash entries (repo-global, not gated): 2", "the operator-facing line must print the undercount as a plain number");
1004
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
1005
- });
1006
-
1007
- // #482: one shape of that ceiling, and the one that is not a ceiling any more.
1008
- // Only this half of it — a MISSING non-tip object is skipped in silence at rc 0
1009
- // and stays under #306, which is why this fixture corrupts rather than removes.
1010
- // Corrupt the loose object behind a NON-TIP entry and the reflog stays
1011
- // intact, so `stash list` resolves the ref, prints the entries it could read,
1012
- // names the fault and exits 1 — a nonempty list at a nonzero rc, which is the
1013
- // one shape none of the `show-ref` states above produce. The cross-check sees
1014
- // no disagreement, so the rc is the whole signal, and the old pipeline gave
1015
- // `wc`'s status instead of git's. The count printed was short by exactly the
1016
- // entries git refused to read.
1017
- test("a corrupt loose object behind a non-tip stash entry reports unknown, not the count git could not finish, #482", (t) => {
1018
- const c = repo(t);
1019
- stashSomething(c.w, "h1.txt");
1020
- stashSomething(c.w, "h2.txt");
1021
- stashSomething(c.w, "h3.txt");
1022
- const sha = git(c.w, "rev-parse", "refs/stash@{2}"); // the OLDEST entry, not the tip
1023
- const obj = join(c.w, ".git", "objects", sha.slice(0, 2), sha.slice(2));
1024
- chmodSync(obj, 0o644); // loose objects are mode 444
1025
- writeFileSync(obj, "junk\n");
1026
-
1027
- // The signature that makes this state its own: git fails, and it fails
1028
- // AFTER printing entries. Measured here rather than asserted in prose,
1029
- // because both halves are what the fix reads and neither is obvious.
1030
- const list = spawnSync("git", ["stash", "list"], { cwd: c.w, env: ENV, encoding: "utf8" });
1031
- assert.equal(list.status, 1, `a corrupt non-tip object must make the list call fail; got ${list.status} ${list.stderr}`);
1032
- assert.equal(list.stdout.split("\n").filter(Boolean).length, 2, "fixture must leave a nonempty, undercounted list — an empty one lands on the show-ref branch instead");
1033
- const showRef = spawnSync("git", ["show-ref", "refs/stash"], { cwd: c.w, env: ENV, encoding: "utf8" });
1034
- assert.equal(showRef.status, 0, `refs/stash must still resolve — this is why the cross-check cannot see it; got ${showRef.status} ${showRef.stderr}`);
1035
- const reflog = readFileSync(join(c.w, ".git", "logs", "refs", "stash"), "utf8").split("\n").filter(Boolean);
1036
- assert.equal(reflog.length, 3, "the reflog is intact — the true count is 3, which is what makes the printed 2 a lie rather than a limit");
1037
-
1038
- const r = audit(c);
1039
- assert.equal(r.status, 0, `unknown must not gate the audit; got ${r.status} ${r.stderr}`);
1040
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1041
- assert.equal(r.json.stash, null, "a list call that failed is not a count — the payload must say unknown, never the short number");
1042
- assert.equal(stashLine(r).slice(0, RC_FAILED_LINE.length), RC_FAILED_LINE, "the operator-facing line must name THIS cause, not just say unknown — the other two say the list came back empty, which this state is not");
1043
- assert.match(stashLine(r), /fatal: loose object \S+ .* is corrupt/, "git named the fault outright; the audit must pass it through rather than guess");
1044
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
1045
- });
1046
-
1047
- // A stash object that is CORRUPT rather than missing reaches the same branch —
1048
- // list empty at rc 1, show-ref rc 0 — but git answers in SEVEN lines there, and
1049
- // a bad `objects/info/alternates` both adds three more and puts a backslash in
1050
- // them. That fixture is what makes the two hazards of `msg="$msg — $diag";
1051
- // echo "$msg"` observable at once: unfolded newlines put git's text at column 0
1052
- // where only the audit's own `$ git ...` step headers belong, and `echo` under
1053
- // `#!/bin/sh` eats the operator's line from the `\c` onward.
1054
- //
1055
- // The alternates path also makes git's LATER calls complain at column 0, which
1056
- // is why the fold assertion below is scoped to the diagnostic's own text rather
1057
- // than to every unindented line.
1058
- test("a multi-line diagnostic holding a backslash arrives folded and whole", (t) => {
1059
- const c = repo(t);
1060
- stashSomething(c.w);
1061
- const sha = git(c.w, "rev-parse", "refs/stash");
1062
- const obj = join(c.w, ".git", "objects", sha.slice(0, 2), sha.slice(2));
1063
- chmodSync(obj, 0o644);
1064
- writeFileSync(obj, "junk\n");
1065
-
1066
- // The rc both comments name for this state, measured rather than asserted in
1067
- // prose (#494). `stash list` FAILS here, unlike the states it stays silent
1068
- // about — and the counting pipeline takes `wc`'s status, so the branch still
1069
- // fires and the rc is discarded. That discard is why a wrong rc in the prose
1070
- // above could sit here for as long as it did without a test noticing.
1071
- const list = spawnSync("git", ["stash", "list"], { cwd: c.w, env: ENV, encoding: "utf8" });
1072
- assert.equal(list.status, 1, `a corrupt tip object must make the list call itself fail; got ${list.status} ${list.stderr}`);
1073
-
1074
- mkdirSync(join(c.w, ".git", "objects", "info"), { recursive: true });
1075
- writeFileSync(join(c.w, ".git", "objects", "info", "alternates"), "/no\\clue/objects\n");
1076
-
1077
- const r = audit(c);
1078
- assert.equal(r.json.stash, null, "a corrupt (not missing) stash object must reach the unknown branch too");
1079
- assert.match(stashLine(r), /fatal: loose object \S+ .* is corrupt/, "git named the fault; the audit must not drop it");
1080
- assert.match(
1081
- stashLine(r),
1082
- /\/no\\clue\/objects/,
1083
- "`echo` expands the `\\c` and truncates the line there — the path must arrive verbatim",
1084
- );
1085
- assert.equal(stashLines(r).length, 1, "exactly one stash-entry line — a broken elif chain would let a second one through, #1210");
1086
- const atColumn0 = r.stderr.split("\n").filter((l) => /^\S/.test(l) && /loose object|unable to unpack|inflate/.test(l));
1087
- assert.deepEqual(atColumn0, [], "git's diagnostic belongs folded into the audit's own indented line, never at column 0");
1088
- });
1089
-
1090
- // Its own test, not a line inside the behaviour test above: `assert` aborts the
1091
- // whole test function, so a prose drift ahead of `audit(c)` would pre-empt this
1092
- // file's only coverage of the #304 fold and `printf` hazards, and report the
1093
- // comment instead of the behaviour. Measured — with the fold dropped AND the
1094
- // comment reverted, the fold regression went unnamed and only the comment was
1095
- // reported.
1096
- test("no-undo-audit.sh's own comment names the rc the fixture above measures", () => {
1097
- // Bounded to the paragraph under test, not matched against the whole file: an
1098
- // unbounded end lets a later, unrelated occurrence of the phrase satisfy this
1099
- // after the real clause is deleted. Measured — that false green reproduces
1100
- // against an unbounded match and reds here. The gutter comes off before
1101
- // `phrase`'s wrap-tolerant `\s+`, because the clause is hard-wrapped and it is
1102
- // the `#`, not whitespace, that sits at the break.
1103
- const paragraph = between(
1104
- stripHashGutter(readFileSync(SCRIPT, "utf8")),
1105
- "A stash object that is CORRUPT",
1106
- "`printf`, not `echo`",
1107
- "no-undo-audit.sh",
1108
- );
1109
- assert.match(
1110
- paragraph,
1111
- phrase("list empty at rc 1"),
1112
- "no-undo-audit.sh states this same rc in its own comment; the two must not drift apart again",
1113
- );
1114
- });
1115
-
1116
- // The other half of #304, and the half a careless append breaks: the `stash
1117
- // list` this branch captures says nothing in either permission state, so the
1118
- // line must come out exactly as it did before — no trailing separator, no
1119
- // empty parenthetical, nothing dangling where the diagnostic would have gone.
1120
- // One test for both, because it is one behaviour: an empty capture appends
1121
- // nothing. Git as a whole is NOT silent in both — see the narrowing below.
1122
- test("the states `stash list` is silent about print the unknown line unchanged", (t) => {
1123
- if (process.getuid?.() === 0) return t.skip("root reads a 000 file regardless");
1124
- for (const path of [[".git", "logs", "refs", "stash"], [".git", "refs", "stash"]]) {
1125
- const c = repo(t);
1126
- stashSomething(c.w);
1127
- chmodSync(join(c.w, ...path), 0o000);
1128
-
1129
- const r = audit(c);
1130
- assert.equal(r.json.stash, null, `${path.join("/")}: fixture must reach the unknown branch`);
1131
- assert.equal(stashLine(r), UNKNOWN_LINE, `${path.join("/")}: git said nothing, so nothing may be appended`);
1132
- assert.equal(stashLines(r).length, 1, `${path.join("/")}: exactly one stash-entry line — a broken elif chain would let a second one through, #1210`);
1133
- // Reflog only. The `stash list` this branch captures is silent in both
1134
- // states, but git as a whole is not: in the `refs/stash` case the
1135
- // `show-ref` cross-check above prints `fatal: git show-ref: bad ref
1136
- // refs/stash (0000…)`, and the audit only looks silent there because that
1137
- // call runs under `>/dev/null 2>&1` (#481). Asserting no `fatal:` over
1138
- // that state would convert an unstated ceiling into an invariant, and make
1139
- // the follow-up edit a passing test.
1140
- if (path.includes("logs")) {
1141
- assert.doesNotMatch(r.stderr, /fatal:|warning:/, "the unreadable reflog is the one state git says nothing about at all");
1142
- }
1143
- }
1144
- });
1145
-
1146
- // The count stays reported-only, even at "unknown" — the dirty check is the
1147
- // sole gate, and an unreadable reflog must not mask it either.
1148
- test("a dirty worktree refuses even when the stash is unknown", (t) => {
1149
- if (process.getuid?.() === 0) return t.skip("root reads a 000 file regardless");
1150
- const c = repo(t);
1151
- stashSomething(c.w);
1152
- chmodSync(join(c.w, ".git", "logs", "refs", "stash"), 0o000);
1153
- writeFileSync(join(c.w, "uncommitted.txt"), "work\n");
1154
-
1155
- const r = audit(c);
1156
- assert.equal(r.status, 1, "unknown must not mask the dirty check, in either direction");
1157
- assert.equal(r.json.clean, false);
1158
- assert.equal(r.json.stash, null);
1159
- });
1160
-
1161
- // `clean` is now the sole gate, so a `git status` that fails must not read as a
1162
- // clean worktree. It used to have an accidental backstop: a repo holding any
1163
- // stash refused anyway, whatever `status` did. That backstop left with the gate.
1164
- test("a git status that fails is unanswerable (2), never clean (0)", (t) => {
1165
- if (process.getuid?.() === 0) return t.skip("root reads a 000 file regardless");
1166
- const c = repo(t);
1167
- writeFileSync(join(c.w, "uncommitted.txt"), "work that exists nowhere else\n");
1168
- chmodSync(join(c.w, ".git", "index"), 0o000);
1169
-
1170
- const r = audit(c);
1171
- assert.equal(r.status, 2, "an unreadable index cannot answer the question — it must not answer 'clean'");
1172
- assert.match(r.stderr, /cannot tell a clean worktree from a dirty one/);
1173
- assert.doesNotMatch(r.stdout, /"clean":true/);
1174
- });
1175
-
1176
- test("a dirty worktree refuses even when a stash is also present", (t) => {
1177
- const c = repo(t);
1178
- stashSomething(c.w);
1179
- writeFileSync(join(c.w, "uncommitted.txt"), "work\n");
1180
-
1181
- const r = audit(c);
1182
- assert.equal(r.status, 1, "the stash must not mask the dirty check, in either direction");
1183
- assert.equal(r.json.clean, false);
1184
- assert.equal(r.json.stash, 1);
1185
- });
1186
-
1187
- // ---------------------------------------------------------------------------
1188
- // conflicts[] and atRisk[]. The refusal above is only half the audit: a clean
1189
- // worktree still exits 0 while answering "what would a careless resolution
1190
- // eat", and that answer had no coverage at all.
1191
- // ---------------------------------------------------------------------------
1192
-
1193
- // One path carries both failures, because they compound. The space made the
1194
- // pathspec word-split into `has` + `space.txt`, so `atRisk` came back empty on
1195
- // a branch that really was about to eat a commit — a false safe, which is the
1196
- // one outcome this script exists to prevent. The quote made the payload
1197
- // unparseable, on exit 0, so a caller that got as far as reading the answer
1198
- // crashed instead. A path that git has to quote also proves the paths reaching
1199
- // the caller are real paths and not git's C-quoted rendering of them.
1200
- test("a conflicting path with a space and a quote still names the commits at risk", (t) => {
1201
- const path = 'has"quote and space.txt';
1202
- const c = conflictRepo(t, path);
1203
-
1204
- const fork = git(c.w, "merge-base", "origin/main", `origin/${c.branch}`);
1205
- const truth = git(c.w, "log", "--oneline", `${fork}..origin/main`, "--", path);
1206
- assert.equal(truth.split("\n").filter(Boolean).length, 1, "fixture must put exactly one main commit at risk");
1207
-
1208
- const r = audit(c);
1209
- assert.equal(r.status, 0, `a clean worktree passes even with conflicts; got ${r.status} ${r.stderr}`);
1210
- assert.equal(r.jsonError, null, `a passing audit must emit parseable JSON; got ${r.jsonError?.message}\n${r.stdout}`);
1211
- assert.deepEqual(r.json.conflicts, [path], "the real path, not git's C-quoted rendering of it");
1212
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"], `ground truth was ${truth}`);
1213
- assert.match(r.stderr, /at risk: /);
1214
- });
1215
-
1216
- // Same question, asked the other way: an ordinary path must not regress while
1217
- // the quoted one is being fixed.
1218
- test("a plain conflicting path names the commits at risk", (t) => {
1219
- const c = conflictRepo(t, "plain.txt");
1220
-
1221
- const r = audit(c);
1222
- assert.equal(r.status, 0);
1223
- assert.deepEqual(r.json.conflicts, ["plain.txt"]);
1224
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"]);
1225
- });
1226
-
1227
- // #148: above ARG_MAX, `xargs -0` runs `git log` once per batch of the
1228
- // pathspec list, and each invocation reports every commit touching ITS OWN
1229
- // batch — so a commit spanning several batches used to come back once per
1230
- // batch. `withSplitXargs` forces that split at 20 files instead of the
1231
- // thousands real ARG_MAX needs, reproducing the ticket's own measurement
1232
- // (`xargs -s 300`) without a ~1 MiB fixture.
1233
- //
1234
- // Sorted, because the set is the whole claim: once xargs splits, `atRisk` is
1235
- // the concatenation of per-batch outputs in PATHSPEC order, not `git log`'s
1236
- // reverse-chronological one, and which commit lands first depends on how the
1237
- // batch boundaries fall — which depends on the length of the tmpdir path.
1238
- // Asserting the emitted order would pin the environment, not the dedupe.
1239
- test("two commits spanning the conflicting paths are each named once in atRisk, even when xargs splits the pathspec list into several batches", (t) => {
1240
- const c = manyConflictsTwoCommits(t);
1241
- const xargs = withSplitXargs(t);
1242
-
1243
- const r = audit(c, { ...ENV, PATH: xargs.path });
1244
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1245
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1246
- assert.equal(r.json.conflicts.length, c.paths.length, "fixture must put every file in conflict");
1247
- assert.ok(xargs.batches() > 1, `xargs must actually split — ran git log ${xargs.batches()}x, and at 1 this test passes with the dedupe deleted`);
1248
- assert.deepEqual(
1249
- subjects(r).sort(),
1250
- ["MAIN COMMIT AT RISK, even paths", "MAIN COMMIT AT RISK, odd paths"],
1251
- "each commit named once, not once per xargs batch it lands in",
1252
- );
1253
- });
1254
-
1255
- // #522: this pipeline's status is `xargs`' — the last command — not that of the
1256
- // `git log` xargs drives, and there is no `pipefail` in POSIX sh to change
1257
- // that. So an xargs-side fault reaches the guard, and the guard used to answer
1258
- // for it by naming git log, sending the reader to git for a fault git never had.
1259
- // Induced with the same shim #148's test uses, at a size that leaves xargs no
1260
- // room for the command line at all, so it exits nonzero without running git.
1261
- // Only the audit's own line is pinned: the accompanying diagnostic is xargs'
1262
- // own and its wording differs between implementations.
1263
- test("an xargs-side failure listing the at-risk commits is unanswerable, and does not answer for it by naming git log", (t) => {
1264
- const c = bareConflictRepo(t, "plain.txt");
1265
- const xargs = withSplitXargs(t, 60);
1266
-
1267
- const r = audit(c, { ...ENV, PATH: xargs.path });
1268
- assert.equal(r.status, 2, `an at-risk list that could not be built is unanswerable, not a verdict; got ${r.status} ${r.stderr}`);
1269
- assert.equal(r.stdout.trim(), "", `exit 2 emits no payload — a payload is an answer; got ${r.stdout}`);
1270
- assert.match(
1271
- r.stderr,
1272
- /listing commits for the conflicting paths failed \(git log or xargs\)/,
1273
- "the guard no longer names both commands that can produce the status it reads",
1274
- );
1275
- assert.doesNotMatch(
1276
- r.stderr,
1277
- /git log failed for the conflicting paths/,
1278
- "the guard is back to blaming git log for a fault that can be xargs' own",
1279
- );
1280
- });
1281
-
1282
- /**
1283
- * Shadows `awk` on PATH with a wrapper that fails ONLY the dedupe call this
1284
- * guard reads, and defers to the real awk otherwise — so the earlier
1285
- * stash-counting `awk 'END{print NR}'` keeps working and the fault lands on
1286
- * the one statement under test. Same technique as `withBrokenEscaper`, and
1287
- * for its reason: the call is selected on the at-risk list flowing THROUGH
1288
- * it, never on the program text handed to it. Selecting on the literal
1289
- * `!seen[$1]++` looked equivalent and was not — a behaviour-preserving
1290
- * rewrite to `{if(!seen[$1]++)print}` fell straight through to the real awk,
1291
- * disarming the injection while the test went red as if the `|| die` had
1292
- * regressed (measured).
1293
- *
1294
- * Input is captured to a file and replayed byte-for-byte rather than through
1295
- * `printf`, which would turn the stash call's empty input into one blank line
1296
- * and its `NR` from 0 into 1.
1297
- *
1298
- * `fired` is the residual that selecting on content cannot cover: a rewrite
1299
- * routing the dedupe away from awk altogether still disarms the fault, and
1300
- * without this the run would again red as a guard regression rather than as
1301
- * an injection that never fired.
1302
- */
1303
- function withFailingDedupeAwk(t) {
1304
- const bin = mkdtempSync(join(tmpdir(), "no-undo-audit-awk-"));
1305
- t.after(() => rmSync(bin, { recursive: true, force: true }));
1306
- const real = execFileSync("sh", ["-c", "command -v awk"], { encoding: "utf8" }).trim();
1307
- writeExecStub(join(bin, "awk"), `#!/bin/sh
1308
- f="${bin}/stdin.$$"
1309
- cat > "$f"
1310
- if grep -qF 'MAIN COMMIT AT RISK' "$f"; then
1311
- : > "${bin}/fired"
1312
- echo "SHIM: forced awk failure for test" >&2
1313
- exit 13
1314
- fi
1315
- exec ${real} "$@" < "$f"
1316
- `);
1317
- return { path: `${bin}:${process.env.PATH}`, fired: join(bin, "fired") };
1318
- }
1319
-
1320
- // This statement is kept separate from the xargs/git-log pipe above it (see
1321
- // the comment ahead of the dedupe line in the script) precisely so an
1322
- // awk-side fault is diagnosed by name instead of swallowed into that pipe's
1323
- // status. Nothing forced that statement to fail before this test, so the
1324
- // separation it documents was unpinned -- deleting the `|| die` left this
1325
- // exact fixture green (measured): under `set -eu` a bare
1326
- // `at_risk=$(... | awk ...)` still aborts on the shim's exit 13, but with
1327
- // awk's own status and no named message, which is what the assertions below
1328
- // discriminate from the guard actually firing.
1329
- test("an awk-side failure deduplicating the at-risk commits is unanswerable, and names awk rather than the git-log/xargs pipe ahead of it", (t) => {
1330
- const c = bareConflictRepo(t, "plain.txt");
1331
-
1332
- const awk = withFailingDedupeAwk(t);
1333
- const r = audit(c, { ...ENV, PATH: awk.path });
1334
- assert.ok(existsSync(awk.fired),
1335
- "the fault injection never fired — the at-risk list no longer flows through awk, so every assertion below is measuring an unmutated run");
1336
- assert.equal(r.status, 2, `an at-risk list that could not be deduplicated is unanswerable, not a verdict; got ${r.status} ${r.stderr}`);
1337
- assert.equal(r.stdout.trim(), "", `exit 2 emits no payload -- a payload is an answer; got ${r.stdout}`);
1338
- assert.match(
1339
- r.stderr,
1340
- /awk failed deduplicating the at-risk commits/,
1341
- "the guard must name awk, not fall through to a bare set -e abort",
1342
- );
1343
- assert.doesNotMatch(
1344
- r.stderr,
1345
- /listing commits for the conflicting paths failed \(git log or xargs\)/,
1346
- "an awk-side fault must not be misreported as the git-log/xargs pipe ahead of it",
1347
- );
1348
- });
1349
-
1350
- /**
1351
- * Shadows `awk` on PATH with a wrapper that fails ONLY the stash-count call
1352
- * this guard reads — selected on content flowing THROUGH it, never on the
1353
- * program text handed to it, same technique and same reason as
1354
- * `withFailingDedupeAwk` above. `stash@{` is git's own `stash list` line
1355
- * prefix and cannot appear in the at-risk dedupe's commit-log input, so the
1356
- * two awk call sites stay distinguishable without either one shadowing the
1357
- * other.
1358
- */
1359
- function withFailingStashCountAwk(t) {
1360
- const bin = mkdtempSync(join(tmpdir(), "no-undo-audit-awk-stash-"));
1361
- t.after(() => rmSync(bin, { recursive: true, force: true }));
1362
- const real = execFileSync("sh", ["-c", "command -v awk"], { encoding: "utf8" }).trim();
1363
- writeExecStub(join(bin, "awk"), `#!/bin/sh
1364
- f="${bin}/stdin.$$"
1365
- cat > "$f"
1366
- if grep -qF 'stash@{' "$f"; then
1367
- : > "${bin}/fired"
1368
- echo "SHIM: forced awk failure for test" >&2
1369
- exit 13
1370
- fi
1371
- exec ${real} "$@" < "$f"
1372
- `);
1373
- return { path: `${bin}:${process.env.PATH}`, fired: join(bin, "fired") };
1374
- }
1375
-
1376
- // Same shape as the dedupe guard's own test above, and the fix for finding 1
1377
- // of #1160's follow-up review: this was the one external-tool command
1378
- // substitution left in the file with no guard, and it reproduced the EXACT
1379
- // symptom this script exists to remove — a clean worktree refused at exit 1,
1380
- // no payload, no cause named — because it ANSWERS a question (the stash
1381
- // count) rather than only rendering one, so it belongs with the `|| die`
1382
- // family below, not with `render`'s family above.
1383
- test("an awk-side failure counting the stash entries is unanswerable, and names awk rather than a bare set -e abort", (t) => {
1384
- const c = repo(t);
1385
- stashSomething(c.w);
1386
- assert.equal(git(c.w, "stash", "list").split("\n").filter(Boolean).length, 1, "fixture must leave one stash");
1387
-
1388
- const awk = withFailingStashCountAwk(t);
1389
- const r = audit(c, { ...ENV, PATH: awk.path });
1390
- assert.ok(existsSync(awk.fired),
1391
- "the fault injection never fired — the stash count no longer flows through awk, so every assertion below is measuring an unmutated run");
1392
- assert.equal(r.status, 2, `a stash count that could not be computed is unanswerable, not a verdict; got ${r.status} ${r.stderr}`);
1393
- assert.equal(r.stdout.trim(), "", `exit 2 emits no payload -- a payload is an answer; got ${r.stdout}`);
1394
- assert.match(
1395
- r.stderr,
1396
- /awk failed counting the stash entries/,
1397
- "the guard must name awk, not fall through to a bare set -e abort — the #1160 symptom this fixes",
1398
- );
1399
- });
1400
-
1401
- // #583: a POSIX pipeline's status is its LAST command's, so a fault in any
1402
- // earlier stage is invisible to `set -e` and to a trailing `|| die` alike. The
1403
- // stage that reads merge-tree's output is the one that can fail — measured on
1404
- // the locale fault #582 filed, `PIPESTATUS: 1 0 0`, the first stage exiting 1
1405
- // and truncating while the two behind it exit 0 on the short input handed to
1406
- // them. What came out was a SMALLER conflicts list at exit 0: a false safe from
1407
- // the one tool whose job is to say whether a rebase would eat a commit.
1408
- //
1409
- // The fault is injected on the file rather than on any one command, so the
1410
- // pin survives a change of reader: whatever reads merge-tree's output, it must
1411
- // refuse when it cannot.
1412
- test("merge-tree's output going unreadable at the moment it is read is unanswerable (2), never an empty conflicts list at exit 0", (t) => {
1413
- const c = bareConflictRepo(t, "plain.txt");
1414
-
1415
- const r = audit(c, { ...ENV, PATH: withUnreadableMergeTreeOutput(t) });
1416
- assert.equal(r.status, 2,
1417
- `a conflicts list that could not be read is unanswerable, not a verdict; got ${r.status} ${r.stderr}`);
1418
- assert.equal(r.stdout.trim(), "",
1419
- `exit 2 emits no payload — an empty conflicts[] here would be a false safe on a branch that really conflicts; got ${r.stdout}`);
1420
- assert.match(r.stderr, /could not read git merge-tree's output \(python3\)/,
1421
- "the guard names the command whose status it actually reads, the way #522 taught the at-risk guard to");
1422
- });
1423
-
1424
- // The other half of #583, and the one that rules `set -o pipefail` out even
1425
- // where a shell offers it: on a large CORRECT run the reader stops at the empty
1426
- // record by design and leaves merge-tree's prose tail unread, so a `tr | tr |
1427
- // awk` reads back `141 141 0 0` — two stages killed by SIGPIPE with nothing
1428
- // wrong. Adopting a prefix stage's status would refuse this run. It must
1429
- // answer, and answer in full.
1430
- test("a conflicting run whose unread tail outgrows a pipe buffer still answers, and answers in full", (t) => {
1431
- const c = longTailConflictRepo(t);
1432
- const tail = unreadTailBytes(c);
1433
- assert.ok(tail > 65536,
1434
- `the fixture must leave more unread than a pipe buffer holds, or nothing is being controlled for — left ${tail} bytes`);
1435
-
1436
- const r = audit(c);
1437
- assert.equal(r.status, 0, `a large correct run is an answer, not a refusal; got ${r.status} ${r.stderr}`);
1438
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}`);
1439
- assert.deepEqual([...r.json.conflicts].sort(), [...c.paths].sort(),
1440
- "every conflicting path, not the prefix that fitted before the reader stopped");
1441
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"]);
1442
- });
1443
-
1444
- // The at-risk half of #583. Its `|| die` reads the status of the LAST command
1445
- // in the pipeline that built the pathspec list, so the `printf | sed | tr` that
1446
- // once sat ahead of `xargs` could fail and leave `at_risk` short or empty at
1447
- // exit 0 — a branch reported as eating nothing while it really was about to.
1448
- // The fix is that the list no longer passes through them at all, and this is
1449
- // the assertion that says so: break `sed` on the invocation that used to build
1450
- // the pathspecs and the answer must be unchanged, because there is no longer
1451
- // such an invocation. Restore the pipeline and the decoy commit comes back with
1452
- // the real one, since an empty pathspec list leaves `git log` filtering by
1453
- // nothing.
1454
- //
1455
- // `conflictRepo`, not `bareConflictRepo`: the decoys are what make an
1456
- // unfiltered `git log` distinguishable from a correctly filtered one. Without
1457
- // them the range holds a single commit and the broken run returns the right
1458
- // answer for the wrong reason.
1459
- test("breaking the sed that used to build the at-risk pathspecs changes nothing, because nothing ahead of xargs can fail unseen", (t) => {
1460
- const c = conflictRepo(t, "plain.txt");
1461
-
1462
- const r = audit(c, { ...ENV, PATH: withBrokenEscaper(t, { tool: "sed", marker: "plain.txt", selector: "literal" }) });
1463
- assert.equal(r.status, 0, `nothing failed, so nothing is unanswerable; got ${r.status} ${r.stderr}`);
1464
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}`);
1465
- assert.deepEqual(r.json.conflicts, ["plain.txt"]);
1466
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"],
1467
- "the decoys are back, which means the pathspec list went through something that could fail without the guard hearing it");
1468
- });
1469
-
1470
- // A temporary the audit cannot create is a question it cannot answer, and the
1471
- // exit code has to say so: bare `set -eu` would abort with mktemp's own 1,
1472
- // which out of THIS script is the dirty-worktree refusal — fabricated on a
1473
- // worktree already measured clean, with no payload and nothing on stderr.
1474
- //
1475
- // The last assertion is about the abort PATH, not the verdict, and it is the
1476
- // one that needs saying: the fault lands between the two `mktemp` calls, so a
1477
- // cleanup trap armed after both would not yet exist when this run dies, and the
1478
- // temporary the first call created would outlive it. Exit code and message are
1479
- // both correct in that world, which is why they cannot be the whole pin —
1480
- // asking whether the file is gone is the only question that separates a trap
1481
- // armed early enough from one armed too late.
1482
- test("a temporary file the at-risk step cannot create is unanswerable (2), never the refusal that means dirty", (t) => {
1483
- const c = bareConflictRepo(t, "plain.txt");
1484
-
1485
- const m = withLaterMktempFailing(t);
1486
- const r = audit(c, { ...ENV, PATH: m.path });
1487
- assert.equal(r.status, 2,
1488
- `the worktree is clean and was measured clean — exit 1 here would report it dirty on the strength of a full TMPDIR; got ${r.status} ${r.stderr}`);
1489
- assert.equal(r.stdout.trim(), "", `exit 2 emits no payload; got ${r.stdout}`);
1490
- assert.match(r.stderr, /cannot create a temporary file/,
1491
- "and it names the cause rather than exiting silently");
1492
-
1493
- const first = readFileSync(m.firstTemp, "utf8").trim();
1494
- assert.ok(first, "the shim must have recorded the temporary the first call handed back, or the check below proves nothing");
1495
- assert.equal(existsSync(first), false,
1496
- `the temporary created before the failing call has to be cleaned up by the abort that follows it, or a run that dies here leaks one; ${first} survived`);
1497
- });
1498
-
1499
- // #146: a BS, tab, FF, CR or DEL in a conflicting path used to be replaced
1500
- // with a space, so `conflicts[]` named a file that exists nowhere on disk —
1501
- // this is the case the ticket itself measured. RFC 8259 gives short forms to
1502
- // all four control bytes (\b \t \f \r) and DEL (\177) is not a C0 byte at
1503
- // all, so all five must round-trip, and `conflictsRewritten` must say so. BS
1504
- // and FF are here because the first version of this fix scrubbed them anyway.
1505
- test("a conflicting path with a BS, a tab, a FF, a CR and a DEL round-trips and is not flagged rewritten", (t) => {
1506
- const path = "has\bbs\ttab\fff\rcr\x7fdel.txt";
1507
- const c = conflictRepo(t, path);
1508
-
1509
- const r = audit(c);
1510
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1511
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1512
- assert.deepEqual(r.json.conflicts, [path], "the real path, byte for byte — this is what a consumer pastes into `git diff --`");
1513
- assert.deepEqual(r.json.conflictsRewritten, [false], "escaped or preserved, not replaced");
1514
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"]);
1515
- });
1516
-
1517
- // The other half: a byte with no JSON short form still has to be replaced —
1518
- // unlike tab/CR/DEL, JSON has nowhere to put it — but the payload must now say
1519
- // so, since the runbook step that pastes `conflicts[]` into a diff command must
1520
- // skip exactly this path.
1521
- // \013 (VT) rides along with \002: it is the C0 byte that looks like it has a
1522
- // short form and does not — RFC 8259 lists no \v — so narrowing the scrub set
1523
- // to make room for \b and \f must not take VT out with them. Unescaped in a
1524
- // JSON string it is a parse error, so `jsonError` is the discriminator.
1525
- test("a conflicting path with bytes that have no short form is replaced and flagged rewritten", (t) => {
1526
- const path = "has\x02bell\x0bvt.txt";
1527
- const c = conflictRepo(t, path);
1528
-
1529
- const r = audit(c);
1530
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1531
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1532
- assert.deepEqual(r.json.conflicts, ["has bell vt.txt"], "no short form for \\002 or \\013 — both still neutralised to a space");
1533
- assert.deepEqual(r.json.conflictsRewritten, [true], "and the payload must disclose that it was");
1534
- });
1535
-
1536
- // `--` ends the options, not the pathspec magic, so a real file named
1537
- // `:colon.txt` is parsed as a pathspec expression and matches nothing. Same
1538
- // false safe as the space, reached by a different byte, and `:(literal)` is
1539
- // what closes it.
1540
- test("a conflicting path that looks like pathspec magic names the commits at risk", (t) => {
1541
- const path = ":colon.txt";
1542
- const c = conflictRepo(t, path);
1543
-
1544
- const r = audit(c);
1545
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1546
- assert.deepEqual(r.json.conflicts, [path]);
1547
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"], "a leading `:` must be matched literally, not as magic");
1548
- });
1549
-
1550
- // #582: `tr` is locale-sensitive, and under a UTF-8 locale BSD tr exits 1 on a
1551
- // byte that is not valid UTF-8. What that cost was measured on the `tr | tr |
1552
- // awk` that used to split merge-tree's output, where the FIRST stage was the
1553
- // one that failed — PIPESTATUS `1 0 0`, the second `tr` and `awk` both exiting
1554
- // 0 on the short input it handed them — so the real status sat in a non-final
1555
- // slot where `set -e` could not see it (the pipeline's status was awk's) and
1556
- // where the line carried no `|| die` of its own either. `conflicts` came back
1557
- // holding the single truncated entry `b`, `plain.txt` was dropped from the list
1558
- // entirely, `atRisk` was `[]`, and the audit exited 0: a false safe from the one
1559
- // tool whose whole job is to say whether a rebase would eat a commit, which is
1560
- // the outcome the comment above `conflicts=` says must be exit 2.
1561
- // `export LC_ALL=C` is the fix, and it is the convention inflight.sh already
1562
- // follows, both globally and per site.
1563
- //
1564
- // Past tense throughout, because that mechanism is no longer here to reproduce:
1565
- // #583 replaced the split with a single byte-oriented reader whose status
1566
- // nothing discards, so the pin is not what stands between that byte and a false
1567
- // safe on this path any more. The assertions below are unchanged by that —
1568
- // they assert the correct ANSWER, which is what both the split and the reader
1569
- // owe.
1570
- //
1571
- // WHAT KILLS THE MUTANT, and the difference matters to anyone tidying the
1572
- // script. Measured on this tree with the pin deleted: the reader parses both
1573
- // conflicting paths correctly whatever the locale, and the kill lands further
1574
- // down, in the `conflict: ` render that prints them to stderr. `sed` exits on
1575
- // the byte — `sed: RE error: illegal byte sequence` on `b\377ad.txt` — and
1576
- // emits nothing, so neither conflict line reaches stderr.
1577
- //
1578
- // It used to produce a second kill beside that one, and it no longer does. The
1579
- // render was a bare pipeline, so `set -eu` took sed's own 1 — which out of
1580
- // this script is the dirty-worktree refusal, fabricated on a worktree the
1581
- // audit had already printed `clean` for — and the status assertion below
1582
- // caught the mutant on that. #1160 put the render behind a guard, so the
1583
- // verdict no longer moves when it fails, and the status, payload and
1584
- // `subjects()` assertions below now all stay GREEN under the mutant.
1585
- //
1586
- // So the kill is the pair of STDERR assertions at the end of this test and
1587
- // nothing else. Measured both ways at #1160's own commit: with the pin, both
1588
- // conflicting paths are named; with it deleted, `no-undo-audit: could not
1589
- // render the conflicting-path list to stderr` stands in their place, at the
1590
- // same exit 0 over the same payload. Do not drop them to tidy the test —
1591
- // on this script nothing else observes the pin.
1592
- //
1593
- // The locale goes in as `LANG`, with `LC_ALL` explicitly UNSET, and both halves
1594
- // are load-bearing. Explicit rather than inherited, because a suite that takes
1595
- // whatever the runner happens to export pins nothing at all — same reasoning,
1596
- // and same technique, as inflight.test.mjs' own locale test. `LANG` rather than
1597
- // `LC_ALL`, because passing `LC_ALL` in puts it in the child's environment
1598
- // BEFORE the script runs, and a POSIX shell keeps a variable's export attribute
1599
- // once it is already there: a plain `LC_ALL=C` with the `export` keyword
1600
- // dropped would still reach `tr`, and these tests would go on passing against a
1601
- // script that exports nothing. Measured both ways — under
1602
- // `{ LC_ALL: "en_US.UTF-8" }` that mutant survives, under this shape it dies.
1603
- // It is also the honest shape: the ambient failure is an operator's
1604
- // `LANG=en_US.UTF-8` with `LC_ALL` unset.
1605
- //
1606
- // Platform ceiling, stated rather than hidden: BSD tr — macOS, the fleet's own
1607
- // platform — rejects the byte, while GNU tr is byte-oriented and accepts it, so
1608
- // on Linux the unpatched script already answers correctly and this test passes
1609
- // with or without the pin. Measured under a full GNU toolchain (coreutils 9.11,
1610
- // gnu-sed 4.10, gawk 5.4.1 ahead of PATH): the whole file stays green with
1611
- // `export LC_ALL=C` deleted. This test asserts the correct ANSWER, which is
1612
- // right on both platforms; only the macOS run kills the mutant. `ci.yml` runs
1613
- // ubuntu-latest, so the half CI can check is the source assertion in
1614
- // locale-pin-prose.test.mjs, not this one.
1615
- test("a conflicting path holding an invalid-UTF-8 byte still names every conflict and every commit at risk under an ambient UTF-8 locale", (t) => {
1616
- const c = byteConflictRepo(t, "b\\377ad.txt");
1617
-
1618
- const r = audit(c, { ...ENV, LANG: "en_US.UTF-8", LC_ALL: undefined });
1619
- assert.equal(r.status, 0, `a clean worktree passes even with conflicts; got ${r.status} ${r.stderr}`);
1620
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1621
- assert.equal(r.json.conflicts.length, 2,
1622
- `both conflicting paths, not a list truncated at the bad byte; got ${JSON.stringify(r.json.conflicts)}`);
1623
- assert.equal(r.json.conflicts[1], "plain.txt",
1624
- "the path AFTER the bad one is what truncation drops, and dropping it silently is the false safe");
1625
- assert.match(r.json.conflicts[0], /^b.ad\.txt$/, "the bad path arrives whole, not cut down to `b`");
1626
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"],
1627
- "and the commit a careless resolution would eat is named, rather than atRisk: [] at exit 0");
1628
- // The kill, per the block above. Matched on `.` rather than on the byte:
1629
- // `audit()` decodes the child's stderr as UTF-8 and substitutes U+FFFD for
1630
- // it on the way in, the same lossy read #613 measured on stdout.
1631
- assert.match(r.stderr, /^ {4}conflict: b.ad\.txt$/m,
1632
- "the render must name the bad path — with `export LC_ALL=C` deleted, sed exits on the byte and emits nothing");
1633
- assert.match(r.stderr, /^ {4}conflict: plain\.txt$/m,
1634
- "and the path behind it, which sed's failure takes with it whether it aborts the audit or not");
1635
- });
1636
-
1637
- // #613: the test above parses the payload through `audit()`'s
1638
- // `encoding: "utf8"`, and Node decodes a child's stdout as UTF-8 LOSSILY on
1639
- // the way in — the same silent U+FFFD substitution `jq` performs — so it
1640
- // cannot tell "the script emitted valid UTF-8" from "the script emitted a raw
1641
- // invalid byte and Node papered over it before JSON.parse ever saw it". This
1642
- // reads the raw bytes instead and checks them against the two consumers the
1643
- // issue measured: `jq`, which substitutes U+FFFD silently at exit 0
1644
- // (corrupting the data without saying so), and `python3 json.load`, a strict
1645
- // parser that refuses the payload outright with `UnicodeDecodeError`. Both
1646
- // must now accept the SAME bytes the script wrote, and the field naming which
1647
- // element lost a byte must say so honestly rather than silently.
1648
- test("a conflicting path holding an invalid-UTF-8 byte round-trips as valid, parseable UTF-8 JSON, with the fault flagged rather than hidden (#613)", (t) => {
1649
- const c = byteConflictRepo(t, "b\\377ad.txt");
1650
-
1651
- const r = spawnSync("sh", [SCRIPT, c.w, c.branch], { env: ENV, encoding: "buffer" });
1652
- assert.equal(r.status, 0,
1653
- `a clean worktree passes even with conflicts; got ${r.status} ${r.stderr?.toString("utf8")}`);
1654
- const raw = r.stdout;
1655
-
1656
- // Round-trip validity: re-encoding what a lossy UTF-8 decode produces
1657
- // reproduces the same bytes only when the buffer was already valid UTF-8.
1658
- assert.deepEqual(Buffer.from(raw.toString("utf8"), "utf8"), raw,
1659
- "the audit's own stdout is not valid UTF-8 — a raw invalid byte reached the payload");
1660
-
1661
- // `jq -e '.'` cannot pin the #613 bug on its own — it is one of the two
1662
- // LENIENT consumers the issue names, silently substituting U+FFFD at exit 0
1663
- // on a raw invalid byte just like Node's own decode above, so it would
1664
- // exit 0 against the pre-fix payload too. The round-trip check above and
1665
- // the strict `python3 json.load` below are what actually pin validity;
1666
- // this only confirms a real downstream consumer of this payload (several
1667
- // fleet scripts pipe conflicts/atRisk through jq) can parse it as
1668
- // well-formed JSON at all.
1669
- const jq = spawnSync("jq", ["-e", "."], { input: raw });
1670
- assert.equal(jq.status, 0, `jq must accept the payload as well-formed JSON; stderr: ${jq.stderr?.toString("utf8")}`);
1671
-
1672
- const py = spawnSync("python3", ["-c", "import json,sys; json.load(sys.stdin.buffer)"], { input: raw });
1673
- assert.equal(py.status, 0,
1674
- `a strict UTF-8 JSON parser must accept the payload; stderr: ${py.stderr?.toString("utf8")}`);
1675
-
1676
- const json = JSON.parse(raw.toString("utf8"));
1677
- assert.equal(json.conflicts.length, 2, "both conflicting paths are present");
1678
- assert.match(json.conflicts[0], /^b.ad\.txt$/, "the bad path arrives whole, not cut down to `b`");
1679
- assert.equal(json.conflicts[0].includes("�"), true,
1680
- "the fault must render as U+FFFD, not the original invalid byte and not silence");
1681
- assert.equal(json.conflictsRewritten[0], true,
1682
- "the path that lost a byte to U+FFFD must be flagged rewritten — a caller must not treat it as the real path");
1683
- assert.equal(json.conflictsRewritten[1], false, "the untouched path must not be flagged");
1684
- });
1685
-
1686
- // The other half of the same pin, and the half a fix-only suite never covers:
1687
- // what does `export LC_ALL=C` now REFUSE? It makes every `tr`, `sed` and `awk`
1688
- // in the script byte-oriented, so a path of legitimate multi-byte UTF-8 must
1689
- // still round-trip whole and must NOT be flagged rewritten. Every scrub set in
1690
- // this script is \001-\037 and every byte of a multi-byte UTF-8 sequence is
1691
- // >= \200 — the script's own jstr comment says so — so the pin cannot reach it.
1692
- // This is the test that keeps that true.
1693
- //
1694
- // Built through the same shell-side `printf` as the invalid case rather than
1695
- // through `conflictRepo`: written to disk, the name goes through the
1696
- // filesystem's Unicode normalisation, and `caf\303\251.txt` (NFC) can come back
1697
- // NFD — a byte-for-byte assertion failing for a reason that has nothing to do
1698
- // with this script.
1699
- test("a conflicting path of valid multi-byte UTF-8 round-trips whole under the pinned locale and is not flagged rewritten", (t) => {
1700
- const c = byteConflictRepo(t, "caf\\303\\251.txt");
1701
-
1702
- const r = audit(c, { ...ENV, LANG: "en_US.UTF-8", LC_ALL: undefined });
1703
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1704
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1705
- assert.deepEqual(r.json.conflicts, ["café.txt", "plain.txt"],
1706
- "byte for byte — this is what a consumer pastes into `git diff --`");
1707
- assert.deepEqual(r.json.conflictsRewritten, [false, false],
1708
- "a byte >= \\200 is outside every scrub set, and pinning the locale must not change that");
1709
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"]);
1710
- });
1711
-
1712
- // A commit subject is free text, so it reaches the payload with whatever the
1713
- // author typed. `\` matters as much as `"`: escaping the quote first and the
1714
- // backslash second turns `\` into `\\` twice over, so the order is load-bearing
1715
- // and only a subject holding both can tell a correct pipeline from that one.
1716
- // The \x01 rides along because git stores control bytes in a subject happily and
1717
- // JSON forbids them unescaped — dropping the scrub leaves the payload
1718
- // unparseable, which is this PR's own defect class one byte over.
1719
- // `$conflicts` and `$at_risk` are the last two operands carrying caller text,
1720
- // and `$at_risk` is the most reachable of the whole class: it holds
1721
- // `git log --oneline` output, so an ordinary commit subject is enough — no
1722
- // corrupt repo, no exotic filename. It is also the audit's most consequential
1723
- // line, the commits a careless resolution deletes. One fixture pins both.
1724
- test("a backslash escape in a conflicting path and in an at-risk subject reaches the operator whole", (t) => {
1725
- const c = conflictRepo(t, "back\\clue.txt");
1726
- git(c.w, "checkout", "-q", "main");
1727
- writeFileSync(join(c.w, "back\\clue.txt"), "MAIN AGAIN\n");
1728
- git(c.w, "commit", "-q", "-am", "fix: the \\connection retry");
1729
- git(c.w, "push", "-q", "origin", "main");
1730
- git(c.w, "checkout", "-q", c.branch);
1731
-
1732
- const r = audit(c);
1733
- assert.equal(r.status, 0, `fixture must be clean; got ${r.status} ${r.stderr}`);
1734
- assert.match(r.stderr, /^ conflict: back\\clue\.txt$/m, "`echo` truncates the conflict line at the `\\c`");
1735
- assert.match(r.stderr, /^ at risk: \S+ fix: the \\connection retry$/m, "`echo` truncates the at-risk line at the `\\c` — an ordinary commit subject is enough to lose it");
1736
- });
1737
-
1738
- test("a quote, a backslash and a control byte in a commit subject keep the payload parseable", (t) => {
1739
- const c = conflictRepo(t, "plain.txt");
1740
- git(c.w, "checkout", "-q", "main");
1741
- writeFileSync(join(c.w, "plain.txt"), "MAIN AGAIN\n");
1742
- git(c.w, "commit", "-q", "-am", 'fix: the "quoted" back\\slash \x01 case');
1743
- git(c.w, "push", "-q", "origin", "main");
1744
- git(c.w, "checkout", "-q", c.branch);
1745
- assert.match(git(c.w, "log", "-1", "--pretty=%s", "origin/main"), /\x01/, "fixture must keep the control byte in the subject");
1746
-
1747
- const r = audit(c);
1748
- assert.equal(r.status, 0);
1749
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1750
- assert.ok(
1751
- r.json.atRisk.some((l) => l.includes('the "quoted" back\\slash case')),
1752
- `the subject must survive escaping verbatim, the control byte scrubbed to a space; got ${JSON.stringify(r.json.atRisk)}`,
1753
- );
1754
- assert.deepEqual(r.json.atRiskRewritten, [true, false], "\\001 has no JSON short form — the payload must disclose the scrub");
1755
- });
1756
-
1757
- // #146: BS, tab, FF, CR and DEL in a commit subject get the opposite treatment
1758
- // from \x01 above — four now have JSON short forms and the fifth is not a C0
1759
- // byte at all, so all five must round-trip in atRisk[] too, and none may flag
1760
- // the entry as rewritten.
1761
- test("a BS, a tab, a FF, a CR and a DEL in a commit subject round-trip in atRisk without being flagged rewritten", (t) => {
1762
- const c = conflictRepo(t, "plain.txt");
1763
- git(c.w, "checkout", "-q", "main");
1764
- writeFileSync(join(c.w, "plain.txt"), "MAIN AGAIN\n");
1765
- git(c.w, "commit", "-q", "-am", "fix: has\bbs\ttab\fff\rcr\x7fdel case");
1766
- git(c.w, "push", "-q", "origin", "main");
1767
- git(c.w, "checkout", "-q", c.branch);
1768
-
1769
- const r = audit(c);
1770
- assert.equal(r.status, 0);
1771
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1772
- assert.ok(
1773
- r.json.atRisk.some((l) => l.includes("has\bbs\ttab\fff\rcr\x7fdel case")),
1774
- `all five bytes must survive verbatim; got ${JSON.stringify(r.json.atRisk)}`,
1775
- );
1776
- assert.deepEqual(r.json.atRiskRewritten, [false, false]);
1777
- });
1778
-
1779
- // git accepts `"` in a ref name and every byte but NUL and `/` in a path
1780
- // component, so both of these are names a caller can really hand over. `\` is
1781
- // rejected in a ref but legal in a path, which is why the backslash rides on
1782
- // the worktree.
1783
- test("a quote in the branch and a backslash in the worktree path keep the payload parseable", (t) => {
1784
- const c = repo(t, 'fix/1-say"hi', 'no-undo-audit-back\\slash-say"hi-');
1785
-
1786
- const r = audit(c);
1787
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1788
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1789
- assert.equal(r.json.branch, 'fix/1-say"hi');
1790
- assert.equal(r.json.worktree, c.w);
1791
- assert.equal(r.json.branchRewritten, false);
1792
- assert.equal(r.json.worktreeRewritten, false);
1793
- });
1794
-
1795
- // #146, the scalar fields: git forbids control bytes in a ref outright, so
1796
- // `branch` cannot carry one — but `worktree` is a filesystem path, the same
1797
- // vector as the conflicting-path cases above. Tab, CR and DEL must round-trip
1798
- // there too, and a byte with no short form must still be replaced and flagged.
1799
- test("a BS, a tab, a FF, a CR and a DEL in the worktree path round-trip and are not flagged rewritten", (t) => {
1800
- const c = repo(t, "fix/1-thing", "no-undo-audit-has\bbs\ttab\fff\rcr\x7fdel-");
1801
-
1802
- const r = audit(c);
1803
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1804
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1805
- assert.equal(r.json.worktree, c.w, "BS, tab, FF, CR and DEL must all survive intact");
1806
- assert.equal(r.json.worktreeRewritten, false);
1807
- });
1808
-
1809
- // The multi-line half of #146. `wt` is argv $1, a filesystem path, and a
1810
- // directory name may hold a newline where a ref may not — so this is the one
1811
- // input json.sh's `jstr` receives as more than one line from any live caller.
1812
- // It is
1813
- // what the `:a;$!N;$!ba` slurp and the `s/\n/\\n/g` rule exist for: without
1814
- // the slurp sed cycles once per LINE and the LF rule never sees the byte, so
1815
- // the payload carries a raw newline inside a JSON string and no parser accepts
1816
- // it. Deleting either half left the whole suite green before this test.
1817
- //
1818
- // The same value cannot be driven through release-ticket.sh or inflight.sh:
1819
- // release-ticket reaches `awk -v b="refs/heads/$branch"` first and awk refuses
1820
- // a newline in a -v value (rc 2, before any receipt); its only other
1821
- // interpolated message is the pair of `halt` calls that already flatten git's
1822
- // stderr with `tr '\n' ' '`; and inflight builds every evidence string from
1823
- // line-oriented git output. (No line numbers: #129 tracks five citations in
1824
- // these files that have already drifted, one of them mid-review here.)
1825
- // Since #119 there is one `jstr`, in json.sh, rather than three copies: those
1826
- // two callers reach the shared slurp with values that can never be multi-line,
1827
- // so this test is still the only place a real value exercises it.
1828
- test("a newline in the worktree path round-trips as an escaped \\n", (t) => {
1829
- const c = repo(t, "fix/1-thing", "no-undo-audit-has\nnewline-");
1830
-
1831
- const r = audit(c);
1832
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1833
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1834
- assert.equal(r.json.worktree, c.w, "the newline arrives escaped, and the path comes back byte for byte");
1835
- assert.equal(r.json.worktreeRewritten, false, "escaped, not replaced — \\012 is not in the scrub set");
1836
- });
1837
-
1838
- test("bytes with no short form in the worktree path are replaced and flagged rewritten", (t) => {
1839
- // \013 (VT) alongside \002 for the same reason as the conflicting-path case:
1840
- // RFC 8259 has no \v, so VT must stay in the scrub set after \b and \f left it.
1841
- const c = repo(t, "fix/1-thing", "no-undo-audit-has\x02bell\x0bvt-");
1842
-
1843
- const r = audit(c);
1844
- assert.equal(r.status, 0, `got ${r.status} ${r.stderr}`);
1845
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
1846
- assert.equal(r.json.worktree, c.w.replace("\x02", " ").replace("\x0b", " "), "no short form for \\002 or \\013 — both still neutralised to a space");
1847
- assert.equal(r.json.worktreeRewritten, true, "and the payload must disclose that it was");
1848
- });
1849
-
1850
- // ---------------------------------------------------------------------------
1851
- // Exit 2. Every one of these is "the question could not be answered"; none of
1852
- // them may reach the payload, because a payload is an answer.
1853
- // ---------------------------------------------------------------------------
1854
-
1855
- // `rev-parse --verify` resolves a tag to an object of ANY type, so a tag on a
1856
- // blob walks straight past it and into merge-tree, which refuses to merge it.
1857
- // git 2.50.1 spends exit 1 on that refusal — the same code it spends on "ran
1858
- // fine, found conflicts" — so the exit code alone cannot tell them apart and
1859
- // the audit used to print `"conflicts":[],"atRisk":[]` and exit 0. Safe, on a
1860
- // question it never asked.
1861
- // The section split reads an empty line as the end of the filename list, so a
1862
- // path holding a literal newline manufactures that marker: the list comes back
1863
- // short — sometimes empty — and the audit exits 0 saying nothing is at risk.
1864
- // git C-quoted such a path before `-z`, which at least emitted JSON the caller
1865
- // choked on, so answering "safe" here would be a strict downgrade. A shell
1866
- // variable cannot hold NUL, so the only honest answer is that there isn't one.
1867
- test("a conflicting path containing a newline is unanswerable (2), never safe (0)", (t) => {
1868
- const c = bareConflictRepo(t, "lead\nline.txt");
1869
- writeFileSync(join(c.w, "zz.txt"), "branch side\n");
1870
- git(c.w, "add", "--", "zz.txt");
1871
- git(c.w, "commit", "-q", "-m", "branch adds a second file");
1872
- git(c.w, "push", "-q", "origin", c.branch);
1873
- git(c.w, "checkout", "-q", "main");
1874
- writeFileSync(join(c.w, "zz.txt"), "MAIN SIDE\n");
1875
- git(c.w, "add", "--", "zz.txt");
1876
- git(c.w, "commit", "-q", "-m", "MAIN ALSO AT RISK");
1877
- git(c.w, "push", "-q", "origin", "main");
1878
- git(c.w, "checkout", "-q", c.branch);
1879
-
1880
- const r = audit(c);
1881
- assert.equal(r.status, 2, `got ${r.status} with stdout ${r.stdout}`);
1882
- assert.equal(r.stdout, "", "an unanswerable audit must not emit a payload");
1883
- assert.match(r.stderr, /contains a newline/);
1884
- });
1885
-
1886
- // merge-tree refuses unrelated histories at exit 128. Note what this does NOT
1887
- // pin: that refusal also writes nothing, so `[ -s ]` alone catches it and the
1888
- // `mt_rc` half of the guard can be deleted with the suite staying green
1889
- // (measured). No reachable input produces a bad exit code AND output, so the
1890
- // code check is there for a git that prints the tree OID and then fails.
1891
- test("unrelated histories are unanswerable (2), never safe (0)", (t) => {
1892
- const c = repo(t);
1893
- git(c.w, "checkout", "-q", "--orphan", "orphan");
1894
- git(c.w, "rm", "-rq", "--cached", ".");
1895
- writeFileSync(join(c.w, "o.txt"), "no shared ancestor\n");
1896
- git(c.w, "add", "--", "o.txt");
1897
- git(c.w, "commit", "-q", "-m", "orphan root");
1898
- git(c.w, "push", "-q", "origin", "orphan");
1899
- git(c.w, "checkout", "-qf", "main");
1900
- git(c.w, "clean", "-qfd");
1901
-
1902
- const r = audit({ w: c.w, branch: "orphan" });
1903
- assert.equal(r.status, 2, `got ${r.status} with stdout ${r.stdout}`);
1904
- assert.equal(r.stdout, "", "an unanswerable audit must not emit a payload");
1905
- assert.match(r.stderr, /cannot determine conflicts/);
1906
- });
1907
-
1908
- test("a BASE_REF that dereferences to a blob is unanswerable (2), never safe (0)", (t) => {
1909
- const c = repo(t);
1910
- const blob = git(c.w, "hash-object", "-w", "f.txt");
1911
- // Named under refs/remotes/ rather than as a tag, so it clears the
1912
- // accept-list (#1565) and reaches the qualify step unchanged, exercising
1913
- // rev-parse resolving to the wrong TYPE rather than the wrong ref.
1914
- git(c.w, "update-ref", "refs/remotes/origin/blobtag", blob);
1915
- assert.equal(git(c.w, "rev-parse", "--verify", "--quiet", "refs/remotes/origin/blobtag"), blob, "fixture must pass the rev-parse guard");
1916
-
1917
- const r = audit(c, { ...ENV, BASE_REF: "refs/remotes/origin/blobtag" });
1918
- assert.equal(r.status, 2, `merge-tree could not answer; got ${r.status} with stdout ${r.stdout}`);
1919
- assert.doesNotMatch(r.stdout, /"conflicts"/, "an unanswerable audit must not emit a payload");
1920
- assert.match(r.stderr, /cannot determine conflicts/);
1921
- });
1922
-
1923
- test("a local ref shadowing `origin/main` does not read a real add/add conflict as none (#1565)", (t) => {
1924
- // Same class release-ticket.sh, reap.sh and worktree-audit.sh already
1925
- // found in the same default — each qualifies the shorthand base into
1926
- // refs/remotes/<name> before measuring. `origin/main` is a SHORTHAND, and git
1927
- // resolves a shorthand through its own disambiguation order (gitrevisions:
1928
- // refs/<name>, refs/tags/<name>, refs/heads/<name>, refs/remotes/<name>,
1929
- // …), in which refs/remotes/origin/main comes LAST. A local TAG literally
1930
- // named `origin/main` outranks the real remote-tracking branch, so `git
1931
- // merge-tree` and `git merge-base`/`git log` against the bare shorthand
1932
- // below answer about the tag's target instead, at rc 0 — git's own
1933
- // `warning: refname 'origin/main' is ambiguous.` on stderr is the only
1934
- // tell, and this script reads none of it.
1935
- const path = "conflict.txt";
1936
- const c = bareConflictRepo(t, path);
1937
- // The tag points at the FORK point — one commit behind main's real tip —
1938
- // rather than at main's tip. The fork point never touched `path`, so a
1939
- // merge-tree probe against the tag sees only the branch's ADD and reports
1940
- // a clean merge; the real origin/main tip added the same path on its own
1941
- // side, which is the add/add conflict this fixture exists to carry.
1942
- const fork = git(c.w, "rev-parse", "main~1");
1943
- git(c.w, "tag", "origin/main", fork);
1944
- assert.equal(git(c.w, "rev-parse", "origin/main"), fork, "fixture: the shorthand now resolves to the fork point, not main's tip");
1945
- assert.notEqual(git(c.w, "rev-parse", "refs/remotes/origin/main"), fork, "fixture: the real upstream is still main's later commit");
1946
-
1947
- const r = audit(c);
1948
- assert.equal(r.status, 0, `a clean worktree passes even with conflicts; got ${r.status} ${r.stderr}`);
1949
- assert.equal(r.jsonError, null, `a passing audit must emit parseable JSON; got ${r.jsonError?.message}\n${r.stdout}`);
1950
- assert.deepEqual(r.json.conflicts, [path], "must measure the merge-tree probe against refs/remotes/origin/main, not the shadowing tag");
1951
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"], "must measure the at-risk commit list against refs/remotes/origin/main, not the shadowing tag");
1952
- });
1953
-
1954
- test("a local ref shadowing `origin/$branch` does not read a real add/add conflict as none (#1576)", (t) => {
1955
- // The branch-side twin of the test above. #1565 qualified only the base
1956
- // side into $base_rev; the branch side stayed the bare `origin/$branch`
1957
- // shorthand, so the identical false safe was still reachable by shadowing
1958
- // the BRANCH's name instead of the base's. A local TAG literally named
1959
- // `origin/<branch>` outranks the real remote-tracking branch in git's own
1960
- // disambiguation order (refs/tags/<name> before refs/remotes/<name>), so
1961
- // `git merge-tree` and `git merge-base` against the bare shorthand below
1962
- // would answer about the tag's target instead, at rc 0.
1963
- const path = "conflict.txt";
1964
- const c = bareConflictRepo(t, path);
1965
- // The tag points at the branch's PRIOR commit — one commit behind the
1966
- // branch's real tip, before it added `path` — rather than at the branch's
1967
- // real tip. A merge-tree probe against the tag then sees main's ADD of
1968
- // `path` against a branch state that never touched `path` at all: a clean
1969
- // merge, not the add/add conflict this fixture exists to carry.
1970
- const fork = git(c.w, "rev-parse", `${c.branch}~1`);
1971
- git(c.w, "tag", `origin/${c.branch}`, fork);
1972
- assert.equal(
1973
- git(c.w, "rev-parse", `origin/${c.branch}`),
1974
- fork,
1975
- "fixture: the shorthand now resolves to the branch's prior commit, not its real tip",
1976
- );
1977
- assert.notEqual(
1978
- git(c.w, "rev-parse", `refs/remotes/origin/${c.branch}`),
1979
- fork,
1980
- "fixture: the real upstream is still the branch's later commit",
1981
- );
1982
-
1983
- const r = audit(c);
1984
- assert.equal(r.status, 0, `a clean worktree passes even with conflicts; got ${r.status} ${r.stderr}`);
1985
- assert.equal(r.jsonError, null, `a passing audit must emit parseable JSON; got ${r.jsonError?.message}\n${r.stdout}`);
1986
- assert.deepEqual(r.json.conflicts, [path], "must measure the merge-tree probe against refs/remotes/origin/$branch, not the shadowing tag");
1987
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"], "must measure the at-risk commit list against refs/remotes/origin/$branch, not the shadowing tag");
1988
- });
1989
-
1990
- test("a local ref shadowing `origin/$branch` does not skew the merge-base call's at-risk range (#1576)", (t) => {
1991
- // The test above proves only that the merge-tree call reads
1992
- // refs/remotes/origin/$branch, not the shadowing tag: reverting just the
1993
- // merge-base call's `$branch_rev` argument back to the bare `origin/$branch`
1994
- // leaves it green, because merge-tree already used the qualified ref there
1995
- // and the shadowing tag it plants happens to share the real branch's own
1996
- // fork point with main. This fixture instead points the shadowing tag at
1997
- // main's OWN tip, so a merge-base computed against the tag collapses the
1998
- // at-risk range to nothing (`git merge-base main main` == main, so `git log
1999
- // main..main` is empty) while a merge-base against the real
2000
- // refs/remotes/origin/$branch still returns the true fork point and a
2001
- // non-empty at-risk list — the exact false "clean" #1576 exists to close.
2002
- const path = "conflict.txt";
2003
- const c = bareConflictRepo(t, path);
2004
- const mainTip = git(c.w, "rev-parse", "refs/remotes/origin/main");
2005
- git(c.w, "tag", `origin/${c.branch}`, mainTip);
2006
- assert.equal(
2007
- git(c.w, "rev-parse", `origin/${c.branch}`),
2008
- mainTip,
2009
- "fixture: the shorthand now resolves to main's own tip, not the branch",
2010
- );
2011
- assert.notEqual(
2012
- git(c.w, "rev-parse", `refs/remotes/origin/${c.branch}`),
2013
- mainTip,
2014
- "fixture: the real upstream is still the branch's own tip",
2015
- );
2016
-
2017
- const r = audit(c);
2018
- assert.equal(r.status, 0, `a clean worktree passes even with conflicts; got ${r.status} ${r.stderr}`);
2019
- assert.equal(r.jsonError, null, `a passing audit must emit parseable JSON; got ${r.jsonError?.message}\n${r.stdout}`);
2020
- assert.deepEqual(r.json.conflicts, [path], "the merge-tree call already reads refs/remotes/origin/$branch — unaffected by this fixture");
2021
- assert.deepEqual(
2022
- subjects(r),
2023
- ["MAIN COMMIT AT RISK"],
2024
- "must compute the merge-base against refs/remotes/origin/$branch, not the shadowing tag — a merge-base against the tag collapses the at-risk range to nothing",
2025
- );
2026
- });
2027
-
2028
- test("every unanswerable precondition exits 2 and emits no payload", (t) => {
2029
- const c = repo(t);
2030
- const plain = mkdtempSync(join(tmpdir(), "no-undo-audit-plain-"));
2031
- t.after(() => rmSync(plain, { recursive: true, force: true }));
2032
-
2033
- const cases = [
2034
- ["too few arguments", [c.w], ENV, /usage:/],
2035
- ["too many arguments", [c.w, c.branch, "extra"], ENV, /usage:/],
2036
- ["worktree does not exist", [join(c.w, "nope"), c.branch], ENV, /does not exist/],
2037
- ["not a git worktree", [plain, c.branch], ENV, /is not a git worktree/],
2038
- ["branch never pushed", [c.w, "never-pushed"], ENV, /origin\/never-pushed does not resolve/],
2039
- ["BASE_REF does not resolve", [c.w, c.branch], { ...ENV, BASE_REF: "origin/no-such-ref" }, /does not resolve/],
2040
- ["BASE_REF outside the remote-tracking namespace", [c.w, c.branch], { ...ENV, BASE_REF: "refs/heads/main" }, /BASE_REF must be spelled origin\/<branch> or refs\/remotes\/<path>, got 'refs\/heads\/main'/],
2041
- // Both spellings of the audited branch, because both clear the accept-list
2042
- // and both make every measurement ask whether the branch conflicts with
2043
- // ITSELF — `conflicts: []`, `atRisk: []` at exit 0 on a worktree that
2044
- // really does conflict with origin/main. A guard narrowed to the shorthand
2045
- // would leave the qualified half of that reachable, so both are pinned.
2046
- ["BASE_REF names the audited branch", [c.w, c.branch], { ...ENV, BASE_REF: `origin/${c.branch}` }, new RegExp(`BASE_REF must not name the audited branch, got 'origin/${c.branch}'`)],
2047
- ["BASE_REF names the audited branch, qualified", [c.w, c.branch], { ...ENV, BASE_REF: `refs/remotes/origin/${c.branch}` }, new RegExp(`BASE_REF must not name the audited branch, got 'refs/remotes/origin/${c.branch}'`)],
2048
- ];
2049
-
2050
- for (const [why, args, env, re] of cases) {
2051
- const r = spawnSync("sh", [SCRIPT, ...args], { cwd: c.w, env, encoding: "utf8" });
2052
- assert.equal(r.status, 2, `${why}: expected 2, got ${r.status} — ${r.stderr}`);
2053
- assert.match(r.stderr, re, why);
2054
- assert.equal(r.stdout, "", `${why}: an unanswerable audit must not emit a payload`);
2055
- }
2056
- });
2057
-
2058
- // ---------------------------------------------------------------------------
2059
- // Whose worktree is the answer about. Exit 2 again for the refusals, but the
2060
- // question is upstream of every check above: the script has to be looking at
2061
- // the tree it was handed. The passing case closes the block, because a guard
2062
- // that establishes identity is one keystroke from refusing every real worktree.
2063
- // ---------------------------------------------------------------------------
2064
-
2065
- // The `is not a git worktree` case in the preconditions above passes a plain
2066
- // directory with no repo ANYWHERE above it, so `rev-parse --git-dir` fails and
2067
- // the script refuses. That is the harmless half. These are the other half:
2068
- // `rev-parse --git-dir` WALKS UP, so with an enclosing repo present the gate
2069
- // passes at rc 0 having resolved a git dir that is not this worktree's, and
2070
- // `status --porcelain` then answers for that repo — empty, at rc 0, because the
2071
- // enclosing repo is clean and `.worktrees/` is gitignored. `clean:true` for a
2072
- // tree the script never looked at, with the work still sitting on disk. The
2073
- // `die` on a failing status is the wrong side of this: the command SUCCEEDS,
2074
- // it just answers about somewhere else.
2075
- //
2076
- // Both assert the refusal lands BEFORE the audit reports anything. Exit 2 alone
2077
- // would not pin it — a script that audits, prints "clean", and refuses
2078
- // afterwards has already put the wrong answer on the caller's screen.
2079
- function refusedAsUnknownBeforeAnySay(c) {
2080
- assert.ok(existsSync(join(c.w, "precious.txt")), "fixture: the uncommitted work must still be on disk");
2081
- assert.equal(git(c.parent, "status", "--porcelain"), "", "fixture: a CLEAN enclosing repo is what makes the leak answer 'clean'");
2082
- assert.doesNotThrow(
2083
- () => git(c.w, "rev-parse", "--git-dir"),
2084
- "fixture: the script's own gate must still pass here, or this test pins nothing",
2085
- );
2086
- assert.equal(git(c.w, "status", "--porcelain"), "", "fixture: git answers for the enclosing repo — the manufactured clean this must refuse");
2087
-
2088
- const r = audit(c);
2089
- assert.equal(r.status, 2, `got ${r.status} with stdout ${r.stdout}`);
2090
- assert.equal(r.stdout, "", "an unanswerable audit must not emit a payload");
2091
- assert.doesNotMatch(r.stderr, /status --porcelain/, "the refusal must land before the audit runs, let alone reports");
2092
- assert.match(r.stderr, /answers for the repo above/);
2093
- }
2094
-
2095
- test("a worktree whose .git was deleted is unanswerable (2), never clean (0)", (t) => {
2096
- const c = nestedWorktree(t);
2097
- rmSync(join(c.w, ".git"));
2098
-
2099
- refusedAsUnknownBeforeAnySay(c);
2100
- });
2101
-
2102
- // One byte over: an EMPTY `.git` DIRECTORY is something a `-e "$wt/.git"` guard
2103
- // calls present, and git walks up past it exactly as it does past an absent one.
2104
- test("a worktree whose .git is an empty directory is unanswerable (2), never clean (0)", (t) => {
2105
- const c = nestedWorktree(t);
2106
- rmSync(join(c.w, ".git"));
2107
- mkdirSync(join(c.w, ".git"));
2108
- assert.ok(existsSync(join(c.w, ".git")), "fixture: a `-e` guard must call this .git present, or it pins the case above again");
2109
-
2110
- refusedAsUnknownBeforeAnySay(c);
2111
- });
2112
-
2113
- // And one byte over again, which is why the guard asks git instead of stat-ing
2114
- // `.git`: a DIRECTORY holding a lone HEAD. Every "does the linkage exist" guard
2115
- // spelled against the filesystem calls this present — `-e "$wt/.git/HEAD"` most
2116
- // obviously — and git still walks up, because it wants HEAD *and* `objects/`
2117
- // *and* `refs/` before it will call a directory a git dir. Each subset below
2118
- // manufactured `clean:true` at exit 0 against such a guard (measured, git
2119
- // 2.50.1); the last is a REAL `.git` whose HEAD an interrupted write truncated,
2120
- // so this is not only a hand-built shape.
2121
- for (const [why, build] of [
2122
- ["holding a lone HEAD", (g) => writeFileSync(join(g, "HEAD"), "ref: refs/heads/fix/9-nested\n")],
2123
- ["whose HEAD is empty", (g) => writeFileSync(join(g, "HEAD"), "")],
2124
- ["missing objects/", (g) => {
2125
- writeFileSync(join(g, "HEAD"), "ref: refs/heads/fix/9-nested\n");
2126
- mkdirSync(join(g, "refs"));
2127
- }],
2128
- ]) {
2129
- test(`a worktree whose .git is a directory ${why} is unanswerable (2), never clean (0)`, (t) => {
2130
- const c = nestedWorktree(t);
2131
- rmSync(join(c.w, ".git"));
2132
- mkdirSync(join(c.w, ".git"));
2133
- build(join(c.w, ".git"));
2134
- assert.ok(existsSync(join(c.w, ".git", "HEAD")), "fixture: HEAD must be present, or this pins the empty-directory case again");
2135
-
2136
- refusedAsUnknownBeforeAnySay(c);
2137
- });
2138
- }
2139
-
2140
- // The other direction, and it is not theory: a guard spelled `-e
2141
- // "$wt/.git/HEAD"` alone passes every refusal test above (measured) while
2142
- // refusing every LINKED worktree on disk, whose `.git` is a file and which
2143
- // therefore has no `.git/HEAD` to stat. That is the fleet's own shape —
2144
- // `claim-ticket.sh` makes worktrees with `git worktree add` — so the false
2145
- // refusal would land on every real caller while the suite stayed green. This
2146
- // pins the shape the refusal tests do not reach.
2147
- test("an intact linked worktree, whose .git is a file, still passes", (t) => {
2148
- const c = nestedWorktree(t);
2149
- rmSync(join(c.w, "precious.txt"));
2150
- assert.ok(statSync(join(c.w, ".git")).isFile(), "fixture must leave the linkage intact, and leave it a FILE — the shape this test exists to pin");
2151
- assert.equal(git(c.w, "status", "--porcelain"), "", "fixture must leave the worktree clean");
2152
-
2153
- const r = audit(c);
2154
- assert.equal(r.status, 0, `a linked worktree is the fleet's own shape; got ${r.status} ${r.stderr}`);
2155
- assert.equal(r.json.clean, true);
2156
- });
2157
-
2158
- // The same worktree, reached through a symlinked path. `--show-toplevel`
2159
- // resolves the symlink away, so the linkage guard's working-tree compare
2160
- // (#2040) holds it against the CANONICAL `$wt`, never against the path as
2161
- // typed — this case is what reds if that canonicalisation is ever dropped.
2162
- test("an intact linked worktree, reached through a symlinked path, still passes", (t) => {
2163
- const c = nestedWorktree(t);
2164
- rmSync(join(c.w, "precious.txt"));
2165
- const link = `${c.w}-symlink`;
2166
- symlinkSync(c.w, link);
2167
- t.after(() => rmSync(link, { force: true }));
2168
-
2169
- const r = audit({ w: link, branch: c.branch });
2170
- assert.equal(r.status, 0, `a symlinked path to a real worktree must still pass; got ${r.status} ${r.stderr}`);
2171
- assert.equal(r.json.clean, true);
2172
- });
2173
-
2174
- // The same worktree, named `cafe` + U+0301 COMBINING ACUTE ACCENT and passed in
2175
- // the spelling `worktree list --porcelain` gives it — reap.sh's `nfd` fixture
2176
- // (#2072), here for the working-tree compare. Where the filesystem also
2177
- // resolves the precomposed spelling to that directory (APFS), the
2178
- // `core.precomposeunicode` `git clone` writes there lists it precomposed while
2179
- // `--show-toplevel` answers the on-disk NFD bytes, so a byte compare refused
2180
- // this healthy worktree at exit 2 (#2095). Where it does not (ext4), both
2181
- // answers are the NFD bytes and this is the plain case.
2182
- test("an intact linked worktree with an NFD name, passed as git lists it, still passes (#2095)", (t) => {
2183
- const { parent, w: onDisk, branch } = nestedWorktree(t, "cafe\u0301");
2184
- rmSync(join(onDisk, "precious.txt"));
2185
-
2186
- const listing = git(parent, "worktree", "list", "--porcelain").split("\n")
2187
- .filter((l) => l.startsWith("worktree ")).map((l) => l.slice(9));
2188
- const wt = listing.find((p) => p.normalize("NFC").endsWith("/.worktrees/caf\u00e9"));
2189
- assert.ok(wt, `fixture: git must list the worktree: ${listing}`);
2190
- const top = git(onDisk, "rev-parse", "--show-toplevel");
2191
- assert.ok(top.endsWith("/.worktrees/cafe\u0301"), "fixture: git must answer the on-disk NFD bytes");
2192
- if (existsSync(onDisk.normalize("NFC"))) {
2193
- assert.notEqual(wt, top, "fixture: a filesystem that aliases the two spellings must list one git's toplevel answer does not, byte for byte");
2194
- }
2195
-
2196
- const r = audit({ w: wt, branch });
2197
- assert.equal(r.status, 0, `an NFD-named worktree passed as git lists it must still pass; got ${r.status} ${r.stderr}`);
2198
- assert.equal(r.json.clean, true);
2199
- });
2200
-
2201
- // The same fixture, `$wt` passed exactly as it sits on disk (NFD) rather than
2202
- // as git lists it. `--show-toplevel` already answers this spelling, so this
2203
- // leaves the test above's working-tree compare a no-op and instead exercises
2204
- // the OWNER compares above it (#2095): `owner` is read back from git's own
2205
- // `gitdir` back-pointer file, spelled however `core.precomposeunicode` wrote
2206
- // it when the linkage was created (measured: precomposed, even though the
2207
- // directory itself stayed decomposed on disk), which can differ — byte for
2208
- // byte, same directory — from `$wt` as passed here.
2209
- test("an intact linked worktree with an NFD name, passed as it sits on disk, still passes (#2095)", (t) => {
2210
- const c = nestedWorktree(t, "cafe\u0301");
2211
- rmSync(join(c.w, "precious.txt"));
2212
-
2213
- const r = audit(c);
2214
- assert.equal(r.status, 0, `an NFD on-disk worktree path passed as-is must still pass; got ${r.status} ${r.stderr}`);
2215
- assert.equal(r.json.clean, true);
2216
- });
2217
-
2218
- // ---------------------------------------------------------------------------
2219
- // #189: whose ADMIN DIR answered, not just whose ROOT git resolved. A `.git`
2220
- // FILE takes its root from the file's own location, so a `.git` rewritten to
2221
- // name a SIBLING worktree's admin dir still passes --show-prefix — the root
2222
- // is genuinely $wt — while status is computed against the sibling's HEAD and
2223
- // index. Every case below refuses via `die`, exit 2, no payload: the guard
2224
- // establishes identity BEFORE the audit runs, same as the --show-prefix block
2225
- // above it, never a warning printed alongside a "clean" answer.
2226
- // ---------------------------------------------------------------------------
2227
-
2228
- test("a .git file naming a sibling worktree's admin dir is refused, never clean — the ticket's repro", (t) => {
2229
- const c = nestedWorktreePair(t);
2230
- assert.ok(existsSync(join(c.w, "precious.txt")), "fixture: uncommitted work must still be on disk");
2231
- // The ticket's leak needs more than an empty prefix: `status` is computed
2232
- // against the sibling's INDEX, but the WORKING TREE stays $wt's own files
2233
- // on disk (a `.git` file redirects the git-dir, not the work-tree). Content
2234
- // collision is what makes that read clean — the sibling commits the exact
2235
- // bytes $wt already has sitting there uncommitted.
2236
- writeFileSync(join(c.sibling, "precious.txt"), readFileSync(join(c.w, "precious.txt")));
2237
- git(c.sibling, "add", "precious.txt");
2238
- git(c.sibling, "commit", "-q", "-m", "precious.txt, committed here and only here");
2239
- writeFileSync(join(c.w, ".git"), `gitdir: ${c.siblingAdmin}\n`);
2240
- // The spoof still resolves a root of $wt and a foreign, CLEAN HEAD/index —
2241
- // the exact leak the ticket measured, reproduced before asserting the fix.
2242
- assert.equal(git(c.w, "rev-parse", "--show-prefix"), "", "fixture: the root claim must still admit, or this pins nothing new");
2243
- assert.equal(git(c.w, "status", "--porcelain"), "", "fixture: the sibling's HEAD must read clean, or this is the old leak by a different name");
2244
-
2245
- const r = audit(c);
2246
- assert.equal(r.status, 2, `must be unanswerable, not clean; got ${r.status} ${r.stdout}`);
2247
- assert.equal(r.stdout, "", "an unanswerable audit must not emit a payload");
2248
- assert.match(r.stderr, /names another worktree's admin dir/);
2249
- });
2250
-
2251
- test("a .git file naming a sibling's admin dir by a RELATIVE gitdir: path is refused the same way", (t) => {
2252
- const c = nestedWorktreePair(t);
2253
- // Relative to $wt/.git's own directory, i.e. $wt itself — same shape git
2254
- // itself resolves relative gitdir: lines against. Spelled as the literal the
2255
- // fixture's own layout already fixes, rather than computed: the assertion
2256
- // below is what keeps it honest, since a wrong spelling resolves elsewhere
2257
- // and fails there loudly.
2258
- writeFileSync(join(c.w, ".git"), "gitdir: ../../.git/worktrees/8-y\n");
2259
- assert.equal(git(c.w, "rev-parse", "--git-dir"), c.siblingAdmin, "fixture: git must resolve the relative spoof to the sibling admin dir, or this pins nothing new");
2260
-
2261
- const r = audit(c);
2262
- assert.equal(r.status, 2, `must be unanswerable, not clean; got ${r.status} ${r.stdout}`);
2263
- assert.equal(r.stdout, "");
2264
- assert.match(r.stderr, /names another worktree's admin dir/);
2265
- });
2266
-
2267
- // The same spoof, spelled as a SYMLINK instead of a `gitdir:` file. It is not a
2268
- // variant of the test above but a separate code path: `rev-parse --git-dir`
2269
- // answers the bare `.git` for this shape — the same string a main checkout
2270
- // answers — so a guard that reads that string as "the main worktree, nothing to
2271
- // verify" skips the linkage check entirely and admits the leak at exit 0.
2272
- // Measured on git 2.50.1, and measured admitted by the first spelling of this
2273
- // PR's own guard.
2274
- test("a .git SYMLINKED to a sibling worktree's admin dir is refused, never clean", (t) => {
2275
- const c = nestedWorktreePair(t);
2276
- assert.ok(existsSync(join(c.w, "precious.txt")), "fixture: uncommitted work must still be on disk");
2277
- writeFileSync(join(c.sibling, "precious.txt"), readFileSync(join(c.w, "precious.txt")));
2278
- git(c.sibling, "add", "precious.txt");
2279
- git(c.sibling, "commit", "-q", "-m", "precious.txt, committed here and only here");
2280
- rmSync(join(c.w, ".git"));
2281
- symlinkSync(c.siblingAdmin, join(c.w, ".git"));
2282
- assert.equal(git(c.w, "rev-parse", "--git-dir"), ".git", "fixture: this spelling must still answer the bare `.git`, or it is no longer the shape that bypassed the guard");
2283
- assert.equal(git(c.w, "rev-parse", "--show-prefix"), "", "fixture: the root claim must still admit, or this pins nothing new");
2284
- assert.equal(git(c.w, "status", "--porcelain"), "", "fixture: the sibling's HEAD must read clean, or this is the old leak by a different name");
2285
-
2286
- const r = audit(c);
2287
- assert.equal(r.status, 2, `must be unanswerable, not clean; got ${r.status} ${r.stdout}`);
2288
- assert.equal(r.stdout, "", "an unanswerable audit must not emit a payload");
2289
- assert.match(r.stderr, /names another worktree's admin dir/);
2290
- });
2291
-
2292
- test("an admin dir whose own gitdir back-pointer file is missing is unanswerable, never clean", (t) => {
2293
- const c = nestedWorktree(t);
2294
- const admin = git(c.w, "rev-parse", "--path-format=absolute", "--git-dir");
2295
- rmSync(join(admin, "gitdir"));
2296
-
2297
- const r = audit(c);
2298
- assert.equal(r.status, 2, `must be unanswerable, not clean; got ${r.status} ${r.stdout}`);
2299
- assert.equal(r.stdout, "");
2300
- assert.match(r.stderr, /gitdir is missing or unreadable/);
2301
- });
2302
-
2303
- test("an admin dir whose own gitdir back-pointer file is unreadable is unanswerable, never clean", (t) => {
2304
- const c = nestedWorktree(t);
2305
- const admin = git(c.w, "rev-parse", "--path-format=absolute", "--git-dir");
2306
- // No restore: the outer temp-dir cleanup (registered by `repo()`, and so
2307
- // ahead of this test's own `t.after`) force-removes the whole tree first,
2308
- // and deleting a file needs write access to its DIRECTORY, never to the
2309
- // file itself — same reasoning the existing stash-reflog fixtures above
2310
- // already rely on without restoring their own chmods.
2311
- chmodSync(join(admin, "gitdir"), 0o000);
2312
-
2313
- const r = audit(c);
2314
- assert.equal(r.status, 2, `must be unanswerable, not clean; got ${r.status} ${r.stdout}`);
2315
- assert.equal(r.stdout, "");
2316
- assert.match(r.stderr, /gitdir is missing or unreadable/);
2317
- });
2318
-
2319
- // The false-refusal side of the same trim: a legitimate back-pointer file with
2320
- // trailing whitespace tacked on must still compare equal, or the guard refuses
2321
- // worktrees it has no reason to. Real git never writes trailing whitespace
2322
- // here, but a hand-edited or copy-touched one could, and the comparison being
2323
- // exact-string means a wrong turn on this trim is a silent over-refusal, not
2324
- // a loud one.
2325
- test("a back-pointer file with trailing whitespace still passes, not falsely refused", (t) => {
2326
- const c = nestedWorktree(t);
2327
- rmSync(join(c.w, "precious.txt"));
2328
- const admin = git(c.w, "rev-parse", "--path-format=absolute", "--git-dir");
2329
- const gitdirFile = join(admin, "gitdir");
2330
- writeFileSync(gitdirFile, `${readFileSync(gitdirFile, "utf8").trimEnd()} \t\n`);
2331
-
2332
- const r = audit(c);
2333
- assert.equal(r.status, 0, `trailing whitespace on the back-pointer must not refuse; got ${r.status} ${r.stderr}`);
2334
- assert.equal(r.json.clean, true);
2335
- });
2336
-
2337
- // ---------------------------------------------------------------------------
2338
- // The ACCEPT side of the same guard. A gate on an irreversible action is as
2339
- // wrong when it refuses a healthy checkout as when it admits a spoofed one, and
2340
- // a suite that only feeds a refusal guard spoofs pins nothing about what it must
2341
- // still answer for. Every shape below is one `git` itself produces, and each
2342
- // was measured REFUSED (exit 2, no payload) by the first spelling of this
2343
- // guard. The intact-linked-worktree and symlinked-path cases above, and every
2344
- // `repo(t)` test in this file (a plain main checkout), are the rest of the set.
2345
- // ---------------------------------------------------------------------------
2346
-
2347
- // `--git-dir` answers the bare `.git` here too, exactly as it does for the
2348
- // sibling-admin-dir SYMLINK spoof above — so this is the pair that shows the
2349
- // guard discriminates on whose admin dir answered rather than on that string:
2350
- // same `--git-dir` answer, opposite verdict.
2351
- test("a .git symlinked to the worktree's OWN admin dir still passes", (t) => {
2352
- const c = nestedWorktree(t);
2353
- rmSync(join(c.w, "precious.txt"));
2354
- const admin = git(c.w, "rev-parse", "--path-format=absolute", "--git-dir");
2355
- rmSync(join(c.w, ".git"));
2356
- symlinkSync(admin, join(c.w, ".git"));
2357
- assert.equal(git(c.w, "rev-parse", "--git-dir"), ".git", "fixture: this must be the same `--git-dir` answer the spoof gives, or the pair proves nothing");
2358
-
2359
- const r = audit(c);
2360
- assert.equal(r.status, 0, `a .git symlinked to its own admin dir must pass; got ${r.status} ${r.stderr}`);
2361
- assert.equal(r.json.clean, true);
2362
- });
2363
-
2364
- // git writes the back-pointer RELATIVE, not absolute, whenever
2365
- // `worktree.useRelativePaths` is set — per-repo config, or `git worktree add
2366
- // --relative-paths` per invocation. Written here by hand rather than by that
2367
- // flag, in the exact spelling git produces (relative to the admin dir, which is
2368
- // what git resolves it against): the flag and the config both arrived in git
2369
- // 2.48, and a fixture that needs them stops covering anything, silently and
2370
- // green, on any older git the suite is run under.
2371
- test("a RELATIVE back-pointer still passes, not read as another worktree's admin dir", (t) => {
2372
- const c = nestedWorktree(t);
2373
- rmSync(join(c.w, "precious.txt"));
2374
- const admin = git(c.w, "rev-parse", "--path-format=absolute", "--git-dir");
2375
- writeFileSync(join(admin, "gitdir"), "../../../.worktrees/9-x/.git\n");
2376
-
2377
- const r = audit(c);
2378
- assert.equal(r.status, 0, `a relative back-pointer must not refuse; got ${r.status} ${r.stderr}`);
2379
- assert.equal(r.json.clean, true);
2380
- });
2381
-
2382
- // Neither shape below is a linked worktree, so neither admin dir carries a
2383
- // `gitdir` back-pointer to check — and "has no back-pointer" is not "belongs to
2384
- // another worktree". Both are `.git` FILES redirecting to a git dir elsewhere,
2385
- // which is what makes them land in the same guard as #189's spoof; both are
2386
- // DIRTY, so a pass here is the audit actually answering (exit 1, `clean:false`)
2387
- // rather than a refusal wearing a fail-safe exit code.
2388
- //
2389
- // Each audits its own checkout's feature branch rather than `main`: BASE_REF
2390
- // defaults to `origin/main`, and the audited-branch guard refuses a BASE_REF
2391
- // whose last component is the branch under audit, so `main` here would be
2392
- // refused at exit 2 before either shape reached the linkage question these two
2393
- // exist to ask.
2394
- test("a submodule checkout is audited, not refused for carrying no back-pointer", (t) => {
2395
- const c = repo(t);
2396
- const sub = repo(t, "fix/2-sub", "no-undo-audit-sub-");
2397
- git(c.w, "-c", "protocol.file.allow=always", "submodule", "add", "-q", git(sub.w, "remote", "get-url", "origin"), "sub");
2398
- const w = join(c.w, "sub");
2399
- writeFileSync(join(w, "dirt.txt"), "uncommitted, inside a submodule\n");
2400
-
2401
- const r = audit({ w, branch: sub.branch });
2402
- assert.equal(r.status, 1, `a dirty submodule must report dirty, not refuse; got ${r.status} ${r.stderr}`);
2403
- assert.equal(r.json.clean, false);
2404
- });
2405
-
2406
- test("a --separate-git-dir clone is audited, not refused for carrying no back-pointer", (t) => {
2407
- const c = repo(t);
2408
- const w = `${c.w}-sgd`;
2409
- execFileSync("git", ["clone", "-q", "--separate-git-dir", `${w}.git`, git(c.w, "remote", "get-url", "origin"), w], { env: ENV });
2410
- writeFileSync(join(w, "dirt.txt"), "uncommitted, in a --separate-git-dir clone\n");
2411
-
2412
- const r = audit({ w, branch: c.branch });
2413
- assert.equal(r.status, 1, `a dirty --separate-git-dir clone must report dirty, not refuse; got ${r.status} ${r.stderr}`);
2414
- assert.equal(r.json.clean, false);
2415
- });
2416
-
2417
- // Named in #189 alongside the spoof: not this ticket's mechanism (git refuses
2418
- // before the linkage guard even runs, same as a deleted `.git`), but the same
2419
- // enumerate pass that found the spoof named it too, so it is pinned here
2420
- // rather than assumed.
2421
- test("a dangling .git symlink is unanswerable (2), never clean (0)", (t) => {
2422
- const c = nestedWorktree(t);
2423
- rmSync(join(c.w, ".git"));
2424
- symlinkSync("/nonexistent-target-189", join(c.w, ".git"));
2425
-
2426
- refusedAsUnknownBeforeAnySay(c);
2427
- });
2428
-
2429
- // ---------------------------------------------------------------------------
2430
- // #2040: `core.worktree` moves the WORKING TREE, not the git dir. Every shape
2431
- // below passes the `--show-prefix` root claim (empty at rc 0) and the git-dir
2432
- // owner check, and `status` then compares $wt's own HEAD and index against the
2433
- // redirect target's files. A target holding the tracked content — any other
2434
- // checkout of the branch — reads clean at rc 0 over `precious.txt`: the one
2435
- // WRONG VERDICT this script can give, where every other broken shape refuses.
2436
- // Refused by the working-tree compare (`--show-toplevel` against the canonical
2437
- // $wt), exit 2, before anything is audited.
2438
- // ---------------------------------------------------------------------------
2439
-
2440
- /**
2441
- * The three fixture claims that make a redirect case pin something: the work
2442
- * is on disk, the root claim still admits the shape (or this is the #74 walk-up
2443
- * again under another name), and git itself answers "clean" — the false clean
2444
- * the refusal exists to replace. Then the refusal: exit 2, no payload, before
2445
- * the audit runs, naming the working tree git actually answered for.
2446
- */
2447
- function refusedAsRedirected(c, target) {
2448
- assert.ok(existsSync(join(c.w, "precious.txt")), "fixture: uncommitted work must still be on disk");
2449
- assert.equal(git(c.w, "rev-parse", "--show-prefix"), "", "fixture: the --show-prefix gate must still admit this shape, or this pins nothing new");
2450
- assert.equal(git(c.w, "rev-parse", "--show-toplevel"), target, "fixture: git must answer for the redirect target");
2451
- assert.equal(git(c.w, "status", "--porcelain", "-uall"), "", "fixture: git must read clean over the work — the false clean this pins");
2452
-
2453
- const r = audit(c);
2454
- assert.equal(r.status, 2, `a core.worktree redirect must be unanswerable, not clean: got ${r.status} ${r.stdout}`);
2455
- assert.equal(r.stdout, "", "an unanswerable audit must not emit a payload");
2456
- assert.doesNotMatch(r.stderr, /status --porcelain/, "the refusal must land before the audit runs");
2457
- assert.ok(r.stderr.includes(`git answers for the working tree at ${target}, not ${c.w}`), r.stderr);
2458
- }
2459
-
2460
- /** extensions.worktreeConfig on in `repoDir`, then `core.worktree` set for `w` alone. */
2461
- function redirectWorktree(repoDir, w, target) {
2462
- git(repoDir, "config", "extensions.worktreeConfig", "true");
2463
- git(w, "config", "--worktree", "core.worktree", target);
2464
- }
2465
-
2466
- test("b2: a linked worktree whose config.worktree sets core.worktree elsewhere is refused, never clean (#2040)", (t) => {
2467
- // The ticket's b2: `.git` untouched, `$gd` is $wt's own admin dir with its
2468
- // back-pointer intact, one `git config --worktree` away from a healthy tree.
2469
- const c = nestedWorktreePair(t);
2470
- redirectWorktree(c.parent, c.w, c.sibling);
2471
- refusedAsRedirected(c, git(c.sibling, "rev-parse", "--show-toplevel"));
2472
- });
2473
-
2474
- test("c2: a .git naming a foreign git dir NOT called .git, whose core.worktree is elsewhere, is refused (#2040)", (t) => {
2475
- // The ticket's c2. `$gd == common` and the `${gd%/.git}` strip is a no-op,
2476
- // so the owner check admits it as the ceiling's `--separate-git-dir` shape.
2477
- const c = nestedWorktree(t);
2478
- const root = dirname(c.parent);
2479
- const foreignGd = join(root, "foreign-gd");
2480
- const foreign = join(root, "foreign");
2481
- execFileSync("git", ["clone", "-q", "--separate-git-dir", foreignGd, git(c.parent, "remote", "get-url", "origin"), foreign], { env: ENV });
2482
- git(foreign, "checkout", "-q", c.branch);
2483
- git(foreign, "config", "core.worktree", foreign);
2484
- writeFileSync(join(c.w, ".git"), `gitdir: ${foreignGd}\n`);
2485
- assert.equal(git(c.w, "rev-parse", "--path-format=absolute", "--git-dir"), git(c.w, "rev-parse", "--path-format=absolute", "--git-common-dir"),
2486
- "fixture: the foreign git dir must be the common-dir shape the owner check admits");
2487
- refusedAsRedirected(c, git(foreign, "rev-parse", "--show-toplevel"));
2488
- });
2489
-
2490
- test("a MAIN checkout whose core.worktree names another checkout is refused, never clean (#2040)", (t) => {
2491
- // Beyond the ticket's table, and the cheapest of all: one `git config
2492
- // core.worktree` on an ordinary clone. `$gd == common`, named `.git`, owner
2493
- // `$wt` — the owner check has nothing to object to.
2494
- const c = repo(t);
2495
- const elsewhere = `${c.w}-elsewhere`;
2496
- git(c.w, "worktree", "add", "-q", "--detach", elsewhere);
2497
- git(c.w, "config", "core.worktree", elsewhere);
2498
- writeFileSync(join(c.w, "precious.txt"), "work that exists nowhere else\n");
2499
- refusedAsRedirected(c, git(elsewhere, "rev-parse", "--show-toplevel"));
2500
- });
2501
-
2502
- test("a core.worktree INSIDE $wt is refused: every file outside it goes unread (#2040)", (t) => {
2503
- const c = nestedWorktree(t);
2504
- const sub = join(c.w, "sub");
2505
- mkdirSync(sub);
2506
- for (const f of [".gitignore", "f.txt", "g.txt"]) copyFileSync(join(c.w, f), join(sub, f));
2507
- redirectWorktree(c.parent, c.w, sub);
2508
- refusedAsRedirected(c, git(sub, "rev-parse", "--show-toplevel"));
2509
- });
2510
-
2511
- test("a core.worktree naming a MISSING directory is unanswerable (2), never the dirty verdict (1) (#2040)", (t) => {
2512
- // git still answers `--show-toplevel` at rc 0 here (measured), so a guard
2513
- // that canonicalised that answer through `cd` would fail under `set -e` and
2514
- // exit 1 — the dirty verdict — over a tree nothing looked at.
2515
- const c = nestedWorktree(t);
2516
- const missing = join(dirname(c.parent), "never-created");
2517
- redirectWorktree(c.parent, c.w, missing);
2518
- const r = audit(c);
2519
- assert.equal(r.status, 2, `got ${r.status} ${r.stdout} ${r.stderr}`);
2520
- assert.equal(r.stdout, "");
2521
- assert.match(r.stderr, /answers for the working tree at .*never-created, not /);
2522
- });
2523
-
2524
- // Why the working-tree compare was ADDED to the owner check rather than
2525
- // replacing it: a `.git` naming a foreign git dir literally called `.git`
2526
- // whose `core.worktree` names $wt BACK passes the new compare — git answers
2527
- // for $wt — while every read goes against the foreign repo's HEAD and index.
2528
- // A foreign index that already carries `precious.txt`, byte for byte, reads
2529
- // clean over work that exists nowhere in THIS repo. Only the `${gd%/.git}`
2530
- // owner compare refuses it; drop that and this reds (measured, #2040).
2531
- test("a foreign */.git whose core.worktree names $wt back is still refused by the owner compare (#2040)", (t) => {
2532
- const c = nestedWorktree(t);
2533
- const foreign = join(dirname(c.parent), "foreign");
2534
- execFileSync("git", ["clone", "-q", git(c.parent, "remote", "get-url", "origin"), foreign], { env: ENV });
2535
- git(foreign, "checkout", "-q", c.branch);
2536
- copyFileSync(join(c.w, "precious.txt"), join(foreign, "precious.txt"));
2537
- git(foreign, "add", "precious.txt");
2538
- git(foreign, "commit", "-q", "-m", "precious, committed in a repo that is not $wt's");
2539
- git(foreign, "config", "core.worktree", c.w);
2540
- writeFileSync(join(c.w, ".git"), `gitdir: ${join(foreign, ".git")}\n`);
2541
- assert.equal(git(c.w, "rev-parse", "--show-toplevel"), `${git(c.parent, "rev-parse", "--show-toplevel")}/.worktrees/9-x`,
2542
- "fixture: git must answer for $wt itself, or the working-tree compare refuses this and it pins nothing about the owner check");
2543
- assert.equal(git(c.w, "status", "--porcelain", "-uall"), "", "fixture: the foreign index must read clean over the work");
2544
-
2545
- const r = audit(c);
2546
- assert.equal(r.status, 2, `got ${r.status} ${r.stdout}`);
2547
- assert.equal(r.stdout, "");
2548
- assert.match(r.stderr, /whose worktree is .*foreign, not /);
2549
- });
2550
-
2551
- // The `$(...)` that captures `wt_real` and `top` for the working-tree compare
2552
- // strips ALL trailing newlines, not one: a `core.worktree` target whose REAL
2553
- // directory name itself ends in a newline byte would lose it on both sides of
2554
- // the compare, so a redirect to a genuinely different directory could string-
2555
- // match into $wt. Constructed rather than found: `git worktree add`/`git
2556
- // config core.worktree` both accept the byte as an ordinary path character.
2557
- //
2558
- // `refusedAsRedirected` is not reused here: it asserts `--show-toplevel`
2559
- // against a JS-trimmed `target`, and `.trim()` removes the one real byte
2560
- // this case is about, which would make the fixture assertion itself fail
2561
- // against a correctly-fixed script. The behaviour asserted below is the
2562
- // same as every other redirect case: refused, no payload, before the audit.
2563
- test("a core.worktree target whose real name ends in a newline is still refused, never string-matched into $wt (#2040)", (t) => {
2564
- const c = nestedWorktree(t);
2565
- const twin = join(c.parent, ".worktrees", "9-x\n");
2566
- execFileSync("git", ["clone", "-q", git(c.parent, "remote", "get-url", "origin"), twin], { env: ENV });
2567
- git(twin, "checkout", "-q", c.branch);
2568
- redirectWorktree(c.parent, c.w, twin);
2569
-
2570
- const rawTop = execFileSync("git", ["-C", twin, "rev-parse", "--show-toplevel"], { env: ENV, encoding: "utf8" });
2571
- assert.ok(rawTop.endsWith("9-x\n\n"), "fixture: git must resolve the twin to its real, newline-suffixed path, or this pins nothing new");
2572
- assert.equal(
2573
- execFileSync("git", ["-C", c.w, "status", "--porcelain", "-uall"], { env: ENV, encoding: "utf8" }),
2574
- "",
2575
- "fixture: git must read clean through the newline-suffixed target — the false clean this pins",
2576
- );
2577
-
2578
- const r = audit(c);
2579
- assert.equal(r.status, 2, `a newline-suffixed redirect target must not string-compare equal to $wt: got ${r.status} ${r.stdout}`);
2580
- assert.equal(r.stdout, "", "an unanswerable audit must not emit a payload");
2581
- assert.match(r.stderr, /git answers for the working tree at/);
2582
- assert.match(r.stderr, /cannot tell a clean worktree from a dirty one/);
2583
- });
2584
-
2585
- // The ACCEPT side, which a refusal-only suite cannot see: the compare keys on
2586
- // the working tree git answers for, so a `core.worktree` that leaves it at $wt
2587
- // must still be audited. Both measured admitted with the fix in place.
2588
- test("a core.worktree naming $wt itself, through a symlinked spelling, is audited, not refused (#2040)", (t) => {
2589
- const c = nestedWorktree(t);
2590
- const link = join(dirname(c.parent), "parent-link");
2591
- symlinkSync(c.parent, link);
2592
- redirectWorktree(c.parent, c.w, join(link, ".worktrees", "9-x"));
2593
- const r = audit(c);
2594
- assert.equal(r.status, 1, `a core.worktree naming the worktree itself must not refuse: got ${r.status} ${r.stderr}`);
2595
- assert.equal(r.json.clean, false);
2596
- });
2597
-
2598
- test("a core.worktree git IGNORES — the common config, seen from a linked worktree — is audited, not refused (#2040)", (t) => {
2599
- // git does not apply the shared config's core.worktree to a linked worktree
2600
- // (measured: `--show-toplevel` and `status` both still answer for $wt), so
2601
- // refusing it would be refusing a setting that changes nothing.
2602
- const c = nestedWorktree(t);
2603
- git(c.parent, "config", "core.worktree", join(dirname(c.parent), "elsewhere"));
2604
- const r = audit(c);
2605
- assert.equal(r.status, 1, `got ${r.status} ${r.stderr}`);
2606
- assert.equal(r.json.clean, false);
2607
- });
2608
-
2609
- // ---------------------------------------------------------------------------
2610
- // Dirty means dirty. Every fixture above leaves an untracked file, which is the
2611
- // one form `status --porcelain` reports with no index involved at all.
2612
- // ---------------------------------------------------------------------------
2613
-
2614
- // A payload that could not be written is not an answer, but the script's exit
2615
- // code is spent before the write: without a guard the failing `printf` exits 1
2616
- // under `set -e`, and 1 is "REFUSED, worktree dirty" — a clean worktree
2617
- // reported as dirty, with no payload to contradict it. Same shape as the guard
2618
- // inflight.sh carries on its own final printf.
2619
- test("a payload that cannot be written is unanswerable (2), never a refusal (1)", (t) => {
2620
- const c = repo(t);
2621
-
2622
- // node cannot hand a child a closed fd 1, so sh closes it after the fork.
2623
- const r = spawnSync("sh", ["-c", '"$0" "$@" >&-', SCRIPT, c.w, c.branch], {
2624
- cwd: c.w,
2625
- env: ENV,
2626
- encoding: "utf8",
2627
- });
2628
- assert.equal(r.status, 2, `got ${r.status}; 1 would claim the worktree is dirty`);
2629
- // WHICH 2 it is, and the only signal a caller whose stdout is gone can still
2630
- // read. The design spec's row names this cause in its closed list (#1472),
2631
- // and a refusal that reached here silently would be indistinguishable from
2632
- // every other 2 in that list.
2633
- assert.match(r.stderr, /^no-undo-audit: could not write the audit for /m,
2634
- `the write failure must name itself on stderr; got ${JSON.stringify(r.stderr)}`);
2635
- });
2636
-
2637
- // --- #1514: the same question asked of the OTHER stream, and the direction
2638
- // that is strictly worse. A caller whose stdout is gone gets no payload and
2639
- // an honest 2, above. A caller whose stderr was gone got a complete payload
2640
- // saying `"clean":true` AND an exit 1 stacked on top of it — REFUSED, from
2641
- // the one tool whose job is to say whether a rebase would eat a commit, about
2642
- // a tree that had already been measured safe on the same run.
2643
- //
2644
- // The cause was the whole class, not one site: `set -e` reads a failed
2645
- // `echo`'s status, 1 out of this script is the dirty-worktree refusal, and
2646
- // every bare `>&2` diagnostic outside `render()` was an unguarded command.
2647
- // The run died on the FIRST of them — the status-command header, before git
2648
- // had been asked anything — so the verdict was fabricated by a stream that
2649
- // answers no part of the question. Measured on this exact fixture before the
2650
- // fix: exit 1.
2651
- test("a diagnostic stream that cannot be written is never a refusal (#1514)", (t) => {
2652
- const c = repo(t);
2653
-
2654
- // node cannot hand a child a closed fd 2 either, so sh closes it after the
2655
- // fork — the same shape the closed-stdout test above uses on fd 1.
2656
- const r = spawnSync("sh", ["-c", '"$0" "$@" 2>&-', SCRIPT, c.w, c.branch], {
2657
- cwd: c.w,
2658
- env: ENV,
2659
- encoding: "utf8",
2660
- });
2661
-
2662
- assert.equal(r.status, 0, `got ${r.status}; 1 would claim a clean worktree is dirty on the strength of a stream that measured nothing`);
2663
- // Losing the diagnostics is not losing the answer: the payload is the
2664
- // audit's actual output and it is unaffected by fd 2. Without this the
2665
- // status assertion above would also pass on a script that exited 0 early.
2666
- assert.equal(JSON.parse(r.stdout).clean, true,
2667
- `the verdict must still be delivered in full; got ${JSON.stringify(r.stdout)}`);
2668
- });
2669
-
2670
- // The other half of the pair, and the one that keeps the fix from being a
2671
- // blanket `exit 0`: `|| :` must swallow the WRITE, never the verdict. This
2672
- // tree really is dirty, the answer really is 1, and it has to survive having
2673
- // nowhere to print the refusal — the two-line REFUSED message is itself two
2674
- // of the newly guarded sites, and they sit after `rc=1` is already set.
2675
- test("a genuinely refused worktree still refuses (1) with stderr closed (#1514)", (t) => {
2676
- const c = repo(t);
2677
- writeFileSync(join(c.w, "uncommitted.txt"), "work that exists nowhere else\n");
2678
-
2679
- const r = spawnSync("sh", ["-c", '"$0" "$@" 2>&-', SCRIPT, c.w, c.branch], {
2680
- cwd: c.w,
2681
- env: ENV,
2682
- encoding: "utf8",
2683
- });
2684
-
2685
- assert.equal(r.status, 1, `uncommitted work must still refuse with no stderr to say so on; got ${r.status}`);
2686
- assert.equal(JSON.parse(r.stdout).clean, false,
2687
- `and the refusal must still carry the payload that justifies it; got ${JSON.stringify(r.stdout)}`);
2688
- });
2689
-
2690
- // `die` is the third outcome and was the worst of the three: its whole body
2691
- // is a write to fd 2 followed by `exit 2`, and `set -e` took the write's
2692
- // status before the `exit` was ever reached. So every unanswerable question —
2693
- // 30-odd `|| die` sites — came back 1 with stderr closed, telling an operator
2694
- // to commit a worktree the run had never managed to look at. Exit 2's own
2695
- // rule still holds here: no payload, because a payload is an answer.
2696
- test("an unanswerable question with stderr closed exits 2, never 1 (#1514)", (t) => {
2697
- const c = repo(t);
2698
- const notARepo = `${c.w}-notarepo`;
2699
- mkdirSync(notARepo);
2700
-
2701
- const r = spawnSync("sh", ["-c", '"$0" "$@" 2>&-', SCRIPT, notARepo, c.branch], {
2702
- cwd: c.w,
2703
- env: ENV,
2704
- encoding: "utf8",
2705
- });
2706
-
2707
- assert.equal(r.status, 2, `a non-worktree is unanswerable however unwritable stderr is; got ${r.status}`);
2708
- assert.equal(r.stdout.trim(), "", "exit 2 emits no payload — a payload is an answer");
2709
- });
2710
-
2711
- // --- #1571: the same three outcomes, but the descriptor is not closed before
2712
- // launch — a reader takes the first line and then genuinely leaves mid run,
2713
- // a real SIGPIPE rather than a write against a dead fd. Every write above
2714
- // this ticket guarded (`die`, `render`, `emit`) is a bare shell builtin, so
2715
- // it runs in the script's own process rather than a forked child: unguarded,
2716
- // the signal's default disposition killed that process on the spot, before
2717
- // `|| :` was ever consulted, and the script exited 141 — outside its own
2718
- // 0/1/2 contract and unreadable to a caller branching on which of the three
2719
- // it got. Measured before the fix, the case asserting a clean tree exits 0,
2720
- // never 141, itself returned 141.
2721
- //
2722
- // All three outcomes below are the closed-fd trio's own fixtures rerun
2723
- // through `earlyClosingStderrReaderStatus` instead of `2>&-` — the write
2724
- // that fails is now a signal, but which outcome the run reaches and what its
2725
- // payload says must be unchanged either way.
2726
- test("with a genuine SIGPIPE on stderr, a clean tree still exits 0, never 141 (#1571)", (t) => {
2727
- const c = repo(t);
2728
-
2729
- assert.equal(earlyClosingStderrReaderStatus(c), 0,
2730
- "a reader leaving mid run must not turn a safe tree into a signal death");
2731
- });
2732
-
2733
- test("with a genuine SIGPIPE on stderr, a genuinely refused tree still exits 1, never 141 (#1571)", (t) => {
2734
- const c = repo(t);
2735
- writeFileSync(join(c.w, "uncommitted.txt"), "work that exists nowhere else\n");
2736
-
2737
- assert.equal(earlyClosingStderrReaderStatus(c), 1,
2738
- "uncommitted work must still refuse — not 0 (the signal never reached), not 141 (it reached and killed the run)");
2739
- });
2740
-
2741
- test("with a genuine SIGPIPE on stderr, an unanswerable question still exits 2, never 141 (#1571)", (t) => {
2742
- const c = repo(t);
2743
- const notARepo = `${c.w}-notarepo`;
2744
- mkdirSync(notARepo);
2745
-
2746
- assert.equal(earlyClosingStderrReaderStatus({ w: notARepo, branch: c.branch }, c.w), 2,
2747
- "die's own write is a bare printf too — the same signal that killed the process before this fix must not reach it either");
2748
- });
2749
-
2750
- test("a modified tracked file refuses, like an untracked one", (t) => {
2751
- const c = repo(t);
2752
- writeFileSync(join(c.w, "f.txt"), "edited in place, committed nowhere\n");
2753
- // `git` trims, and porcelain spends its first column on the index — so the
2754
- // status this fixture needs is ` M`, read here with that column already gone.
2755
- assert.equal(git(c.w, "status", "--porcelain"), "M f.txt", "fixture must modify a tracked file, unstaged");
2756
-
2757
- const r = audit(c);
2758
- assert.equal(r.status, 1, "an edit to a tracked file exists nowhere else either");
2759
- assert.equal(r.json.clean, false);
2760
- });
2761
-
2762
- test("a staged change refuses", (t) => {
2763
- const c = repo(t);
2764
- writeFileSync(join(c.w, "staged.txt"), "staged, never committed\n");
2765
- git(c.w, "add", "staged.txt");
2766
- assert.equal(git(c.w, "status", "--porcelain"), "A staged.txt", "fixture must stage without committing");
2767
-
2768
- const r = audit(c);
2769
- assert.equal(r.status, 1, "the index is not a commit — a rebase does not carry it");
2770
- assert.equal(r.json.clean, false);
2771
- });
2772
-
2773
- /** The design spec's script-surface row for this script, as one line. */
2774
- function specRow() {
2775
- const spec = readFileSync(
2776
- fileURLToPath(new URL("../../docs/specs/2026-07-23-fleet-plugin-design.md", import.meta.url)),
2777
- "utf8",
2778
- );
2779
- const row = spec.split("\n").find((l) => l.startsWith("| `no-undo-audit.sh` |"));
2780
- assert.ok(row, "the script-surface table must still carry a no-undo-audit.sh row");
2781
- return row;
2782
- }
2783
-
2784
- // The design spec's script-surface table names this script's payload field by
2785
- // field, and #146 added four fields to it. The table went stale in the same
2786
- // commit that added them — the fix for that is one edited row, and this is the
2787
- // part that keeps the next one from going stale silently. Derived from a real
2788
- // run, never from a hand-written key list: a list typed here drifts from the
2789
- // script exactly the way the table did.
2790
- test("the design spec's script-surface row names every field the payload actually emits", (t) => {
2791
- const c = repo(t);
2792
- const r = audit(c);
2793
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
2794
-
2795
- const row = specRow();
2796
-
2797
- // The Out cell alone, since the rest of the row legitimately names things that
2798
- // are not keys: scanning the whole row let the In cell's `<worktree>` satisfy
2799
- // `worktree` and the `Non-zero when` prose's "the stash count is reported"
2800
- // satisfy `stash`, so either could be dropped from the type signature with
2801
- // this test green (measured, both directions).
2802
- const out = row.split("|")[3];
2803
-
2804
- // Word-boundary match, so `worktree` cannot be satisfied by `worktreeRewritten`
2805
- // sitting elsewhere in the cell — the exact substring trap that would let the
2806
- // four new flags be dropped again while this test stayed green.
2807
- const missing = Object.keys(r.json).filter((k) => !new RegExp(`\\b${k}\\b`).test(out));
2808
- assert.deepEqual(missing, [], `the spec row omits fields the script emits: ${missing.join(", ")}`);
2809
- });
2810
-
2811
- // Both docs describe this script's exit-2 causes, and its linkage clause covers
2812
- // THREE failures git reports differently. A parenthetical naming only the
2813
- // walk-up one stood, byte-identical, in both files, and was false for the
2814
- // second (#420); the third arrived with #2040. Measured, git 2.50.1: delete the
2815
- // worktree's `.git` and `rev-parse --show-prefix` returns `.worktrees/<wt>/`
2816
- // while `--show-toplevel` is the enclosing repo; rewrite that file to
2817
- // `gitdir: …/worktrees/<sibling>` and `--show-prefix` is empty at rc 0 with
2818
- // `--show-toplevel` the worktree itself, while HEAD, the branch and `status`
2819
- // all answer from the sibling; set `core.worktree` elsewhere and
2820
- // `--show-prefix` is still empty at rc 0 while `--show-toplevel` and `status`
2821
- // answer for the other directory, against $wt's own HEAD and index.
2822
- //
2823
- // ONE exact-span assertion rather than a match per mechanism, because the claim
2824
- // lives in the JOIN: separate matches for `enclosing repo` and for `another
2825
- // worktree's HEAD and index` are both satisfied by a rewrite that re-merges the
2826
- // two into a single wrong account ("git walks up and reports the enclosing
2827
- // repo, or reads another worktree's HEAD and index"), which is the defect this
2828
- // pin exists to keep out. Safe to pin as an exact span because both carriers
2829
- // are one unwrapped line — a table row and a prose paragraph — so there is no
2830
- // reflow to survive.
2831
- //
2832
- // SCOPE of the rc-0 clause: measured for a worktree nested inside its repo —
2833
- // the only shape this fleet builds, since `claim-ticket.sh` derives the
2834
- // worktree path under `.worktrees/` relative to the repo root. Outside any
2835
- // repo the clause's own subject does not exist: with `.git` deleted git has
2836
- // nothing to walk up to and `rev-parse` exits 128, though the script still
2837
- // refuses at exit 2, via its not-a-git-worktree die rather than the one for
2838
- // git answering above the worktree (measured, git 2.50.1). Re-open if the
2839
- // fleet ever places a worktree outside the repo — the clause then needs
2840
- // scoping, and the string is byte-identical across the docs this test reads
2841
- // and this constant, so every carrier moves together.
2842
- const LINKAGE_PARENTHETICAL =
2843
- "its linkage is broken, and git still answers at rc 0 — for the enclosing repo when the `.git` is gone, from another worktree's HEAD and index when it names that worktree's admin dir, against another directory's files when `core.worktree` moves the working tree there";
2844
-
2845
- test("both docs' exit-2 prose keeps the three linkage failures distinct", () => {
2846
- for (const [rel, anchor] of [
2847
- ["../commands/run-merge-bot.md", (l) => l.includes("Exit **2**")],
2848
- ["../../docs/specs/2026-07-23-fleet-plugin-design.md", (l) => l.startsWith("| `no-undo-audit.sh` |")],
2849
- ]) {
2850
- const line = readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8")
2851
- .split("\n").find(anchor);
2852
- assert.ok(line, `${rel} must still describe this script's exit-2 causes`);
2853
- assert.ok(line.includes(LINKAGE_PARENTHETICAL),
2854
- `${rel} no longer names all three linkage failures as distinct: a deleted \`.git\` is the one git walks up from, a \`.git\` naming another worktree's admin dir is the one git answers for this worktree while reading the other one's HEAD and index, and a \`core.worktree\` redirect is the one git answers with this worktree's HEAD and index against another directory's files. Merging them, or generalising until it names none, all land here.`);
2855
- }
2856
- });
2857
-
2858
- // --- #1472: the exit-2 cause census.
2859
- //
2860
- // The two pins above read this row for its FIELDS and for one clause of its
2861
- // exit-2 prose. Neither asks the closed-list question — does the row name
2862
- // every cause this script can refuse for, and none it cannot reach? #1108
2863
- // answered that for worktree-audit.sh and reap.sh after two PRs in one fleet run
2864
- // each left a row asserting an enumeration its script had outgrown with the
2865
- // suite green (#1104/#525, #1105/#482). This block answers it here, both
2866
- // directions:
2867
- //
2868
- // TOO NARROW — the script grows a refusal the row does not carry. `CAUSES`
2869
- // binds every `die` site to the phrase that represents it, and the census
2870
- // test asserts that binding is EXACTLY the set of sites the script has. Add
2871
- // a `die` and it reds on an unbound site; delete one and it reds on a
2872
- // binding whose cause the script can no longer produce. The set is derived
2873
- // from the script, so the binding cannot rot silently the way the row did —
2874
- // a reworded message reds too, which is the point: the row is what then has
2875
- // to be revisited.
2876
- //
2877
- // TOO BROAD — the row grows a cause no `die` produces. The census cannot see
2878
- // that; a phrase added to the cell binds to nothing and no assert notices.
2879
- // `EXIT2_ENUMERATION` is the pin that does: the whole closed list, byte for
2880
- // byte, in the `UNKNOWN_LINE`/`ORPHAN_LINE` verbatim-constant discipline
2881
- // this file already uses on the stash lines above.
2882
- //
2883
- // The span pin's cost is deliberate, and it was #1108's ruling: it reds on
2884
- // EVERY edit to the enumeration, a legitimate rewording included. A structural
2885
- // assertion loose enough to survive rewording cannot red on a rewrite that
2886
- // quietly drops a real cause, which is the defect that was measured twice.
2887
- //
2888
- // WHAT THIS SCRIPT'S SHAPE CHANGES, and it is not cosmetic. Its two siblings
2889
- // answer with a 2 or not at all, so their cells OPEN on `exit 2 only` and a
2890
- // prefix slice is its own anchor. Exit 2 is one of THREE outcomes here:
2891
- // the cell opens on the exit-1 refusal — which carries a closed list of its
2892
- // own, the `stash: null` shapes — and closes on the `worktree`/`branch`
2893
- // `null`-field rule, which fires at the verdict's own exit code — 0 or 1 —
2894
- // never exclusively at exit 0.
2895
- // Two consequences, and a copied exit-2-only census gets both wrong.
2896
- //
2897
- // The anchor is asserted, never assumed: `exit 2` occurs exactly once in the
2898
- // cell, and the list is read from there for exactly its own length. A prefix
2899
- // slice would red here on the exit-1 clause it never meant to read, and an
2900
- // `includes` would let a cause be smuggled in ahead of the list.
2901
- //
2902
- // The premise is pinned, not inherited: `exitStatements` asserts that `die`'s
2903
- // `exit 2` and the verdict's `exit "$rc"` are the only exits the script
2904
- // spells, and that `$rc` is only ever 0 or 1. A sibling suite gets "every
2905
- // nonzero exit is a `die`" for free; on this script an `exit 2` spelled
2906
- // outside `die` would be an exit-2 cause with no message to bind, invisible
2907
- // to the census, and a third verdict code would be an outcome no cell in the
2908
- // row describes.
2909
- //
2910
- // Scoped to this script's own suite beside its siblings rather than lifted
2911
- // into one shared table over every row: `.out-of-scope/cli-guard-test-
2912
- // consolidation.md` refuses that consolidation for the CLI-guard pins, and its
2913
- // reason holds unchanged here — a file no single script's suite runs recreates
2914
- // the blind spot these pins exist to close.
2915
-
2916
- /**
2917
- * The `Non-zero when` cell of this script's row, and no more of the row.
2918
- *
2919
- * The row is split on `|` and the fifth cell taken; a stray `|` inside any
2920
- * earlier cell's prose would silently narrow what gets scanned instead of
2921
- * erroring, so the split's own arity is asserted first — measured at 6
2922
- * (leading empty, script name, args, JSON shape, `Non-zero when`, trailing
2923
- * empty).
2924
- */
2925
- const nonZeroCell = () => {
2926
- const cells = specRow().split("|");
2927
- assert.equal(
2928
- cells.length,
2929
- 6,
2930
- "the no-undo-audit.sh row's cell count changed — an earlier cell may have gained a literal `|`",
2931
- );
2932
- return cells[4];
2933
- };
2934
-
2935
- /**
2936
- * The row's exit-2 enumeration, verbatim: from `exit 2` to the end of the
2937
- * sentence that closes the list. The exit-1 refusal ahead of it and the
2938
- * `worktree`/`branch` `null`-field rule behind it — which fires at the
2939
- * verdict's own exit code, 0 or 1, never exclusively at exit 0 — are their
2940
- * own claims with their own pins, so the span stops where the closed list
2941
- * does — the slice is the size of the claim.
2942
- */
2943
- const EXIT2_ENUMERATION =
2944
- "exit 2 the question is unanswerable — bad argument, no such worktree, a worktree git does not answer for (its linkage is broken, and git still answers at rc 0 — for the enclosing repo when the `.git` is gone, from another worktree's HEAD and index when it names that worktree's admin dir, against another directory's files when `core.worktree` moves the working tree there), `BASE_REF` is not spelled `origin/<branch>` or `refs/remotes/<path>` (#1565), `BASE_REF` names the audited branch (#1565), a ref that does not resolve, a probe that could not run — with the stash reflog's path resolution the exception (#570): that one failing reports `unknown` on the payload at the verdict's own exit code rather than withholding the audit, the same rule `worktree`/`branch` follow below — a conflicting path no pathspec can name, `json.sh` missing, unreadable or failed to load, a conflicting-path or at-risk array that could not be escaped (#119) — and no payload is emitted, or the audit itself could not be written (#1472) — that one can fail after the payload has already begun printing, so stdout carries it truncated and unparseable, which that exit code and the named stderr line are what distinguish from a complete answer.";
2945
-
2946
- /**
2947
- * Everything in the cell AFTER `EXIT2_ENUMERATION`, verbatim: the
2948
- * `worktree`/`branch` `null`-field rule the enumeration's own doc comment
2949
- * says is its own claim with its own pin. Without this, the byte-span
2950
- * equality below only ever inspects a fixed-length window starting at
2951
- * `exit 2 ` — a phantom cause appended after the enumeration's closing
2952
- * sentence, worded without repeating the literal string `exit 2`, would
2953
- * sit past that window and pass unseen. Pinning the remainder too closes
2954
- * that gap: together the two constants account for every byte of the cell
2955
- * from the anchor to the end of the row's cell.
2956
- */
2957
- const EXIT2_TAIL =
2958
- " `worktree` and `branch` are the exception (#431): they echo argv rather than reporting a finding, so an escaper that cannot render one reports that field and its `*Rewritten` flag as JSON `null` on the payload the audit already earned, at the verdict's own exit code. A `null` there is \"this run could not render the path or branch you passed in\", never \"there is no worktree\" and never a path ";
2959
-
2960
- /**
2961
- * The clauses the ROW collapses several refusals into, named because the
2962
- * bindings below share them and a phrase typed ten times drifts nine ways.
2963
- *
2964
- * Sharing is the row's editorial call and not a looseness here: a reader who
2965
- * meets any of the ten refusals about a worktree git will not answer for
2966
- * does the same thing about it, and so does one who meets either library
2967
- * refusal. The phrases are the short load-bearing labels; their exact wording
2968
- * is `EXIT2_ENUMERATION`'s job.
2969
- *
2970
- * The two BASE_REF clauses are named for a different reason than sharing:
2971
- * each represents exactly one refusal, and `BASE_REF_CLAUSES` below reads
2972
- * them again to pin that both operator-facing enumerations name them. Spelled
2973
- * inline they would sit in two places with no constant holding them together,
2974
- * which is the drift the rest of this block exists to stop.
2975
- */
2976
- const LIBRARY_CLAUSE = "`json.sh` missing, unreadable or failed to load";
2977
- const LINKAGE_CLAUSE = "a worktree git does not answer for";
2978
- const REF_CLAUSE = "a ref that does not resolve";
2979
- const PROBE_CLAUSE = "a probe that could not run";
2980
- const ESCAPE_CLAUSE = "a conflicting-path or at-risk array that could not be escaped (#119)";
2981
- const BASE_REF_SHAPE_CLAUSE = "`BASE_REF` is not spelled `origin/<branch>` or `refs/remotes/<path>` (#1565)";
2982
- const AUDITED_BRANCH_CLAUSE = "`BASE_REF` names the audited branch (#1565)";
2983
-
2984
- /**
2985
- * Every clause representing a BASE_REF refusal, as a closed list.
2986
- *
2987
- * `plugin/commands/run-merge-bot.md` is the operator-facing doc for this
2988
- * script's only documented invocation, and its exit-2 enumeration is derived
2989
- * from nothing: the census below catches a cause the design-spec ROW goes
2990
- * silent about, and nothing caught one the COMMAND DOC goes silent about —
2991
- * #1565's own accept-list reached the row and not that doc, with the suite
2992
- * green. Asserted closed against the script's own messages, so a third
2993
- * BASE_REF refusal reds here until it is listed and named in both docs.
2994
- */
2995
- const BASE_REF_CLAUSES = [BASE_REF_SHAPE_CLAUSE, AUDITED_BRANCH_CLAUSE];
2996
-
2997
- /**
2998
- * Every `die` site in no-undo-audit.sh, bound to the phrase in the row that
2999
- * represents it.
3000
- *
3001
- * The KEY is the message as the script spells it, interpolations and all.
3002
- * `die` is this script's only exit-2 path — `exitStatements` asserts that of
3003
- * the script rather than assuming it — so the message set IS the exit-2 cause
3004
- * set, and keying on it is what makes this derived rather than a third
3005
- * hand-written copy of the contract sitting beside the script and the row.
3006
- */
3007
- const CAUSES = new Map([
3008
- ["cannot read $json_lib — refusing to act without the JSON escaping helpers", LIBRARY_CLAUSE],
3009
- ["$json_lib failed to load", LIBRARY_CLAUSE],
3010
- ["usage: no-undo-audit.sh <worktree> <branch>", "bad argument"],
3011
- ["worktree $wt does not exist", "no such worktree"],
3012
- ["$wt is not a git worktree", LINKAGE_CLAUSE],
3013
- ["git answers for the repo above $wt, not $wt — cannot tell a clean worktree from a dirty one", LINKAGE_CLAUSE],
3014
- ["git will not name the git dir answering for $wt — cannot verify its linkage", LINKAGE_CLAUSE],
3015
- ["git will not name $wt's common git dir — cannot verify its linkage", LINKAGE_CLAUSE],
3016
- ["$gd/gitdir is missing or unreadable — cannot verify $wt's linkage", LINKAGE_CLAUSE],
3017
- ["$gd/gitdir names a directory that does not resolve — cannot verify $wt's linkage", LINKAGE_CLAUSE],
3018
- ["$wt's .git names another worktree's admin dir — cannot tell a clean worktree from a dirty one", LINKAGE_CLAUSE],
3019
- ["$wt's .git names $gd, whose worktree is $owner, not $wt — cannot tell a clean worktree from a dirty one", LINKAGE_CLAUSE],
3020
- ["git will not name the working tree answering for $wt — cannot verify its linkage", LINKAGE_CLAUSE],
3021
- ["git answers for the working tree at $top, not $wt — cannot tell a clean worktree from a dirty one", LINKAGE_CLAUSE],
3022
- ["BASE_REF must be spelled origin/<branch> or refs/remotes/<path>, got '$base'", BASE_REF_SHAPE_CLAUSE],
3023
- ["BASE_REF must not name the audited branch, got '$base'", AUDITED_BRANCH_CLAUSE],
3024
- ["$base does not resolve as $base_rev", REF_CLAUSE],
3025
- ["$branch_rev does not resolve — run 'git fetch origin' and retry", REF_CLAUSE],
3026
- ["git status failed in $wt — cannot tell a clean worktree from a dirty one", PROBE_CLAUSE],
3027
- ["awk failed counting the stash entries — cannot report the stash count", PROBE_CLAUSE],
3028
- ["cannot create a temporary file", PROBE_CLAUSE],
3029
- ["git merge-tree could not answer (exit $mt_rc) against origin/$branch — cannot determine conflicts", PROBE_CLAUSE],
3030
- ["could not read git merge-tree's output (python3) — cannot determine conflicts", PROBE_CLAUSE],
3031
- ["a conflicting path contains a newline — cannot build a pathspec for it", "a conflicting path no pathspec can name"],
3032
- ["could not escape the conflicting paths for $branch", ESCAPE_CLAUSE],
3033
- ["git merge-base failed for $base ($base_rev) and $branch_rev — cannot tell what a resolution would eat", PROBE_CLAUSE],
3034
- ["listing commits for the conflicting paths failed (git log or xargs) — cannot tell what a resolution would eat", PROBE_CLAUSE],
3035
- ["awk failed deduplicating the at-risk commits — cannot tell what a resolution would eat", PROBE_CLAUSE],
3036
- ["could not escape the at-risk commits for $branch", ESCAPE_CLAUSE],
3037
- ["could not write the audit for $branch", "the audit itself could not be written (#1472)"],
3038
- ]);
3039
-
3040
- /**
3041
- * How many sites a message may have. One, except the `mktemp` refusal, which
3042
- * the script arms before each of the two temporaries it creates and spells
3043
- * identically at both: it is one cause, and an operator does nothing
3044
- * different about the second.
3045
- *
3046
- * The siblings' census asserts instead that every message is unique. That is
3047
- * true of their scripts and is a FALSE REFUSAL here — copied over, it reds on
3048
- * this script for something that is not a defect. Counting keeps what
3049
- * uniqueness was buying: a new `die` reusing an existing message reds on the
3050
- * count rather than binding to a cause that is not its own, and a shared
3051
- * message that stops being shared reds as the missing site it is.
3052
- */
3053
- const SITES_PER_MESSAGE = new Map([["cannot create a temporary file", 2]]);
3054
-
3055
- /**
3056
- * The message of every `die` call in the script, read off the script, one
3057
- * entry per cause.
3058
- *
3059
- * Comment lines are dropped: prose quoting a `die "…"` is not a call site, and
3060
- * minting a cause out of one would red this suite over a comment. Greedy to
3061
- * the last quote on the line, so a message carrying a nested `"$…"`
3062
- * substitution arrives whole rather than truncated at its first inner quote.
3063
- */
3064
- function dieSites() {
3065
- const src = readFileSync(SCRIPT, "utf8");
3066
- // Re-derived for #1684, which replaced the hand-copy of `emit`'s body
3067
- // that stood here with a call to `emit` itself: the `|| :` of #1514 and
3068
- // the `( trap '' PIPE; … )` subshell of #1571 now live in one function
3069
- // body rather than two. The premise this anchor protects — that `die`
3070
- // formats one message and reaches `exit 2` — is unchanged by that fix, as
3071
- // it was by the two before it.
3072
- assert.match(
3073
- src,
3074
- /^die\(\) \{ emit "\$NAME: \$1"; exit 2; \}$/m,
3075
- "the census derives its cause set from one `die` that exits 2 — that definition has changed, so re-derive before trusting this file",
3076
- );
3077
- const lines = src.split("\n");
3078
- const sites = lines
3079
- .filter((l) => !/^\s*#/.test(l))
3080
- .flatMap((l) => [...l.matchAll(/(?:^|[;&|(\s])die "(.*)"/g)].map((m) => m[1]));
3081
- assert.ok(sites.length > 1, `the scan found ${sites.length} die sites, so its spelling has drifted off the script`);
3082
-
3083
- // `die` is defined ABOVE `emit` and, since #1684, CALLS it — and a shell
3084
- // resolves a function name at call time, not at definition time. So every
3085
- // `die` call site has to sit below `emit()`'s definition: one hoisted
3086
- // above it runs `emit` as an unknown command, `set -e` takes that 127,
3087
- // and the script answers an unanswerable question with a status outside
3088
- // its own 0/1/2 contract — on whichever branch reached it and nowhere
3089
- // else, which is why no fixture would find it. The ordering is the whole
3090
- // of what makes the forward reference safe, so it is asserted here rather
3091
- // than left to the paragraph beside the definition.
3092
- const emitDef = lines.findIndex((l) => /^emit\(\) \{/.test(l));
3093
- assert.ok(emitDef >= 0,
3094
- "`emit()` is no longer defined at the start of a line — `die` calls it, so this ordering check no longer knows what it is measuring");
3095
- const firstCall = lines.findIndex((l) => !/^\s*#/.test(l) && /(?:^|[;&|(\s])die "/.test(l));
3096
- assert.ok(firstCall > emitDef,
3097
- `the first \`die\` call sits at line ${firstCall + 1}, above \`emit\`'s definition at line ${emitDef + 1} — it would exit 127, not the 2 this script's contract promises`);
3098
- for (const message of new Set(sites)) {
3099
- assert.equal(
3100
- sites.filter((m) => m === message).length,
3101
- SITES_PER_MESSAGE.get(message) ?? 1,
3102
- `\`die "${message}"\` is spelled at a number of sites this census does not expect: two causes sharing a message cannot be bound apart, and a message that stops being shared is a site that went missing`,
3103
- );
3104
- }
3105
- return new Set(sites);
3106
- }
3107
-
3108
- /**
3109
- * Every `exit` statement the script spells, as it spells it.
3110
- *
3111
- * Read from anywhere on the line, not just statement position: `&& exit 2` is
3112
- * an exit path as much as a bare one, and a scan anchored on line start or
3113
- * `; ` misses it — measured, and measured green against a stray `exit 2` this
3114
- * census exists to red on.
3115
- *
3116
- * Quoted spans are cut out first, which is what keeps the word inside a
3117
- * MESSAGE from being minted into an exit path: `die "git merge-tree could not
3118
- * answer (exit $mt_rc) …"` carries one, and so does the render fold's "the
3119
- * payload and the exit status stand". Comment lines are dropped for the reason
3120
- * `dieSites` drops them.
3121
- */
3122
- function exitStatements(src) {
3123
- return src
3124
- .split("\n")
3125
- .filter((l) => !/^\s*#/.test(l))
3126
- .flatMap((l) => {
3127
- const quoted = [...l.matchAll(/'[^']*'|"[^"]*"/g)].map((m) => [m.index, m.index + m[0].length]);
3128
- return [...l.matchAll(/\bexit\b *([^;)&|]*)/g)]
3129
- .filter((m) => !quoted.some(([from, to]) => m.index >= from && m.index < to))
3130
- .map((m) => `exit ${m[1].trim()}`.trim());
3131
- });
3132
- }
3133
-
3134
- /**
3135
- * Every `rc=<value>` assignment to the verdict variable, scanned the same
3136
- * way `exitStatements` scans `exit`: from anywhere on the line rather than
3137
- * anchored to its start, with quoted spans cut out first and comment lines
3138
- * dropped. A line-start/line-end anchor would miss a value assigned inline
3139
- * (`… && rc=2`) or trailed by a comment (`rc=2 # oops`) — exactly the two
3140
- * shapes `exitStatements` was already built to survive. `\brc=` — not a bare
3141
- * `rc=` — is what keeps `sl_rc=`, `sr_rc=`, `mt_rc=` and `stash_reflog_rc=`
3142
- * out: an underscore is a word character, so there is no boundary between it
3143
- * and the `r` those names share with the verdict variable.
3144
- */
3145
- function rcAssignments(src) {
3146
- return src
3147
- .split("\n")
3148
- .filter((l) => !/^\s*#/.test(l))
3149
- .flatMap((l) => {
3150
- const quoted = [...l.matchAll(/'[^']*'|"[^"]*"/g)].map((m) => [m.index, m.index + m[0].length]);
3151
- return [...l.matchAll(/\brc=(\S+)/g)]
3152
- .filter((m) => !quoted.some(([from, to]) => m.index >= from && m.index < to))
3153
- .map((m) => m[1]);
3154
- });
3155
- }
3156
-
3157
- test("`die` is the only way this script reaches exit 2, and its other exits are the two verdicts (#1472)", () => {
3158
- const src = readFileSync(SCRIPT, "utf8");
3159
-
3160
- assert.deepEqual(
3161
- exitStatements(src).sort(),
3162
- ['exit "$rc"', "exit 2"],
3163
- "the census reads the exit-2 causes off `die`'s messages, so every exit-2 path must BE a `die`: an `exit 2` spelled anywhere else is a cause with no message to bind, and the row could stay silent about it with this suite green",
3164
- );
3165
-
3166
- assert.deepEqual(
3167
- [...new Set(rcAssignments(src))].sort(),
3168
- ["0", "1"],
3169
- "`$rc` is the verdict, and the row states exactly two of them — 1 the worktree is dirty, 0 it is clean. A third value assigned here is an outcome no cell in that row describes",
3170
- );
3171
-
3172
- // `set -eu` is on, so an unguarded command failing exits with ITS status
3173
- // rather than with any of the three — a 1 out of a failed `.` or `printf`
3174
- // reads as the dirty-worktree refusal, which is what the guards above are
3175
- // for and what their own fixtures pin. This test is about the exits the
3176
- // script spells itself.
3177
- });
3178
-
3179
- test("the design spec's row represents every exit-2 cause this script can reach, and none it cannot (#1472)", () => {
3180
- // Both directions in one equality: an unbound site is a cause the row may be
3181
- // silent about, and a binding with no site is a cause the row claims while
3182
- // the script can no longer produce it.
3183
- assert.deepEqual([...dieSites()].sort(), [...CAUSES.keys()].sort());
3184
-
3185
- const cell = nonZeroCell();
3186
- for (const phrase of new Set(CAUSES.values())) {
3187
- assert.equal(
3188
- cell.split(phrase).length - 1,
3189
- 1,
3190
- `the \`Non-zero when\` cell must carry "${phrase}" exactly once.\ncell: ${cell}`,
3191
- );
3192
- }
3193
- });
3194
-
3195
- test("the design spec's row states this script's exit-2 causes as a closed list, byte for byte (#1472)", () => {
3196
- const cell = nonZeroCell();
3197
-
3198
- // The anchor, asserted rather than assumed: this cell does not open on the
3199
- // exit-2 list the way its siblings' cells do, so the span below is read from
3200
- // the one place the cell names exit 2 — and that there is exactly one such
3201
- // place is half the claim. A second one is a second enumeration, which is
3202
- // the row carrying its own contradiction.
3203
- assert.equal(
3204
- cell.split("exit 2 ").length - 1,
3205
- 1,
3206
- `the cell must name exit 2 exactly once — it is the anchor the closed list is read from.\ncell: ${cell}`,
3207
- );
3208
-
3209
- // A slice, not an `includes`: a cause smuggled in anywhere inside the list
3210
- // sits outside an exact span of the list's own length. The check runs to
3211
- // the END of the cell, not just the enumeration's own length: a phantom
3212
- // cause appended after the enumeration's closing sentence would otherwise
3213
- // sit past a fixed-length window and pass unseen, provided it avoided the
3214
- // literal string `exit 2` (which the anchor assertion above would still
3215
- // catch) — `EXIT2_TAIL` is what closes that gap for a phantom cause that
3216
- // doesn't repeat it.
3217
- const from = cell.indexOf("exit 2 ");
3218
- assert.equal(cell.slice(from, from + EXIT2_ENUMERATION.length), EXIT2_ENUMERATION);
3219
- assert.equal(cell.slice(from + EXIT2_ENUMERATION.length), EXIT2_TAIL);
3220
- });
3221
-
3222
- test("both operator-facing docs name every BASE_REF refusal this script can reach (#1565)", () => {
3223
- // The closed list, asserted against the script rather than trusted. Both
3224
- // directions: a BASE_REF `die` bound outside the list is a refusal the docs
3225
- // may be silent about, and a clause with no `die` behind it is one the docs
3226
- // claim while the script cannot reach it.
3227
- for (const [message, clause] of CAUSES) {
3228
- if (!message.includes("BASE_REF")) continue;
3229
- assert.ok(
3230
- BASE_REF_CLAUSES.includes(clause),
3231
- `\`die "${message}"\` is a BASE_REF refusal bound to "${clause}", which BASE_REF_CLAUSES does not carry — add it there and name it in both docs, or the command doc can stay silent about it with this suite green`,
3232
- );
3233
- }
3234
- assert.equal(
3235
- [...CAUSES.keys()].filter((m) => m.includes("BASE_REF")).length,
3236
- BASE_REF_CLAUSES.length,
3237
- "every clause in BASE_REF_CLAUSES must have a `die` behind it",
3238
- );
3239
-
3240
- for (const rel of ["../commands/run-merge-bot.md", "../../docs/specs/2026-07-23-fleet-plugin-design.md"]) {
3241
- const anchor = rel.endsWith("run-merge-bot.md")
3242
- ? (l) => l.includes("Exit **2**")
3243
- : (l) => l.startsWith("| `no-undo-audit.sh` |");
3244
- const line = readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8")
3245
- .split("\n").find(anchor);
3246
- assert.ok(line, `${rel} must still describe this script's exit-2 causes`);
3247
- for (const clause of BASE_REF_CLAUSES) {
3248
- assert.equal(
3249
- line.split(clause).length - 1,
3250
- 1,
3251
- `${rel} must name "${clause}" exactly once.\nline: ${line}`,
3252
- );
3253
- }
3254
- }
3255
- });
3256
-
3257
- // --- #119: the escaping library this script now sources rather than carries.
3258
- //
3259
- // `.` is a POSIX special builtin, so failing to open its operand aborts a
3260
- // non-interactive shell before any `||` on the line can run — measured, /bin/sh
3261
- // (macOS bash 3.2), bash 3.2 and `bash --posix` all exit 1 with the guard
3262
- // unfired. Exit 1 is a VERDICT here — `REFUSED — commit the worktree before
3263
- // rebasing`, and "refused" means a dirty worktree this script actually looked
3264
- // at — so a bare 1 out of a missing file would report that refusal without
3265
- // having measured anything. The `[ -r ]` ahead of the `.` is what makes it a 2.
3266
- test("a missing json.sh is exit 2, not a verdict about the worktree", (t) => {
3267
- const c = repo(t);
3268
- const lone = mkdtempSync(join(tmpdir(), "no-undo-audit-nolib-"));
3269
- t.after(() => rmSync(lone, { recursive: true, force: true }));
3270
- copyFileSync(SCRIPT, join(lone, "no-undo-audit.sh"));
3271
-
3272
- const r = spawnSync("sh", [join(lone, "no-undo-audit.sh"), c.w, c.branch], {
3273
- cwd: c.w, env: ENV, encoding: "utf8",
3274
- });
3275
-
3276
- assert.equal(r.status, 2,
3277
- "a missing library is `the question could not be answered`. Exit 0 would call an unexamined worktree safe to rebase, which is the false safe this whole script exists to prevent.");
3278
- assert.match(r.stderr, /json\.sh/,
3279
- "and it names the file — this script has many exit-2 paths and the operator should not have to guess which fired");
3280
- assert.equal(r.stdout, "", "no payload: nothing was measured");
3281
- });
3282
-
3283
- // --- #119, second half: what happens when the library is THERE and its tools
3284
- // are not. `jarr`/`jarr_rewritten` return non-zero on a failed stage now, which
3285
- // is the whole point of the extraction — and under `set -eu` a bare
3286
- // `var=$(… | jarr)` would then abort with the failing tool's own status. On
3287
- // this script that status is 1, byte-identical to the dirty-worktree refusal,
3288
- // on a worktree the run had already logged as clean, with no payload and no
3289
- // diagnostic. These three pin the `|| die` that converts it to a 2.
3290
- //
3291
- // One shim shape, selected on CONTENT rather than on argv, because the two jarr
3292
- // call sites are invoked with identical arguments and only the values passing
3293
- // through them differ. `sed` fails jarr; `tr -d` fails jrewritten and therefore
3294
- // jarr_rewritten, which is the other operand of each `&&` chain.
3295
- //
3296
- // `selector` overrides that default arg match, which is what #431's cases need:
3297
- // `jstr` ends in a `tr` carrying no `-d`, so the two defaults above cannot
3298
- // address it. Passing json.sh's shared scrub set matches BOTH the replacing
3299
- // `tr` that closes `jstr` and the deleting one inside `jrewritten` — which is
3300
- // not ambiguity to route around, because the caller consults `jstr` first and
3301
- // therefore always reports `jstr` as the escaper that failed.
3302
- function withBrokenEscaper(t, { tool, marker, selector }) {
3303
- const bin = mkdtempSync(join(tmpdir(), "no-undo-audit-esc-"));
3304
- t.after(() => rmSync(bin, { recursive: true, force: true }));
3305
- const real = execFileSync("sh", ["-c", `command -v ${tool}`], { encoding: "utf8" }).trim();
3306
- // The selector arg is what keeps this off the script's OWN sed/tr calls:
3307
- // `s/^/"/` appears only in jarr's rule list and `-d` only in jrewritten's.
3308
- selector = selector ?? (tool === "sed" ? `'s/^/"/'` : "-d");
3309
- writeExecStub(join(bin, tool), `#!/bin/sh
3310
- case " $* " in
3311
- *${selector}*)
3312
- in=$(cat)
3313
- case "$in" in *'${marker}'*) exit 1 ;; esac
3314
- printf '%s\\n' "$in" | exec ${real} "$@" ;;
3315
- esac
3316
- exec ${real} "$@"
3317
- `);
3318
- return `${bin}:${process.env.PATH}`;
3319
- }
3320
-
3321
- // --- #896: the two `|| die`s the three cases below exist for, and the
3322
- // fatality all three read off the exit CODE — which is the shell's choice and
3323
- // not this script's.
3324
- //
3325
- // Downgrade either guard to a message-preserving warning and the two `sed`
3326
- // cases emit no payload at all to catch it by. Each pair — `conflicts_json`
3327
- // with `conflicts_rewritten_json`, `at_risk_json` with
3328
- // `at_risk_rewritten_json` — is assigned by one `&&` chain, so the failing
3329
- // `jarr` short-circuits the second and leaves that name unset; with the guard
3330
- // advisory the payload `printf` reads it and `set -u` aborts instead. Measured
3331
- // on this box: bash exits 0, not 1 — `no-undo-audit.sh:538`'s `trap 'rm -f
3332
- // "$mt_out" "$ps_out"' EXIT`, armed before either guard, resets the abort
3333
- // status on its way out, so `<name>: unbound variable` still reaches stderr
3334
- // but the caller gets back the same 0 a genuinely healthy run reports — a
3335
- // false SAFE, and worse than the exit 1 this comment used to claim. dash is
3336
- // unaffected by the trap and still exits 2 saying `<name>: parameter not
3337
- // set` — the very status a firing guard returns, under the same message the
3338
- // downgrade still prints. This file spawns a bare `sh` and
3339
- // `.github/workflows/ci.yml`'s `check` job
3340
- // runs on `ubuntu-latest`, where that name is dash. Measured with the at-risk
3341
- // guard downgraded: every case in this file stayed green under dash and the
3342
- // guard was pinned on a Mac alone.
3343
- //
3344
- // The unset NAME is common to both shells and is printed by neither a healthy
3345
- // run nor a firing guard, so that is what discriminates. The `tr` case needs
3346
- // no such assertion and is given none: `jarr` succeeds there and
3347
- // `jarr_rewritten`'s capture is still ASSIGNED, empty, so nothing is unset.
3348
- // Downgraded, that run exits 0 with a payload that PARSES — one conflicting
3349
- // path beside `"conflictsRewritten":[]`, a flag list silently emptied
3350
- // (measured, both shells) — which its status and stdout assertions already
3351
- // refuse.
3352
-
3353
- test("a jarr that cannot escape the conflicts is exit 2 with a cause, never the refusal that means dirty", (t) => {
3354
- const c = bareConflictRepo(t, "boom-conflict.txt");
3355
- const r = audit(c, { ...ENV, PATH: withBrokenEscaper(t, { tool: "sed", marker: "boom-conflict" }) });
3356
-
3357
- assert.equal(r.status, 2,
3358
- "the worktree is clean and was measured clean — exit 1 here would report it dirty on the strength of a broken sed");
3359
- assert.match(r.stderr, /could not escape the conflicting paths/,
3360
- "and it names which stage failed rather than exiting silently");
3361
- assert.equal(r.stdout, "", "no payload: an unescaped conflicts list is not an answer");
3362
- assert.doesNotMatch(r.stderr, /conflicts_rewritten_json/,
3363
- "the guard must stop the script, not warn and leave the payload `printf` reading a name the `&&` chain never assigned. The NAME, because bash's wording and status and dash's differ and only the name is common to both.");
3364
- });
3365
-
3366
- test("a jarr that cannot escape the at-risk commits is exit 2 with its own cause", (t) => {
3367
- const c = bareConflictRepo(t, "plain.txt");
3368
- git(c.w, "checkout", "-q", "main");
3369
- writeFileSync(join(c.w, "plain.txt"), "later main side\n");
3370
- git(c.w, "add", "--", ":(literal)plain.txt");
3371
- git(c.w, "commit", "-q", "-m", "BOOMATRISK subject");
3372
- git(c.w, "push", "-q", "origin", "main");
3373
- git(c.w, "checkout", "-q", c.branch);
3374
-
3375
- const r = audit(c, { ...ENV, PATH: withBrokenEscaper(t, { tool: "sed", marker: "BOOMATRISK" }) });
3376
-
3377
- // A distinct message, not the conflicts one: the two guards are separate
3378
- // statements and a single shared message could not tell the operator which
3379
- // array the run lost.
3380
- assert.equal(r.status, 2, "an at-risk list that could not be rendered is unanswerable, not a dirty worktree");
3381
- assert.match(r.stderr, /could not escape the at-risk commits/,
3382
- "and the cause names the at-risk list, not the conflicts one");
3383
- assert.equal(r.stdout, "", "no payload: a run that cannot say what a resolution would eat has not answered");
3384
- assert.doesNotMatch(r.stderr, /at_risk_rewritten_json/,
3385
- "and the guard is fatal, not advisory — the NAME again, for the reason the conflicts case states: the status a downgrade produces here is 2 under the shell CI runs.");
3386
- });
3387
-
3388
- test("a jarr_rewritten that cannot answer is exit 2 too — the `&&` chain covers both operands", (t) => {
3389
- const c = bareConflictRepo(t, "boom-conflict.txt");
3390
- const r = audit(c, { ...ENV, PATH: withBrokenEscaper(t, { tool: "tr", marker: "boom-conflict" }) });
3391
-
3392
- assert.equal(r.status, 2,
3393
- "`conflictsRewritten` is what tells the runbook a path is not safe to hand to `git diff` — a run that cannot compute it has not answered");
3394
- assert.match(r.stderr, /could not escape the conflicting paths/);
3395
- assert.equal(r.stdout, "", "no payload: half the pair is not a receipt");
3396
- });
3397
-
3398
- test("a shimmed escaper that works answers the audit in full — the guards refuse only a real outage", (t) => {
3399
- // The false-positive half, and the control the three cases above need:
3400
- // shadowing `sed` on PATH is not by itself fatal to this script. The same
3401
- // fixture and the same shadowed name as the first of them, a marker nothing
3402
- // in this run carries — so those exit 2s are the escaper failing, not the
3403
- // shim's mere presence. Without this they could be measuring a PATH they
3404
- // broke wholesale and still read green. The `tr` shim has its counterpart in
3405
- // the #431 cases below, which install that shape and get a payload back.
3406
- const c = bareConflictRepo(t, "boom-conflict.txt");
3407
- const r = audit(c, { ...ENV, PATH: withBrokenEscaper(t, { tool: "sed", marker: "no value in this run carries this" }) });
3408
-
3409
- assert.equal(r.status, 0, "the worktree is clean and every stage rendered — a shim on PATH is not itself a refusal");
3410
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
3411
- assert.deepEqual(r.json.conflicts, ["boom-conflict.txt"], "the array the first case could not render, rendered");
3412
- assert.deepEqual(r.json.conflictsRewritten, [false]);
3413
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"], "and the at-risk array the second one could not");
3414
- });
3415
-
3416
- // --- #1160: the OTHER direction from the three cases above, on the same shim.
3417
- // Those escape `conflicts[]` and `atRisk[]` into the payload and must reach
3418
- // exit 2 when they cannot. These two only RENDER already-computed values to
3419
- // stderr for a human, so they decide nothing and must reach no exit at all.
3420
- // Written bare — `printf … | sed 's/^/ conflict: /' >&2` — the pipeline's
3421
- // status was sed's and `set -eu` took it, so a render exited the audit at 1,
3422
- // the dirty-worktree refusal, on a worktree the same run had already printed
3423
- // `clean` for, with no payload and no `no-undo-audit:` line naming a cause.
3424
- //
3425
- // A shim rather than the locale, and that is what makes these the half CI can
3426
- // run. The invalid-UTF-8 case above reaches the same renders through the pin,
3427
- // but only on BSD sed: under a GNU toolchain the byte passes straight through
3428
- // and no render ever fails, and `ci.yml`'s `check` job runs ubuntu-latest.
3429
- //
3430
- // `selector` is the renders' shared `s/^/` prefix, so one shim reaches the
3431
- // `conflict: ` and `at risk: ` renders and the porcelain one, and reaches
3432
- // json.sh's escapers not at all — their only `s/^/` rule is `s/^/"/` (#119's
3433
- // cases above select on exactly that). `marker: ""` switches the helper's
3434
- // content gate off: it exists because the two jarr call sites share one argv,
3435
- // and these three do not, so argv alone addresses them.
3436
- const withFailingRenders = (t) =>
3437
- withBrokenEscaper(t, { tool: "sed", marker: "", selector: `'s/^/ '` });
3438
-
3439
- test("a render that cannot reach stderr leaves the verdict it decides nothing about intact (#1160)", (t) => {
3440
- const c = bareConflictRepo(t, "boom-conflict.txt");
3441
- const r = audit(c, { ...ENV, PATH: withFailingRenders(t) });
3442
-
3443
- // The fault injection first: without it every assertion below measures an
3444
- // unmutated run and passes on a script with the guards deleted.
3445
- assert.doesNotMatch(r.stderr, /^ {4}conflict: /m,
3446
- "the fault injection never fired — the conflict list still rendered, so nothing here is measuring a failed render");
3447
- assert.doesNotMatch(r.stderr, /^ {4}at risk: /m,
3448
- "nor did it reach the at-risk render, which is a separate call site and was a separate bare pipeline");
3449
-
3450
- assert.equal(r.status, 0,
3451
- `the worktree is clean and was measured clean — exit 1 here is the render deciding the verdict; got ${r.status} ${r.stderr}`);
3452
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
3453
- assert.deepEqual(r.json.conflicts, ["boom-conflict.txt"],
3454
- "the payload is computed before either render and must survive both of them failing");
3455
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"],
3456
- "and the run continues past the first failed render rather than stopping at it — the at-risk step is downstream of it");
3457
-
3458
- // Not `|| :`: a dropped conflict list reads exactly like an empty one, which
3459
- // is the same silent-failure class as the abort. Each render names itself,
3460
- // because a single shared message could not tell the operator which went
3461
- // missing.
3462
- assert.match(r.stderr, /^no-undo-audit: could not render the conflicting-path list to stderr/m,
3463
- "a lost diagnostic must say so, and say which one");
3464
- assert.match(r.stderr, /^no-undo-audit: could not render the at-risk commit list to stderr/m,
3465
- "and the at-risk render must name itself rather than share the line above");
3466
- });
3467
-
3468
- test("a porcelain render that cannot reach stderr still refuses WITH its payload (#1160)", (t) => {
3469
- // The dirty half, and the one the case above cannot cover: here exit 1 is
3470
- // the correct answer, so the status cannot discriminate and the PAYLOAD is
3471
- // what does. This render runs before the payload is written, so unguarded
3472
- // its abort took the whole answer with it — a refusal with nothing on stdout
3473
- // to say what was measured, indistinguishable from the exit 1 a failing
3474
- // render fabricates on a clean tree.
3475
- const c = repo(t);
3476
- writeFileSync(join(c.w, "uncommitted.txt"), "work that exists nowhere else\n");
3477
-
3478
- const r = audit(c, { ...ENV, PATH: withFailingRenders(t) });
3479
-
3480
- assert.doesNotMatch(r.stderr, /^ {4}\?\? uncommitted\.txt$/m,
3481
- "the fault injection never fired — the porcelain dump still rendered");
3482
- assert.equal(r.status, 1,
3483
- `a dirty worktree refuses on its own account, at the status it always did; got ${r.status} ${r.stderr}`);
3484
- assert.equal(r.jsonError, null, `the refusal must still carry its payload; got ${r.jsonError?.message}\n${r.stdout}`);
3485
- assert.equal(r.json.clean, false, "and the payload must say what was measured, not merely that something failed");
3486
- assert.match(r.stderr, /REFUSED — commit the worktree before rebasing/,
3487
- "the refusal the caller acts on is the audit's own sentence, which sits past the failed render");
3488
- assert.match(r.stderr, /^no-undo-audit: could not render the uncommitted-work list to stderr/m,
3489
- "and the dump the operator would have read is reported missing rather than dropped");
3490
- });
3491
-
3492
- // render()'s trailing `|| :` is what stands between an aborted audit and a
3493
- // caller whose stderr is completely gone — both the primary write AND its own
3494
- // one-line fallback disclaimer fail, so the guard's third piece is the only
3495
- // one left to catch it. The two cases above reach that state through a `sed`
3496
- // shim on PATH; this one reaches it the way a real caller does, by closing
3497
- // fd 2 on the whole process.
3498
- //
3499
- // That end-to-end shape was unreachable until #1514, and this test used to
3500
- // extract `render()` by name and run it standalone for exactly that reason:
3501
- // every OTHER bare `>&2` write in the script was unguarded too, so a closed
3502
- // fd 2 aborted the run on the first of them — the status-command header,
3503
- // before git had been asked anything — and #1160's guard was dead code to
3504
- // any test that closed fd 2 for real. The standalone extraction went with
3505
- // the gap it existed to work around: this run drives the same three-piece
3506
- // guard through the same function, twice, inside the script that owns it.
3507
- //
3508
- // The PAYLOAD is the proof it got there, and it has to be, because a run
3509
- // with no stderr has no other way to report. `conflicts[]` and `atRisk[]`
3510
- // are rendered by two separate `render()` calls and then carried to stdout,
3511
- // so a non-empty pair says both renders failed, neither decided anything,
3512
- // and the run continued past each — an exit 0 alone would also be produced
3513
- // by a script that bailed out early with an empty payload.
3514
- //
3515
- // Neither of the stronger signals finding 2 raised fits this script without
3516
- // breaking an invariant already established and tested elsewhere: `exec`-ing
3517
- // a marker to fd 1 would inject a second value into the one-JSON-object
3518
- // stdout contract every payload test parses strictly (`jq -e "."` above), and
3519
- // a distinguishable exit code would hand a render exactly the
3520
- // verdict-deciding power #1160 exists to take away — this file's own header
3521
- // says a render "answers nothing and so must reach no exit at all". Pinning
3522
- // the accepted tradeoff (the JSON payload already carries what every render
3523
- // only duplicates onto stderr) rather than changing it.
3524
- test("a closed fd 2 reaches both renders and leaves the verdict intact (#1160, #1514)", (t) => {
3525
- const c = bareConflictRepo(t, "boom-conflict.txt");
3526
-
3527
- const r = spawnSync("sh", ["-c", '"$0" "$@" 2>&-', SCRIPT, c.w, c.branch], {
3528
- cwd: c.w,
3529
- env: ENV,
3530
- encoding: "utf8",
3531
- });
3532
-
3533
- assert.equal(r.status, 0,
3534
- `the worktree is clean and was measured clean — 1 is a render deciding the verdict and 2 is a question this run could answer; got ${r.status}`);
3535
- const json = JSON.parse(r.stdout);
3536
- assert.deepEqual(json.conflicts, ["boom-conflict.txt"],
3537
- "the conflicting-path render sits between the status header and this field — an empty list means the run never got past it");
3538
- assert.deepEqual(json.atRisk.map((l) => l.replace(/^\S+ /, "")), ["MAIN COMMIT AT RISK"],
3539
- "and the at-risk render is downstream of the first, so this is what says the run continued past a second failed one");
3540
- });
3541
-
3542
- // The sweep, and the only thing that keeps it swept. Every test above walks
3543
- // ONE path: a clean tree, a dirty tree, a conflicted tree, a non-worktree.
3544
- // The stash chain alone has four branches, `die` has thirty-odd call sites,
3545
- // and no realistic fixture set visits all of them — so a future write that
3546
- // bypasses `die`/`render`/`emit` and reaches fd 2 bare on a branch nothing
3547
- // exercises reintroduces the whole bug silently, and no fixture would catch
3548
- // it either.
3549
- //
3550
- // Only `render()`'s write carried failure protection before this PR (#1514).
3551
- // #1160 guarded the FOLD that assembles the stash-diagnostic line against a
3552
- // corrupting `tr`/`sed` exit status — a different hazard — and left every
3553
- // stderr WRITE, `die`'s included, free to abort the run on a closed fd 2.
3554
- // #1514 (this PR) is what guards those, and centralizes them behind `die`,
3555
- // `render`, and the new `emit` so there is one function body to check per
3556
- // guard, not a dozen call sites to keep in sync. #1684 went one further and
3557
- // folded `die`'s own copy of that body into a call to `emit`, so the census
3558
- // below counts two direct writers where it once counted three — `die` still
3559
- // reaches fd 2, but no longer by a statement of its own. #1685 folded
3560
- // `render`'s own copy the same way; the count stayed at two because
3561
- // `render`'s pipeline write and its fallback already shared one segment
3562
- // (see the comment on the count assertion below), so the fold removed a
3563
- // duplicated guard, not a writer the census was counting separately.
3564
- //
3565
- // The rule is structural, so it is asserted structurally rather than
3566
- // sampled: a diagnostic decides nothing, so every statement that writes to
3567
- // fd 2 must end its `||` chain in the no-op, either directly (`|| :`) or by
3568
- // calling a function whose own chain does (`|| emit …`, verified on
3569
- // `emit`'s own segment in the same pass). `render()`'s body spans two lines
3570
- // and ends in a call to `emit` on the second, so continuations are joined
3571
- // before the check; `emit()`'s carries more (`; }`) after ITS OWN guard, on
3572
- // the SAME joined line, separated by `;` rather than `||` — so a line is
3573
- // split on top-level `;` first and each resulting statement's own tail is
3574
- // checked, not just the line's last `>&2`. Quote-aware: a `;`
3575
- // inside a quoted argument (render's fallback message, now `emit`'s own
3576
- // argument, carries one) is not a statement separator. Unaware of that, a
3577
- // line carrying two independent `>&2`-writing statements —
3578
- // `echo "a" >&2; echo "b" >&2 || :` — would report the whole line compliant
3579
- // off the LAST write's guard alone, leaving the first invisible.
3580
- //
3581
- // Paren-aware too, since #1571: `emit()`'s one write still runs inside
3582
- // `( trap '' PIPE; write )`, so the `;` between the trap and the write sits
3583
- // INSIDE that subshell rather than between top-level statements. Splitting
3584
- // on every unquoted `;` regardless of nesting would cut that one segment
3585
- // into two, over-counting below and — worse — leaving one half of the pair
3586
- // to be graded for a guard that was never its own to carry. Depth only
3587
- // needs `(`/`)`, never `{`/`}`: no write in this script sits inside a brace
3588
- // group that isn't also the enclosing function body, which
3589
- // `splitTopLevelStatements` is never handed. The guard check's own tail
3590
- // regex still tolerates one optional `)` immediately after the write's
3591
- // `>&2` for the same reason — `emit`'s subshell close sits between its
3592
- // write and the `|| :` that guards it. `render`'s fallback carries no
3593
- // subshell of its own to tolerate anymore, only a call to the function
3594
- // that does; the tolerance stays because `emit`'s segment still needs it,
3595
- // not because `render`'s does.
3596
- function splitTopLevelStatements(line) {
3597
- const segments = [];
3598
- let cur = "";
3599
- let quote = null;
3600
- let depth = 0;
3601
- for (let i = 0; i < line.length; i += 1) {
3602
- const ch = line[i];
3603
- if (quote) {
3604
- cur += ch;
3605
- if (ch === "\\" && quote === '"' && i + 1 < line.length) {
3606
- i += 1;
3607
- cur += line[i];
3608
- } else if (ch === quote) {
3609
- quote = null;
3610
- }
3611
- continue;
3612
- }
3613
- if (ch === "'" || ch === '"') {
3614
- quote = ch;
3615
- cur += ch;
3616
- } else if (ch === "(") {
3617
- depth += 1;
3618
- cur += ch;
3619
- } else if (ch === ")") {
3620
- depth = Math.max(0, depth - 1);
3621
- cur += ch;
3622
- } else if (ch === ";" && depth === 0) {
3623
- segments.push(cur);
3624
- cur = "";
3625
- } else {
3626
- cur += ch;
3627
- }
3628
- }
3629
- segments.push(cur);
3630
- return segments;
3631
- }
3632
-
3633
- // A `case pat)` arm's close paren has no opening `(` to match, so an
3634
- // unclamped counter would carry depth negative for the rest of the line —
3635
- // every `;` after it stops looking top-level, and the census below would
3636
- // stop seeing statements it must see. Clamping at zero is what keeps a
3637
- // `case` arm from swallowing its neighbors.
3638
- test("an unmatched `)` from a case arm does not swallow the statements after it", () => {
3639
- assert.deepEqual(
3640
- splitTopLevelStatements("case x in x) a; b; esac; c"),
3641
- ["case x in x) a", " b", " esac", " c"],
3642
- );
3643
- });
3644
- // Shared by the fd-2 write census below and its self-referential-emit
3645
- // regression test: extracting this keeps both walking the exact same
3646
- // filters instead of two copies drifting apart.
3647
- function censusStderrWrites(lines) {
3648
- const writes = lines
3649
- .filter((l) => !/^\s*#/.test(l))
3650
- .flatMap(splitTopLevelStatements)
3651
- .filter((s) => s.includes(">&2"));
3652
-
3653
- // A `|| emit` tail only reads as guarded because `emit`'s OWN segment is
3654
- // checked separately, in this same pass — delegating to it is how a
3655
- // write that can't speak for itself borrows a guard that already lives
3656
- // elsewhere. `emit()`'s own definition can't borrow from itself that
3657
- // way: a `|| emit "lost"` fallback on emit's own write recurses into the
3658
- // same failing write instead of reaching a segment this pass has
3659
- // already cleared, and hangs rather than terminating (measured: exit
3660
- // 124, no termination). `delegates` is the exemption both filters below
3661
- // share, with that one carve-out.
3662
- const delegates = (s) =>
3663
- /^\s*\)?\s*\|\|\s*emit\b/.test(s.slice(s.lastIndexOf(">&2") + 3)) &&
3664
- !/^\s*emit\(\)/.test(s.trim());
3665
-
3666
- const unguarded = writes.filter(
3667
- (s) => !/^\s*\)?\s*\|\|\s*:(\s|;|$)/.test(s.slice(s.lastIndexOf(">&2") + 3)) && !delegates(s),
3668
- );
3669
- const untrapped = writes.filter(
3670
- (s) => !/\(\s*trap\s+''\s+PIPE\s*;/.test(s) && !delegates(s),
3671
- );
3672
- return { writes, unguarded, untrapped };
3673
- }
3674
-
3675
-
3676
- test("no stderr write in the script can abort the run under errexit (#1514)", () => {
3677
- const joined = readFileSync(SCRIPT, "utf8").replace(/\\\n\s*/g, " ").split("\n");
3678
- const { writes, unguarded, untrapped } = censusStderrWrites(joined);
3679
-
3680
- // Without this the filter could silently match nothing — a regex typo, a
3681
- // rename — and the assertion below would pass on an empty list, which is
3682
- // the shape a false green takes here. The count is exact, not a floor:
3683
- // `render` and `emit` are the only two places in the script allowed to
3684
- // touch fd 2 directly, so it can only ever be 2 — any other number means
3685
- // a bare write appeared outside both of them, or one vanished. It was 3
3686
- // until #1684 folded `die`'s own copy of `emit`'s body into a call: the
3687
- // segment that held `die`'s `>&2` is gone, and `render`'s and `emit`'s
3688
- // are what the filter still returns. #1685 folded `render`'s own copy the
3689
- // same way and left the count where #1684 put it, for a different reason
3690
- // than `die`'s drop: `render`'s two writes (the `sed` pipeline and its
3691
- // fallback) always shared ONE segment, so routing the fallback through a
3692
- // call to `emit` removed a duplicated guard, not a segment — the filter
3693
- // still sees one `>&2` per site, same as before either fix. Measured
3694
- // against the tree, not decremented on paper: arithmetic on the old count
3695
- // is not a safe way to arrive at the new one.
3696
- assert.equal(writes.length, 2,
3697
- `render and emit are the only statements that may write to fd 2 directly; found ${writes.length}`);
3698
-
3699
- assert.deepEqual(unguarded.map((s) => s.trim()), [],
3700
- "each of these ends the script on its own write status under `set -e`, and 1 out of this script is REFUSED — append `|| :` or route the fallback through `emit`, which already does");
3701
-
3702
- // #1700 made `emit()`'s `( trap '' PIPE; … )` wrapper the ONLY SIGPIPE
3703
- // guard for all 29 `die` call sites — `die` now calls `emit` instead of
3704
- // carrying its own copy. #1685 moved `render`'s fallback write behind the
3705
- // same call, so its trap now lives in `emit`'s OWN segment rather than
3706
- // render's — the `unguarded` filter above already treats a `|| emit` tail
3707
- // as guarded for that reason (unless the segment IS emit's own
3708
- // definition — see `censusStderrWrites`'s `delegates`), and this filter
3709
- // has to agree: a segment whose write reaches fd 2 only by delegating to
3710
- // `emit` carries no trap text of its own to find, and is not untrapped
3711
- // for it, because `emit`'s segment is checked separately, right here, in
3712
- // the same pass. `|| :` only swallows the *status* a killed write would
3713
- // leave behind, not the SIGPIPE that killed it, which is why a bare
3714
- // `|| :` tail (with no `emit` call) still has to show the trap substring
3715
- // in its own segment to pass.
3716
- assert.deepEqual(untrapped.map((s) => s.trim()), [],
3717
- "each of these can deliver SIGPIPE and kill the script instead of turning a dropped write into EPIPE — wrap it in `( trap '' PIPE; … )` or route it through `emit`, which already does");
3718
- });
3719
-
3720
- // #1703 found that treating any `|| emit` tail as guarded let `emit` guard
3721
- // ITSELF: a self-referential `|| emit "lost"` fallback on emit's own write
3722
- // recurses into the same failing write instead of reaching a segment this
3723
- // census clears elsewhere, and hangs rather than terminating (measured:
3724
- // exit 124, no termination). `censusStderrWrites`'s `delegates` carve-out
3725
- // is what keeps that shape out of the real script; this proves the
3726
- // carve-out actually fires, not just that the real script currently lacks
3727
- // the shape.
3728
- test("a self-referential emit() fallback does not pass the fd-2 write census (#1703)", () => {
3729
- const selfReferential = ["emit() { ( trap '' PIPE; printf '%s\\n' \"$1\" >&2 ) || emit \"lost\"; }"];
3730
- const { unguarded } = censusStderrWrites(selfReferential);
3731
- assert.deepEqual(unguarded.map((s) => s.trim()), [selfReferential[0].replace(/;\s*}$/, "").trim()],
3732
- "emit() falling back to calling itself must still be flagged unguarded — it recurses into the same failing write and hangs instead of terminating");
3733
- });
3734
-
3735
- /**
3736
- * Fails the stash-diagnostic fold and nothing else, addressed by ARGV.
3737
- *
3738
- * That fold is the script's only two-operand `tr` whose first operand is the
3739
- * literal `\n` — json.sh's four all carry either `-d` or a `\001-\007` range
3740
- * — so the argv test is exact. Content selection is unusable here:
3741
- * `withBrokenEscaper` reads the tool's stdin through `$(cat)` and re-feeds it
3742
- * with `printf '%s\n'`, and that round trip appends a newline to every value
3743
- * json.sh escapes through its own `tr` calls.
3744
- */
3745
- function withFailingDiagnosticFold(t) {
3746
- const s = shimDir(t, "no-undo-audit-fold-");
3747
- const real = s.real("tr");
3748
- const fired = join(s.bin, "fired");
3749
- s.write("tr", `if [ $# -eq 2 ] && [ "$1" = '\\n' ] && [ "$2" = ' ' ]; then
3750
- : >"${fired}"
3751
- echo "tr: RIP" >&2
3752
- exit 1
3753
- fi
3754
- exec ${real} "$@"
3755
- `);
3756
- return { path: s.path(), fired };
3757
- }
3758
-
3759
- test("a stash diagnostic that cannot be folded still answers, and says which half went missing (#1160)", (t) => {
3760
- // The FOURTH site of the class, and the one #1160's body does not enumerate
3761
- // — it is named only in this script's own locale-pin comment, alongside the
3762
- // three renders. It folds git's multi-line `stash list` diagnostic onto the
3763
- // audit's own line, decides nothing (`$stash` is already `null` and this
3764
- // branch is already reporting a fault), and unguarded an assignment's
3765
- // `$( … | tr … )` still hands `set -eu` tr's own status. `tr` is the surer
3766
- // carrier than the sed renders too: it exits on an invalid byte wherever in
3767
- // the line it sits, where sed tolerates some positions.
3768
- //
3769
- // Same fixture as the fold's own behaviour test above — a corrupt stash TIP
3770
- // object, the state where `stash list` itself fails and git says why.
3771
- const c = repo(t);
3772
- stashSomething(c.w);
3773
- const sha = git(c.w, "rev-parse", "refs/stash");
3774
- const obj = join(c.w, ".git", "objects", sha.slice(0, 2), sha.slice(2));
3775
- chmodSync(obj, 0o644);
3776
- writeFileSync(obj, "junk\n");
3777
-
3778
- const fold = withFailingDiagnosticFold(t);
3779
- const r = audit(c, { ...ENV, PATH: fold.path });
3780
-
3781
- assert.ok(existsSync(fold.fired),
3782
- "the fault injection never fired — git's diagnostic no longer flows through a `tr`, so nothing below measures a failed fold");
3783
- assert.equal(r.status, 0,
3784
- `the worktree is clean and was measured clean — exit 1 here is the fold deciding the verdict; got ${r.status} ${r.stderr}`);
3785
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
3786
- assert.equal(r.json.stash, null,
3787
- "the count is still unknown — that verdict is reached before the fold and must not depend on it");
3788
- assert.equal(stashLines(r).length, 1, "and the line is still printed, exactly once");
3789
- assert.match(stashLine(r), /git said more, and folding it onto this line failed/,
3790
- "git's own text is the half that went missing, and the line says so rather than ending where the fold did or carrying it truncated at the byte");
3791
- });
3792
-
3793
- // --- #431: the same broken escaper, one block further down, and the OPPOSITE
3794
- // answer. The three cases above escape `conflicts[]` and `atRisk[]` — findings
3795
- // the operator can obtain nowhere else, and which step 5 of the no-undo runbook
3796
- // hands to `git diff -- <path>`. A run that cannot render those has not
3797
- // answered, so they keep their `die`.
3798
- //
3799
- // `worktree` and `branch` are the other kind. They are echoes of argv: the
3800
- // caller supplied both and still holds them, and by the time this block runs
3801
- // `clean` has been measured, `stash` counted, and both arrays already rendered.
3802
- // A `tr` that has gone missing there used to convert that finished audit into
3803
- // exit 2 with no payload — discarding every real finding over the formatting of
3804
- // two values the caller typed. Each renders independently now and reports JSON
3805
- // `null` when it cannot, which is what #120 shipped for the same class in
3806
- // inflight.sh.
3807
- //
3808
- // `null` is the honest report and not a quieter `""`: a field that could not be
3809
- // escaped has no usable path to hand to `git diff` in any case, and `""` is
3810
- // indistinguishable from a path, which is the false-reassurance direction.
3811
- test("an escaper that cannot render the branch reports it null and still delivers every finding", (t) => {
3812
- const c = conflictRepo(t, "plain.txt", "fix/1-BOOMBRANCH");
3813
- const r = audit(c, { ...ENV, PATH: withBrokenEscaper(t, {
3814
- tool: "tr", marker: "BOOMBRANCH", selector: `'\\001-\\007\\013\\016-\\037'`,
3815
- }) });
3816
-
3817
- assert.equal(r.status, 0,
3818
- "the worktree was measured clean and every finding survived — exit 2 here would retract a finished audit over a formatter");
3819
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
3820
- assert.equal(r.json.branch, null, "the unrenderable field is null, not a truncated or empty string");
3821
- assert.equal(r.json.branchRewritten, null,
3822
- "and its paired flag too — a `false` there would claim nothing was replaced in a value nothing could examine");
3823
-
3824
- // The point of the whole change: everything the audit established is still on
3825
- // the payload, and the OTHER escaped field is untouched by its sibling's
3826
- // failure.
3827
- assert.equal(r.json.worktree, c.w, "the worktree renders independently and keeps its real value");
3828
- assert.equal(r.json.worktreeRewritten, false);
3829
- assert.equal(r.json.clean, true, "measured before the escape ran, and still reported");
3830
- assert.equal(r.json.stash, 0);
3831
- assert.deepEqual(r.json.conflicts, ["plain.txt"], "the conflicting path was found and is still named");
3832
- assert.deepEqual(r.json.conflictsRewritten, [false]);
3833
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"],
3834
- "the commit a careless resolution would eat is still named — that finding is the reason this script exists");
3835
-
3836
- assert.match(r.stderr, /could not render the branch .*\(jstr\)/,
3837
- "and the operator is told which field and which escaper, not left to diff the payload against a healthy one");
3838
- });
3839
-
3840
- test("an escaper that cannot say whether the worktree path was rewritten reports it null, leaving the branch intact", (t) => {
3841
- const c = conflictRepo(t, "plain.txt", undefined, "no-undo-audit-BOOMWT-");
3842
- const r = audit(c, { ...ENV, PATH: withBrokenEscaper(t, { tool: "tr", marker: "BOOMWT" }) });
3843
-
3844
- assert.equal(r.status, 0);
3845
- assert.equal(r.jsonError, null, `payload must parse; got ${r.jsonError?.message}\n${r.stdout}`);
3846
- assert.equal(r.json.worktree, null,
3847
- "`jstr` rendered this path perfectly and `jrewritten` still could not say whether a byte was replaced — an undisclosed rewrite is not a path a reader may trust");
3848
- assert.equal(r.json.worktreeRewritten, null);
3849
- assert.equal(r.json.branch, c.branch, "the branch renders independently and is unaffected");
3850
- assert.equal(r.json.branchRewritten, false);
3851
- assert.deepEqual(r.json.conflicts, ["plain.txt"]);
3852
- assert.deepEqual(subjects(r), ["MAIN COMMIT AT RISK"]);
3853
-
3854
- // Named separately from `jstr` because the two fail independently: `jstr` can
3855
- // render a string while `jrewritten` cannot judge it, which is exactly this
3856
- // case. One shared word would send a debugger to whichever it guessed.
3857
- assert.match(r.stderr, /could not render the worktree .*\(jrewritten\)/);
3858
- });
3859
-
3860
- // #431's acceptance criterion that lives in prose rather than in the payload: a
3861
- // reader of the runbook has to meet what a `null` field means BEFORE they act
3862
- // on one. Both carriers state it, on the same two lines the linkage pin above
3863
- // anchors on — the runbook's exit-2 paragraph and the design spec's own row.
3864
- //
3865
- // Two phrases, not one, because either alone is satisfied by a rewrite that
3866
- // loses the point. `there is no worktree` alone passes prose that names the
3867
- // misreading without ruling it out; `could not render the path or branch you passed in`
3868
- // alone passes prose that says what the field IS while leaving the dangerous
3869
- // reading unaddressed. The claim is the pair: this is what `null` means, and
3870
- // that is what it does not.
3871
- //
3872
- // Deliberately NOT pinned as one span: the two docs word the surrounding
3873
- // sentence differently on purpose — the runbook bolds its `never` for an
3874
- // operator mid-pass, the spec row does not — and a span pin would force one
3875
- // voice on both or drift into pinning nothing.
3876
- test("both docs rule out reading a null worktree as an absent one", () => {
3877
- for (const rel of ["../commands/run-merge-bot.md", "../../docs/specs/2026-07-23-fleet-plugin-design.md"]) {
3878
- const doc = readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8");
3879
- assert.ok(doc.includes("could not render the path or branch you passed in"),
3880
- `${rel} must say what a null worktree/branch IS — the run could not render the argument the caller supplied — since the field is an echo of argv rather than a finding`);
3881
- assert.ok(doc.includes('"there is no worktree"'),
3882
- `${rel} must rule out the false-reassurance reading by name: a null path is not an absent worktree, and an operator who reads it as one skips the proof step believing there was nothing to prove`);
3883
- }
3884
- });
3885
-
3886
- // --- #1020: the ambient git variables, one fixture each.
3887
- //
3888
- // The `--show-prefix` gate is this script's answer to "can git operate here is
3889
- // not is this the tree it answers about", and both variables walk past it —
3890
- // but through different doors and to different outcomes, so one fixture
3891
- // cannot speak for both. PR #1015 measured the cost of trying: a case
3892
- // overriding only one of the pair leaves the other half of
3893
- // `unset GIT_DIR GIT_WORK_TREE` unpinned and green.
3894
-
3895
- test("an ambient GIT_WORK_TREE does not report a dirty worktree as clean (#1020)", (t) => {
3896
- // The silent-failure half, and the one that clears an irreversible rebase.
3897
- //
3898
- // GIT_WORK_TREE outranks `-C`, so `git -C "$wt" rev-parse --show-prefix`
3899
- // answers about the ambient tree. The cwd is not under that tree, so git
3900
- // returns an EMPTY prefix — the exact value the gate reads as "$wt IS the
3901
- // root" — and the status below then compares $wt's index against the
3902
- // ambient tree's files.
3903
- //
3904
- // The ambient tree holds a COPY of the branch's tracked content, which is
3905
- // what makes the leaked answer an empty one. A bare empty directory would
3906
- // report every tracked file deleted, the audit would refuse, and the case
3907
- // would pin the false-refusal cousin instead of the false clean — the
3908
- // strictly less dangerous direction, and the one this script exists to rule
3909
- // out by name ("clean for a tree nothing looked at").
3910
- const c = repo(t);
3911
- const twin = join(c.w, "..", "twin");
3912
- mkdirSync(twin);
3913
- for (const f of ["f.txt", "g.txt"]) copyFileSync(join(c.w, f), join(twin, f));
3914
- writeFileSync(join(c.w, "precious.txt"), "work that exists nowhere else\n");
3915
-
3916
- // The fixture's own positive control, both directions: without the first the
3917
- // worktree might never have been dirty, without the second the leak may have
3918
- // stopped existing and this case would pin nothing either way.
3919
- assert.equal(git(c.w, "status", "--porcelain"), "?? precious.txt",
3920
- "fixture: the worktree must really be dirty, or this case measures nothing");
3921
- assert.equal(
3922
- execFileSync("git", ["-C", c.w, "status", "--porcelain"], {
3923
- cwd: c.w, env: { ...ENV, GIT_WORK_TREE: twin }, encoding: "utf8",
3924
- }),
3925
- "",
3926
- "fixture: the ambient GIT_WORK_TREE must really silence that answer, or the leak this pins no longer exists",
3927
- );
3928
-
3929
- const r = audit(c, { ...ENV, GIT_WORK_TREE: twin });
3930
-
3931
- // Exit code first, with stderr as the message, for the reason
3932
- // release-ticket.test.mjs's own #427 pair records: reaching for a payload
3933
- // field first turns a refusing run into a null-deref that names nothing,
3934
- // where this order carries the script's own words.
3935
- assert.equal(r.status, 1, r.stderr);
3936
- assert.equal(r.json.clean, false,
3937
- "an ambient GIT_WORK_TREE must not clear a rebase over uncommitted work — `clean: true` here is the exact failure the --show-prefix gate exists to prevent, reached through a door that gate cannot close");
3938
- assert.match(r.stderr, /REFUSED — commit the worktree before rebasing/);
3939
- assert.equal(readFileSync(join(c.w, "precious.txt"), "utf8"), "work that exists nowhere else\n");
3940
- });
3941
-
3942
- test("an ambient GIT_DIR does not blame a healthy .git for another repository (#1020)", (t) => {
3943
- // The false-refusal half, and it cannot use the dirty check as its detector:
3944
- // GIT_DIR is caught EARLIER, by the linkage check, which compares $wt's
3945
- // `.git` against the repository git resolved and finds the ambient one
3946
- // instead. Measured pre-fix: exit 2 naming $wt's own `.git` as the fault, on
3947
- // a worktree whose linkage is perfect — a safe rebase blocked, and the
3948
- // operator sent to repair a file that was never broken.
3949
- const c = repo(t);
3950
- const other = join(c.w, "..", "other");
3951
- execFileSync("git", ["clone", "-q", join(c.w, "..", "origin.git"), other], { env: ENV });
3952
-
3953
- const r = audit(c, { ...ENV, GIT_DIR: join(other, ".git") });
3954
-
3955
- // Exit code first, stderr as the message: pre-fix the script dies before it
3956
- // prints any payload, so `r.json.clean` first is a TypeError naming nothing.
3957
- assert.equal(r.status, 0, r.stderr);
3958
- assert.equal(r.json.clean, true, "a clean worktree must still audit clean with an unrelated GIT_DIR ambient");
3959
- assert.equal(r.json.worktree, c.w,
3960
- "and the payload must describe the worktree the caller named, not the one the environment did");
3961
- });