@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,3436 +0,0 @@
1
- // Regression gate for `ledger.mjs check` — the duplicate-filing guard.
2
- //
3
- // Every test stubs `gh` onto PATH. A test without a stub would put the real
4
- // tracker in the assertion path: the suite would then pass or fail on this
5
- // repo's live issue list and on whether the machine has network and auth, and
6
- // the offline-degradation tests would be asserting the very thing they stub.
7
- //
8
- // The stub is also how the "never queried" claims are proved: it records its
9
- // argv to a sentinel file, so a test can assert that `gh` was NOT run at all
10
- // rather than assuming it from the exit code.
11
-
12
- import { test } from "node:test";
13
- import assert from "node:assert/strict";
14
- import { spawn, spawnSync } from "node:child_process";
15
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
16
- import { tmpdir } from "node:os";
17
- import { join } from "node:path";
18
- import { fileURLToPath, pathToFileURL } from "node:url";
19
- import { writeExecStub } from "./exec-stub.mjs";
20
-
21
- const SCRIPT = fileURLToPath(new URL("./ledger.mjs", import.meta.url));
22
- // #155's fix resolves the ledger's own repository with a real `git`
23
- // subprocess (both here in test setup and inside ledger.mjs itself), so PATH
24
- // cannot simply be reduced to the stub's directory the way `gh` alone used
25
- // to allow — `git` has to stay reachable too. Resolved once, symlinked into
26
- // every fixture's `bin/` below, which keeps `gh` exactly as isolated as
27
- // before (real PATH never reaches it) while `git` still resolves.
28
- const REAL_GIT = spawnSync("which", ["git"], { encoding: "utf8" }).stdout.trim();
29
- if (!REAL_GIT) throw new Error("ledger.test.mjs setup: could not locate a `git` binary on PATH");
30
-
31
- // `printf '%s\n' "$@"` before any early exit: the argv record has to survive the
32
- // failure paths too, or the "what query did gh receive" assertions can only run
33
- // on the success path.
34
- //
35
- // Shell builtins only — no `cat`. PATH is reduced to the stub's own directory
36
- // (see run()), so an external binary here fails with 127 and the stub then
37
- // looks exactly like a broken `gh`: every "tracker returned hits" test would
38
- // silently assert the offline path instead. The `|| [ -n "$line" ]` guard emits
39
- // the last line of a fixture written without a trailing newline, which is what
40
- // JSON.stringify produces.
41
- const GH_STUB = `#!/bin/sh
42
- printf '%s\\n' "$@" > "$GH_ARGS_FILE"
43
- pwd -P > "$GH_CWD_FILE"
44
- printf 'GIT_DIR=%s\\nGH_REPO=%s\\n' "\${GIT_DIR-}" "\${GH_REPO-}" > "$GH_ENV_FILE"
45
- if [ -n "$GH_FAIL" ]; then
46
- echo "gh: could not authenticate to github.com (HTTP 401)" >&2
47
- exit 1
48
- fi
49
- # GH_FAIL's one tidy line is the shape that hides #638: it neither overruns the
50
- # cap nor trims away. This escape emits its value on stderr verbatim — no
51
- # trailing newline added — so a test can drive the stderr shapes that do:
52
- # warnings ahead of the real error, and whitespace with no cause in it at all.
53
- if [ -n "$GH_STDERR" ]; then
54
- printf '%s' "$GH_STDERR" >&2
55
- exit 1
56
- fi
57
- # A gh that prints and then HANGS past the script's own 20 s timeout. \`exec\`,
58
- # and an absolute path: PATH is the stub's own directory (see run()), which
59
- # holds only \`gh\` and \`git\`, so a bare \`sleep\` would exit 127 and this
60
- # would test a broken gh instead of a hanging one. \`exec\` puts the sleep in
61
- # the shell's own process so execFileSync's SIGTERM lands on it directly
62
- # rather than orphaning it to outlive the test.
63
- if [ -n "$GH_HANG" ]; then
64
- printf '%s' "$GH_HANG" >&2
65
- exec /bin/sleep 25
66
- fi
67
- if [ -n "$GH_GARBAGE" ]; then
68
- echo "Welcome to gh! Run gh auth login to get started."
69
- exit 0
70
- fi
71
- while IFS= read -r line || [ -n "$line" ]; do printf '%s\\n' "$line"; done < "$GH_FIXTURE"
72
- `;
73
-
74
- // filed rows go in verbatim; the script's own escaping is exercised by the
75
- // `filed` subcommand, which this file does not touch.
76
- function ledgerText(filed) {
77
- return `# Fleet run ledger\n\n## Rows\n\n\n## Filed\n\n${filed.map((f) => `- ${f}`).join("\n")}\n\n## Ruled\n\n`;
78
- }
79
-
80
- // `hits` is what the gh stub prints; `gh: false` removes gh from PATH entirely
81
- // (the "gh not installed" case, which throws ENOENT rather than exiting non-zero
82
- // — a different code path from an auth failure and worth its own coverage).
83
- //
84
- // `gitRepo` defaults true because that is what every real ledger location is
85
- // (`--file` inside a checkout, or defaultLedgerPath()'s own --git-common-dir
86
- // derivation) — #155 makes the tracker query bind to that repo, so a fixture
87
- // that is not one no longer reaches gh at all. `gitRepo: false` is its own
88
- // case — an explicit --file naming a path outside any repository, or a
89
- // `noFile` run whose fixture dir is never consulted because `procCwd` points
90
- // the ledger resolution somewhere else entirely — and `noFile`
91
- // / `procCwd` exist to drive the no-`--file` documented flow, which resolves
92
- // its own ledger location from the spawned process's cwd rather than `--file`.
93
- //
94
- // `ledgerDirExists: false` withholds the setup `mkdirSync` (and the ledger
95
- // file with it) to reproduce the state every fresh clone and worktree is in
96
- // before the run's first write: `.fleet/` is gitignored and created lazily by
97
- // save(), so the DEFAULT `true` here is a fixture that pre-creates something
98
- // production never has yet — and it is what hid a #155 regression from the
99
- // accept-pin below.
100
- function run(subject, { filed = [], hits = [], ghFails = false, ghGarbage = false, ghStderr = null, ghHang = null, gh = true, args = [], gitRepo = true, noFile = false, procCwd = null, ledgerDirExists = true, ledgerBody = null, spawnEnv = {} } = {}) {
101
- const dir = mkdtempSync(join(tmpdir(), "ledger-"));
102
- try {
103
- // Inherited git vars outrank both cwd and `-C`, and they reach here from
104
- // whatever ran the suite — a git hook, `rebase --exec`, `bisect run`.
105
- // Under an ambient GIT_DIR the `git init` below exits 0 and creates
106
- // NOTHING in `dir`: it re-inits the directory GIT_DIR names instead, so
107
- // the fixture is silently not a repository and the status assert cannot
108
- // see it. Scrub them off the whole fixture, as the fleet's other
109
- // fixtures already do (inflight.test.mjs), so these tests measure the
110
- // code under test rather than the environment that started them.
111
- // `spawnEnv` puts one back deliberately, for the test that pins the
112
- // scrub ledger.mjs itself performs.
113
- const baseEnv = { ...process.env };
114
- delete baseEnv.GIT_DIR;
115
- delete baseEnv.GIT_WORK_TREE;
116
- if (gitRepo) {
117
- const init = spawnSync("git", ["init", "-q"], { cwd: dir, stdio: "ignore", env: baseEnv });
118
- assert.equal(init.status, 0, "test setup: git init must succeed");
119
- // `git init` exiting 0 is not the same as this directory being a repo
120
- // (see above) — assert the thing the fixtures actually depend on.
121
- assert.ok(existsSync(join(dir, ".git")), "test setup: git init must have created a repository HERE");
122
- }
123
- const ledgerDir = noFile ? join(dir, ".fleet") : dir;
124
- if (noFile && ledgerDirExists) mkdirSync(ledgerDir, { recursive: true });
125
- const file = join(ledgerDir, "ledger.md");
126
- // No directory means no ledger file either — writing one would be the very
127
- // state `ledgerDirExists: false` exists to withhold.
128
- // `ledgerBody` writes the file's bytes directly: the states worth testing
129
- // below are ones ledgerText() structurally cannot produce — a file that is
130
- // not a ledger, and a ledger whose header is corrupt.
131
- if (ledgerDirExists) writeFileSync(file, ledgerBody ?? ledgerText(filed));
132
- const fixture = join(dir, "hits.json");
133
- writeFileSync(fixture, JSON.stringify(hits));
134
- const argsFile = join(dir, "gh-argv");
135
- const cwdFile = join(dir, "gh-cwd");
136
- const ghEnvFile = join(dir, "gh-env");
137
- const bin = join(dir, "bin");
138
- const env = {
139
- ...baseEnv,
140
- GH_FIXTURE: fixture,
141
- GH_ARGS_FILE: argsFile,
142
- GH_CWD_FILE: cwdFile,
143
- GH_ENV_FILE: ghEnvFile,
144
- // PATH is replaced, not prefixed: a prefix leaves the real `gh` reachable
145
- // the moment the stub's own directory lookup changes, and the ENOENT test
146
- // would then silently start querying the live tracker. `git` still
147
- // resolves — it is symlinked into this same `bin` below — so this stays
148
- // narrow to `gh` alone.
149
- PATH: bin,
150
- // Last, so a test can deliberately put back a var the scrub above
151
- // removed — that is the whole point of the GIT_DIR pin below.
152
- ...spawnEnv,
153
- };
154
- if (ghFails) env.GH_FAIL = "1";
155
- if (ghGarbage) env.GH_GARBAGE = "1";
156
- if (ghStderr !== null) env.GH_STDERR = ghStderr;
157
- if (ghHang !== null) env.GH_HANG = ghHang;
158
- mkdirSync(bin, { recursive: true });
159
- symlinkSync(REAL_GIT, join(bin, "git"));
160
- if (gh) {
161
- const ghPath = join(bin, "gh");
162
- // No warm-up exec: `writeExecStub` links the trampoline exec-stub.mjs
163
- // already exec'd at import, so this stub's first exec pays no OS scan
164
- // inside the 20 s budget ledger.mjs puts on its gh child.
165
- writeExecStub(ghPath, GH_STUB);
166
- }
167
- // No `stdio` override on purpose: the default pipe is what makes `r.stderr`
168
- // readable at all. spawnSync drains stdout and stderr concurrently, so the
169
- // child never blocks on a full pipe, and no `check` arm reaches its exit
170
- // through process.exit(), which is what dropped queued writes past the
171
- // ~64 KiB pipe buffer (measured on candidates.mjs, issue #132) and
172
- // abandoned the payload with them (#246, #808) — so these assertions are
173
- // honest. The ceiling that is left is spawnSync's own maxBuffer, 1 MiB per
174
- // stream by default: past it the child is killed and the capture arrives
175
- // short under a null exit code. The #808 fixtures run well past the pipe
176
- // buffer and stay under that cap; widen one and that is what gives.
177
- const scriptArgs = noFile ? ["check", ...args, subject] : ["--file", file, "check", ...args, subject];
178
- const r = spawnSync(process.execPath, [SCRIPT, ...scriptArgs], {
179
- encoding: "utf8",
180
- env,
181
- cwd: procCwd || (noFile ? dir : undefined),
182
- });
183
- let json = null;
184
- try {
185
- json = JSON.parse(r.stdout);
186
- } catch {
187
- /* several tests assert on a non-JSON failure exit; leave json null */
188
- }
189
- return {
190
- status: r.status,
191
- stdout: r.stdout,
192
- stderr: r.stderr,
193
- json,
194
- ghRan: existsSync(argsFile),
195
- ghArgv: existsSync(argsFile) ? readFileSync(argsFile, "utf8").trim().split("\n") : [],
196
- ghCwd: existsSync(cwdFile) ? readFileSync(cwdFile, "utf8").trim() : null,
197
- // What gh saw for the two env vars that outrank the cwd it was bound to
198
- // — `""` for either means ledger.mjs scrubbed it, which is the whole
199
- // assertion. Read as strings, so a var that arrived unset and one that
200
- // arrived empty are indistinguishable here: both are the safe state.
201
- ghEnv: existsSync(ghEnvFile)
202
- ? Object.fromEntries(
203
- readFileSync(ghEnvFile, "utf8").trimEnd().split("\n").map((l) => {
204
- const i = l.indexOf("=");
205
- return [l.slice(0, i), l.slice(i + 1)];
206
- }),
207
- )
208
- : null,
209
- // Resolved before the `finally` below removes `dir` — a caller that
210
- // realpath()s this after run() returns hits an ENOENT, not a path.
211
- ledgerRepoDir: realpathSync(dir),
212
- };
213
- } finally {
214
- rmSync(dir, { recursive: true, force: true });
215
- }
216
- }
217
-
218
- // The term-selection tests need the exact --search string gh received, not
219
- // just whether it ran.
220
- function queryOf(r) {
221
- return r.ghArgv[r.ghArgv.indexOf("--search") + 1];
222
- }
223
-
224
- const FILED_114 =
225
- "#114 fleet-plugin-design Non-zero column written from intent — audit 11 rows (review-pr-108)";
226
- const FILED_131 = "#131 run-merge-bot.md exit-2 documentation gap in the merge loop";
227
-
228
- // ---------------------------------------------------------------------------
229
- // The existing exact/subset contract. These pass against the pre-change script
230
- // and exist so the new reporting cannot quietly move the strong signal.
231
- // ---------------------------------------------------------------------------
232
-
233
- test("an exactly-reworded filed subject is still ALREADY FILED, exit 1", () => {
234
- const r = run("fleet-plugin-design Non-zero column written from intent — audit 11 rows (review-pr-108)", {
235
- filed: [FILED_114],
236
- });
237
- assert.equal(r.status, 1);
238
- assert.equal(r.json.found, true);
239
- assert.match(r.json.match, /^#114 /);
240
- assert.equal(r.json.verdict, "already-filed");
241
- assert.match(r.stderr, /ALREADY FILED/);
242
- });
243
-
244
- test("a strict four-token subset of a filed row is still a match, exit 1", () => {
245
- const r = run("Non-zero column audit 11 rows", { filed: [FILED_114] });
246
- assert.equal(r.status, 1);
247
- assert.equal(r.json.found, true);
248
- });
249
-
250
- test("a three-token overlap is below the subset floor and is not a match", () => {
251
- const r = run("column audit rows", { filed: [FILED_114] });
252
- assert.equal(r.status, 0);
253
- assert.equal(r.json.found, false);
254
- assert.equal(r.json.match, null);
255
- });
256
-
257
- // ---------------------------------------------------------------------------
258
- // The two acceptance rules at their boundaries (#888). isMatch() accepts on
259
- // either of two rules — equal token sets at any size, or a subset from at
260
- // least four tokens — and the equal-set acceptance below the subset floor and the
261
- // acceptance at the subset floor are what pin those rules, each sitting where the
262
- // other rule cannot account for the outcome. Same-size sets are where the two
263
- // rules come apart, and the tests above reach that case only through rows
264
- // built for other purposes.
265
- //
266
- // Two tests share this fence without pinning either rule. The same-size
267
- // refusal runs four tokens against four, so both size rules pass and only the
268
- // subset conjunct refuses it — that conjunct is what it pins, and it is the
269
- // same-size case worth pinning. The empty-subject usage failure dies before
270
- // isMatch is reached, so it reaches neither rule.
271
- //
272
- // A same-size match at or above the subset floor is deliberately NOT pinned here: it
273
- // satisfies both rules at once, so no single-rule mutation can red it and it
274
- // discriminates nothing. An equal set under the subset floor is an acceptance only
275
- // one rule can explain.
276
- // ---------------------------------------------------------------------------
277
-
278
- test("a same-size four-token near-miss differing in one token is not a match (#888)", () => {
279
- const r = run("quorum drains under retry", { filed: ["#901 quorum drains under replay"] });
280
- assert.equal(r.status, 0);
281
- assert.equal(r.json.found, false);
282
- assert.equal(r.json.match, null);
283
- });
284
-
285
- test("equal token sets match below the subset floor — the subset floor gates the subset rule alone (#888)", () => {
286
- // The subset floor exists to stop a short generic overlap matching everything, and
287
- // it is a condition of the SUBSET rule only: equal sets are already as
288
- // specific as a match gets, so they qualify at any size. Folding the two
289
- // rules into one guarded expression is the edit that can silently lose
290
- // this, and nothing else in this file builds an equal set small enough to
291
- // notice.
292
- const r = run("pipe truncates payload", { filed: ["#902 payload truncates pipe"] });
293
- assert.equal(r.status, 1);
294
- assert.equal(r.json.found, true);
295
- assert.match(r.json.match, /^#902 /);
296
- });
297
-
298
- test("a strict subset exactly at the subset floor is a match — the subset floor is pinned from above (#899)", () => {
299
- // The subset floor is a lower bound, so the refusal beneath it anchors one side
300
- // only: raise the subset floor and matches quietly stop happening. That is the
301
- // direction `check` is deliberately biased toward — a duplicate someone
302
- // closes rather than a finding silently lost — which is exactly why a
303
- // raised subset floor disturbs nothing else here. Acceptance AT the subset floor is the
304
- // observation that notices, and it has to be a STRICT subset: an equal pair
305
- // qualifies under the equal-size rule as well, so the subset floor would no longer
306
- // be what decides and the mutation would have nothing to move.
307
- //
308
- // Plain words, no punctuation, on both sides. The subject's token count is
309
- // the whole subject of this pin, so it must not shift when norm() changes
310
- // how it folds punctuation — otherwise this reds for a reason it does not
311
- // name. A match also returns before the tracker query is built, so nothing
312
- // in term selection or the near-miss scoring can reach this either.
313
- const r = run("quorum lease drains retry", {
314
- filed: ["#903 retry budget drains the shared quorum lease"],
315
- });
316
- assert.equal(r.status, 1);
317
- assert.equal(r.json.found, true);
318
- assert.match(r.json.match, /^#903 /);
319
- });
320
-
321
- test("a subject with no alphanumeric tokens is a usage failure, exit 2", () => {
322
- const r = run("— — —", { filed: [FILED_114] });
323
- assert.equal(r.status, 2);
324
- assert.match(r.stderr, /normalised subject is empty/);
325
- });
326
-
327
- // ---------------------------------------------------------------------------
328
- // Direction normalisation (#899 review). isMatch() orders the pair by size
329
- // before either acceptance rule reads it, so both rules always measure the
330
- // smaller set. Hardcoding the ordering away leaves the rest of this file
331
- // green because no other fixture reaches a match through the mirror
332
- // orientation — not because of how their sizes happen to fall.
333
- // ---------------------------------------------------------------------------
334
-
335
- test("a filed row that is a strict subset of a longer subject is a match — the smaller set is what the subset floor measures", () => {
336
- // Dropping the ordering — hardcoding the pair as (subject, filed) so the
337
- // checked subject is always taken as the smaller set — leaves every other
338
- // fixture in this file green. This fixture is the mirror orientation, where
339
- // the FILED row is the smaller set. Other fixtures build that orientation
340
- // too, but none of them reaches a match through it, so the ordering never
341
- // decides their answer — this is the first fixture where it does.
342
- //
343
- // Sized clear of the subset floor deliberately. At exactly four tokens a raised
344
- // subset floor reds this too, and it would then be pinning the boundary a
345
- // neighbouring test already owns rather than the ordering. Clear of the
346
- // subset floor, the ordering moves it — so does disabling the `#NNN` strip, which
347
- // decides whether the filed row can be a subset at all, not which of the
348
- // two sets is the smaller one.
349
- //
350
- // Plain words on both sides, as the token counts are load-bearing and must
351
- // not shift when norm() changes how it folds punctuation.
352
- const r = run("the retry budget drains the shared quorum lease under sustained load", {
353
- filed: ["#904 retry budget drains quorum lease"],
354
- });
355
- assert.equal(r.status, 1);
356
- assert.equal(r.json.found, true);
357
- assert.match(r.json.match, /^#904 /);
358
- });
359
-
360
- // ---------------------------------------------------------------------------
361
- // Near-miss reporting (issue #145, option 3).
362
- // ---------------------------------------------------------------------------
363
-
364
- test("a filed finding described in different words surfaces as a scored near-miss", () => {
365
- // Neither token set contains the other — "behaviour"/"undocumented" are absent
366
- // from the filed row, "documentation"/"gap" from the subject — so the subset
367
- // path correctly misses it. That miss is the whole defect #145 reports.
368
- const r = run("merge loop exit 2 behaviour undocumented in run-merge-bot.md", {
369
- filed: [FILED_131],
370
- });
371
- assert.equal(r.status, 0, "a near-miss is advisory, not a stop");
372
- assert.equal(r.json.found, false, "near-misses must not be reported as an exact hit");
373
- assert.ok(r.json.near.length >= 1, "expected the reworded row to surface");
374
- assert.match(r.json.near[0].row, /^#131 /);
375
- assert.ok(r.json.near[0].score >= 0.5, `expected a strong score, got ${r.json.near[0].score}`);
376
- assert.match(r.stderr, /near-miss/);
377
- });
378
-
379
- test("near-misses are ranked best-first and capped at three", () => {
380
- const filed = [
381
- "#1 something else entirely about postgres connection pooling",
382
- "#2 merge loop exit code documentation",
383
- "#3 unrelated worktree audit prose",
384
- "#4 the merge loop exit 2 gap in run-merge-bot.md documentation",
385
- "#5 loop merge unrelated tangent",
386
- // Five rows must score above zero, or "capped at three" passes on the
387
- // filter and never exercises the cap: raising NEAR_SHOWN in ledger.mjs
388
- // from 3 to 10 then reds nothing.
389
- "#6 merge loop tangent",
390
- "#7 loop exit trivia",
391
- ];
392
- const r = run("merge loop exit 2 behaviour undocumented in run-merge-bot.md", { filed });
393
- assert.equal(r.status, 0);
394
- assert.equal(r.json.near.length, 3, "top-3 cap");
395
- assert.ok(
396
- filed.filter((f) => f.match(/merge|loop|exit/)).length > 3,
397
- "the fixture must offer more scoring rows than the cap returns",
398
- );
399
- assert.match(r.json.near[0].row, /^#4 /, "the closest row must rank first");
400
- const scores = r.json.near.map((n) => n.score);
401
- assert.deepEqual(scores, [...scores].sort((a, b) => b - a), "scores must be descending");
402
- });
403
-
404
- test("a subject sharing no content words with any filed row reports no near-misses", () => {
405
- const r = run("postgres connection pooling exhausted under load", { filed: [FILED_114, FILED_131] });
406
- assert.equal(r.status, 0);
407
- assert.deepEqual(r.json.near, []);
408
- });
409
-
410
- // ---------------------------------------------------------------------------
411
- // The cap must SAY it capped (issue #154). `candidates.mjs` legislates the same
412
- // rule one script over and enforces it by refusing outright; refusing is wrong
413
- // here — these lists are advisory context for a decision, not the work queue,
414
- // and a single tracker hit already forces exit 3 — so the remedy is to report
415
- // what was withheld, never to drop it in silence.
416
- // ---------------------------------------------------------------------------
417
-
418
- // Five rows whose every content word is the subject's, so every one scores an
419
- // identical 1.00: the tie is the point. Nothing about the SCORE separates the
420
- // three shown from the two dropped — only the cap does — which is exactly the
421
- // state the caller cannot infer from a three-row list.
422
- const TIED_FIVE = [
423
- "#1 merge loop exit",
424
- "#2 loop exit code",
425
- "#3 merge exit code",
426
- "#4 run merge bot",
427
- "#5 merge code loop",
428
- ];
429
- const TIED_SUBJECT = "the merge loop exit code is undocumented in run-merge-bot.md";
430
-
431
- test("near-misses withheld by the cap are counted, not dropped in silence (#154)", () => {
432
- const r = run(TIED_SUBJECT, { filed: TIED_FIVE });
433
- assert.equal(r.status, 0, "reporting the withheld rows must not move a near-miss off exit 0");
434
- // The verdict half of this moved with #388: a near-miss at this score IS the
435
- // verdict now. What #154 pins here is the reporting of the cut, and that the
436
- // rows stay advisory — the exit code above, not the word.
437
- assert.equal(r.json.verdict, "soft-hit", "rows scoring this high are the answer, not decoration beside it");
438
- assert.equal(r.json.near.length, 3, "the display cap itself is unchanged");
439
- assert.deepEqual(r.json.near.map((n) => n.score), [1, 1, 1], "the fixture must actually tie, or this pins nothing");
440
- assert.equal(r.json.nearTotal, 5, "the caller must be able to tell 3-of-3 from 3-of-5 from the payload alone");
441
- assert.match(
442
- r.stderr,
443
- /2 further near-misses not shown/,
444
- "the count withheld has to reach the caller, not just the JSON",
445
- );
446
- assert.match(
447
- r.stderr,
448
- /highest withheld 1\.00/,
449
- "a withheld row tied with the shown ones is the case the caller most needs told about",
450
- );
451
- // The comment the notice implements says the withheld rows are reported as a
452
- // count and a score, "never the rows" — printing them would give back the
453
- // length the cap exists to take away. Read off the notice line itself rather
454
- // than the whole stderr, which legitimately carries `#N` on every shown
455
- // near-miss, and match the row MARKER rather than this fixture's row text, so
456
- // reordering the tied rows cannot red it while the invariant holds.
457
- assert.doesNotMatch(
458
- r.stderr.split("\n").find((l) => l.includes("further near-miss")) ?? "",
459
- /#\d/,
460
- "the notice reports the count and the top score, never a withheld row",
461
- );
462
- });
463
-
464
- // Every row shares the subject's words, but progressively fewer of them, so no
465
- // two score alike. That is the whole point: under a tie the highest withheld
466
- // score and the lowest are the same number, so an index that reports the wrong
467
- // row prints the right value and no assertion can tell. Measured, a mutation
468
- // reporting the LOWEST withheld score — and even `rankedNear[0]` — survives the
469
- // entire suite against the tied fixture above.
470
- const UNTIED_FIVE = [
471
- "#1 merge loop exit",
472
- "#2 merge loop pooling",
473
- "#3 merge loop pooling exhausted",
474
- "#4 merge pooling exhausted",
475
- "#5 merge pooling exhausted postgres",
476
- ];
477
-
478
- test("the score reported as withheld is the HIGHEST withheld one, not the last shown or the lowest (#154)", () => {
479
- const r = run(TIED_SUBJECT, { filed: UNTIED_FIVE });
480
- assert.equal(r.status, 0);
481
- assert.deepEqual(
482
- r.json.near.map((n) => n.score),
483
- [1, 0.67, 0.5],
484
- "the fixture must NOT tie, or this pins the same nothing the tied one does",
485
- );
486
- assert.equal(r.json.nearTotal, 5);
487
- // One value rules out every off-by-one at once: 0.50 is the last SHOWN row,
488
- // 0.25 the lowest withheld, 1.00 the top of the ranking. Only the first
489
- // withheld row reads 0.33.
490
- assert.match(
491
- r.stderr,
492
- /2 further near-misses not shown — highest withheld 0\.33/,
493
- "the caller is told what the cut cost it, which is the top of what it did not get",
494
- );
495
- });
496
-
497
- test("exactly one withheld near-miss still fires the notice (#154)", () => {
498
- // The tightest boundary the notice has: one row over the cap. A guard off by
499
- // one goes silent precisely here and nowhere else, and the fixtures above —
500
- // two withheld, none withheld — both straddle it.
501
- const r = run(TIED_SUBJECT, { filed: TIED_FIVE.slice(0, 4) });
502
- assert.equal(r.status, 0);
503
- assert.equal(r.json.near.length, 3, "the display cap is what withholds the fourth row");
504
- assert.equal(r.json.nearTotal, 4);
505
- assert.match(r.stderr, /1 further near-miss not shown/, "one withheld row is still a withheld row, and one reads in the singular");
506
- });
507
-
508
- test("exactly three near-misses report no withholding — the notice must not fire on a complete list (#154)", () => {
509
- // Two filed rows that score ZERO sit alongside the three that tie. They are
510
- // what makes this a real pin rather than a restatement: a `nearTotal` counted
511
- // off the filed list instead of the scoring rows reads 5 here and reports two
512
- // rows withheld that no cap ever touched — and the tied fixture above, where
513
- // every filed row scores, cannot tell those two implementations apart.
514
- const r = run(TIED_SUBJECT, {
515
- filed: TIED_FIVE.slice(0, 3).concat([
516
- "#8 postgres connection pooling exhausted",
517
- "#9 unrelated worktree audit prose",
518
- ]),
519
- });
520
- assert.equal(r.status, 0);
521
- assert.equal(r.json.near.length, 3, "a full-but-not-over list still fills the cap exactly");
522
- assert.equal(r.json.nearTotal, 3, "nothing was withheld, and the payload must say so");
523
- assert.doesNotMatch(r.stderr, /further near-miss/, "claiming a withheld row that does not exist is the same lie inverted");
524
- });
525
-
526
- // ---------------------------------------------------------------------------
527
- // Tracker query (issue #145, option 1) and its offline degradation.
528
- // ---------------------------------------------------------------------------
529
-
530
- const HIT_114 = {
531
- number: 114,
532
- title: "fleet-plugin-design: the Script surface table's Non-zero column was written from intent",
533
- state: "OPEN",
534
- url: "https://github.com/feigi/claude-config/issues/114",
535
- };
536
-
537
- test("an open tracker issue absent from the ledger is reported, not passed as safe", () => {
538
- // The subject shares content words with the hit's title on purpose: since
539
- // #388 the escalation to exit 3 is the scorer's call, so a subject that
540
- // scored 0.00 against this row would be testing the advisory arm under this
541
- // test's name.
542
- const r = run("Non-zero column audit 11 rows", { filed: [], hits: [HIT_114] });
543
- assert.equal(r.status, 3, "a tracker hit with a clean ledger is exit 3, not 0");
544
- assert.equal(r.json.found, false, "the ledger genuinely did not have it — `found` stays ledger-only");
545
- assert.equal(r.json.tracker.ok, true);
546
- assert.equal(r.json.tracker.hits[0].number, 114);
547
- assert.equal(r.json.tracker.hits[0].state, "OPEN");
548
- assert.equal(typeof r.json.tracker.hits[0].score, "number");
549
- assert.equal(r.json.verdict, "tracker-hit");
550
- assert.match(r.stderr, /TRACKER HIT/);
551
- // Order, not just presence: the hits are listed inside the same branch that
552
- // prints the count, so a careless edit can emit the summary above the rows it
553
- // summarises. Nothing else pins this.
554
- assert.match(r.stderr, /TRACKER HIT[\s\S]*tracker issue\(s\) match/, "every hit is listed before the line that counts them");
555
- assert.doesNotMatch(r.stderr, /ALREADY FILED/, "a tracker hit is not the same claim as a filed row");
556
- });
557
-
558
- // gh reports no total alongside a capped list, so 5-of-5 and 5-of-300 arrive
559
- // byte-identical. Asking for one more row than is displayed is the whole
560
- // mechanism: the extra row's presence IS the truncation signal (#154).
561
- // Titled to score against the subject these fixtures are checked with, but well
562
- // below the exact-title row below: a filler set scoring 0.00 is the advisory
563
- // arm since #388, and would take both truncation tests off the blocking exit
564
- // code they exist to pin.
565
- const filler = (n) => ({
566
- number: n,
567
- title: "postgres pooling code exhausted under sustained load",
568
- state: "CLOSED",
569
- url: `https://github.com/feigi/claude-config/issues/${n}`,
570
- });
571
- const EXACT_TITLE = {
572
- number: 606,
573
- title: "candidates.mjs row states the opposite of its code",
574
- state: "OPEN",
575
- url: "https://github.com/feigi/claude-config/issues/606",
576
- };
577
-
578
- test("gh is asked for one more issue than is displayed, so a full page is distinguishable from a truncated one (#154)", () => {
579
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], hits: [] });
580
- assert.equal(r.ghArgv[r.ghArgv.indexOf("--limit") + 1], "6", "5 displayed + 1 probe row");
581
- });
582
-
583
- test("a tracker list gh truncated says so, and the probe row still ranks (#154)", () => {
584
- // Six back for a five-row display. The best-scoring row is deliberately LAST
585
- // in gh's own order: it may only survive if the overlap sort runs across the
586
- // whole fetched window before the display cap, not after it.
587
- const hits = [1, 2, 3, 4, 5].map(filler).concat([EXACT_TITLE]);
588
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], hits });
589
- assert.equal(r.status, 3, "truncation reporting must not move a tracker hit off exit 3");
590
- assert.equal(r.json.verdict, "tracker-hit");
591
- assert.equal(r.json.tracker.hits.length, 5, "the sixth row is a probe, not a row to display");
592
- assert.equal(r.json.tracker.truncated, true, "the payload must name the truncation, not leave it inferable");
593
- assert.equal(r.json.tracker.hits[0].number, 606, "the probe row participates in the ranking it was fetched into");
594
- assert.match(r.stderr, /but more than 5 tracker issue\(s\) match/, "a capped count must not be printed as an exact one");
595
- assert.match(r.stderr, /CAPPED at 5/, "and the caller is told the ranking is over gh's window, not over the tracker");
596
- assert.match(
597
- r.stderr,
598
- /TRACKER HIT[\s\S]*tracker issue\(s\) match/,
599
- "the rows still come before the line that counts them",
600
- );
601
- });
602
-
603
- test("a tracker list that exactly fills the display claims no truncation (#154)", () => {
604
- const hits = [1, 2, 3, 4, 5].map(filler);
605
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], hits });
606
- assert.equal(r.status, 3);
607
- assert.equal(r.json.tracker.hits.length, 5, "five rows displayed, none dropped");
608
- assert.equal(r.json.tracker.truncated, false, "no probe row came back, so nothing was withheld");
609
- assert.match(r.stderr, /but 5 tracker issue\(s\) match/, "an exact count is what a complete list has earned");
610
- assert.doesNotMatch(r.stderr, /more than|CAPPED/, "over-reporting truncation would send the caller hunting rows that do not exist");
611
- });
612
-
613
- test("a clean ledger and a clean tracker is the only path that reads safe, exit 0", () => {
614
- const r = run("postgres connection pooling exhausted under load", { filed: [FILED_114], hits: [] });
615
- assert.equal(r.status, 0);
616
- assert.equal(r.json.tracker.ok, true);
617
- assert.deepEqual(r.json.tracker.hits, [], "a searched-and-clean tracker reports an empty list, not absent");
618
- assert.equal(r.json.verdict, "clean");
619
- });
620
-
621
- // ---------------------------------------------------------------------------
622
- // The verdict consumes the scores the payload already carries (#388).
623
- //
624
- // Both halves were measured wrong in one run: `tracker-hit` over rows this
625
- // file's own overlap rates 0.00, and `clean` printed directly above near-miss
626
- // rows that named the right issue. The rows and the scores were computed and
627
- // printed in both cases — only the verdict ignored them. The fixtures below
628
- // are those measured shapes.
629
- //
630
- // `soft-hit` is the verdict for "signal, not a duplicate finding". It stays on
631
- // exit 0 deliberately: exit 3's meaning ("the ledger is clean but the tracker
632
- // has matching rows") is what callers gate on, and near-misses were already
633
- // ruled advisory rather than blocking (#145, #152). What moves is the hit set
634
- // the scorer rates 0.00, which used to force 3.
635
- // ---------------------------------------------------------------------------
636
-
637
- // The wontfix-vocabulary shape: rows that share a filing convention with each
638
- // other and nothing with the subject. gh's ANDed query returned them; every one
639
- // scores 0.00 here.
640
- const REFUTED_BAND = [340, 356, 280].map((n) => ({
641
- number: n,
642
- title: `PR #${n} review: the suggestion band, checked`,
643
- state: "CLOSED",
644
- url: `https://github.com/feigi/claude-config/issues/${n}`,
645
- }));
646
- const KB_SUBJECT = "the KB file the skill points at is missing from the plugin bundle";
647
-
648
- test("tracker rows the scorer rates 0.00 are advisory, not a hit (#388)", () => {
649
- const r = run(KB_SUBJECT, { filed: [], hits: REFUTED_BAND });
650
- assert.equal(r.json.tracker.ok, true, "the tracker WAS read — this is not the unverified arm");
651
- assert.deepEqual(r.json.tracker.hits.map((h) => h.score), [0, 0, 0], "the fixture must actually score zero, or this pins nothing");
652
- assert.equal(r.json.verdict, "soft-hit", "a hit set with no scoring row is not a duplicate finding");
653
- assert.equal(r.status, 0, "honouring it as exit 3 is what dropped a real deferral");
654
- assert.equal(r.json.tracker.hits.length, 3, "the rows stay in the payload — they are the caller's evidence, not noise to hide");
655
- assert.doesNotMatch(r.stderr, /TRACKER HIT/, "stderr is the channel read first; a hard-stop word over advisory rows is the trap itself");
656
- assert.match(r.stderr, /score 0\.00/, "the score the verdict was derived from has to be visible where the rows are");
657
- assert.match(r.stderr, /SOFT HIT/, "the verdict's own stderr line is pinned here like every neighbouring verdict's is");
658
- });
659
-
660
- // The measured self-check: a subject whose tracker rows all score 0.00 while a
661
- // filed row scores well above the soft-hit floor. Reported `tracker-hit` naming the
662
- // unrelated rows, with the genuinely adjacent one sitting in `near`.
663
- const UNREL_HITS = [
664
- { number: 149, title: "run-merge-bot force-push clobbers a rebased branch", state: "OPEN", url: "https://github.com/feigi/claude-config/issues/149" },
665
- { number: 39, title: "cockpit concurrency limit is not honoured", state: "OPEN", url: "https://github.com/feigi/claude-config/issues/39" },
666
- ];
667
- const NEAR_231 = "#231 ledger check emits verdict clean when the ledger file was never read";
668
- const VERDICT_SUBJECT = "ledger check verdict ignores the near-miss rows it prints";
669
-
670
- test("a near row above the soft-hit floor outranks a clean verdict (#388)", () => {
671
- const r = run(VERDICT_SUBJECT, { filed: [NEAR_231], hits: [] });
672
- assert.equal(r.json.found, false, "the near row is not a subset match, or the exact path answers before the verdict does");
673
- assert.ok(r.json.near[0].score >= 0.2, `the fixture must clear the soft-hit floor, got ${r.json.near[0].score}`);
674
- assert.equal(r.json.verdict, "soft-hit", "clean printed above a row naming the right issue is the defect");
675
- assert.equal(r.status, 0, "a near-miss stays advisory — it never became a stop");
676
- assert.match(r.stderr, /near-miss/);
677
- assert.match(r.stderr, /SOFT HIT/, "the verdict's own stderr line is pinned here like every neighbouring verdict's is");
678
- });
679
-
680
- test("score-0 tracker rows and a scoring near row read as one soft hit (#388)", () => {
681
- const r = run(VERDICT_SUBJECT, { filed: [NEAR_231], hits: UNREL_HITS });
682
- assert.equal(r.json.verdict, "soft-hit", "both measured directions land on the same advisory answer");
683
- assert.equal(r.status, 0);
684
- assert.equal(r.json.tracker.hits.length, 2, "the unrelated rows are still reported");
685
- assert.ok(r.json.near[0].score >= 0.2, "and the row that actually matched is still ranked");
686
- });
687
-
688
- test("a genuinely novel subject is still clean at exit 0 — the control (#388)", () => {
689
- // A near row BELOW the soft-hit floor, not an empty ranking: with no scoring row at
690
- // all the clean answer holds however the soft-hit floor moves, and the control pins
691
- // nothing. This one scores under the soft-hit floor and must not promote.
692
- const r = run("worktree reap declines a detached checkout it should have released", {
693
- filed: ["#901 the cockpit board renders a stale checkout of the pool"],
694
- hits: [],
695
- });
696
- assert.equal(r.json.verdict, "clean", "every check becoming a soft hit is the cost of getting this wrong");
697
- assert.equal(r.status, 0);
698
- assert.ok(r.json.near.length === 1 && r.json.near[0].score > 0 && r.json.near[0].score < 0.2,
699
- `the fixture must sit below the soft-hit floor and above zero, got ${JSON.stringify(r.json.near)}`);
700
- });
701
-
702
- test("a near row scoring exactly at the soft-hit floor is a soft hit (#388)", () => {
703
- // The control above sits below the soft-hit floor and the promoting fixture above it
704
- // scores 0.38, so nothing else in this file lands ON 0.2. Without this pair
705
- // the soft-hit floor's VALUE and its INCLUSIVITY are both free: `>=` can become `>`,
706
- // and 0.2 can be retuned upward, with the suite green either way.
707
- const r = run("quorum drains under retry backoff", {
708
- filed: ["#902 quorum vanishes without warning during nightly compaction"],
709
- hits: [],
710
- });
711
- assert.equal(r.json.found, false);
712
- assert.equal(r.json.near[0].score, 0.2, `the fixture must sit ON the soft-hit floor, got ${r.json.near[0].score}`);
713
- assert.equal(r.json.verdict, "soft-hit", "the soft-hit floor is inclusive — the docs promise 'at or above'");
714
- assert.equal(r.status, 0);
715
- });
716
-
717
- test("a tracker row that really scores still blocks at exit 3 (#388)", () => {
718
- const scoring = {
719
- number: 388,
720
- title: "ledger check verdict ignores near-miss rows",
721
- state: "OPEN",
722
- url: "https://github.com/feigi/claude-config/issues/388",
723
- };
724
- const r = run(VERDICT_SUBJECT, { filed: [], hits: [...UNREL_HITS, scoring] });
725
- assert.equal(r.json.tracker.hits[0].number, 388, "the scoring row ranks first, whatever order gh returned");
726
- assert.ok(r.json.tracker.hits[0].score > 0);
727
- assert.equal(r.json.verdict, "tracker-hit", "suppressing the zero rows must not suppress the row beside them");
728
- assert.equal(r.status, 3, "the blocking exit code is unchanged for a hit that scores");
729
- assert.match(r.stderr, /TRACKER HIT/);
730
- });
731
-
732
- // ── The ledger's own readability (#231) ──────────────────────────────────────
733
- //
734
- // `tracker.ok` reports whether the tracker half was read. The ledger half had
735
- // no such field, so a run whose ledger file does not exist emitted a payload
736
- // identical in every field to one that read the ledger and found nothing
737
- // filed — `clean` on both, exit 0 on both. Only stderr told them apart, which
738
- // a consumer parsing the payload cannot see.
739
- //
740
- // The verdict deliberately stays `clean` on both arms: `.fleet/` is gitignored
741
- // and created lazily by save(), so a fresh clone's first `check` legitimately
742
- // has no file to read, and folding that into the verdict would report the
743
- // normal case as unverified.
744
-
745
- const UNFILED_SUBJECT = "postgres connection pooling exhausted under load";
746
-
747
- test("a ledger that was never read is named as such, and nothing else about the answer moves (#231)", () => {
748
- // One subject for both runs: `subject` and the derived `tracker.query` ride
749
- // in the payload, so a differing subject would defeat the comparison below.
750
- const unread = run(UNFILED_SUBJECT, { ledgerDirExists: false });
751
- const read = run(UNFILED_SUBJECT, { filed: [] });
752
-
753
- assert.equal(unread.json.ledger.ok, false, "a ledger file that does not exist was never read, and the payload must say so");
754
- assert.equal(read.json.ledger.ok, true, "a ledger that was read reports so even when it held nothing filed");
755
-
756
- // The whole point of the field: these two payloads were identical, so
757
- // anything weaker than "differs here and nowhere else" leaves the caller
758
- // reconstructing the answer from stderr again.
759
- assert.deepEqual(
760
- { ...unread.json, ledger: null },
761
- { ...read.json, ledger: null },
762
- "the readability flag is the ONLY difference between an unread ledger and one read empty",
763
- );
764
-
765
- // PR #225 made the exit code a pure function of `verdict`, so a field added
766
- // beside it is only safe once both are pinned on the arm it lands on.
767
- for (const r of [unread, read]) {
768
- assert.equal(r.json.verdict, "clean", "naming the unread ledger must not mint a new verdict");
769
- assert.equal(r.status, 0, "and must not move the exit code");
770
- }
771
-
772
- // The warning already stated this consequence in words; the field is what
773
- // makes the machine-readable half agree with it rather than contradict it.
774
- assert.match(unread.stderr, /WARNING — ledger file not found/);
775
- assert.doesNotMatch(read.stderr, /ledger file not found/);
776
- });
777
-
778
- test("an unread ledger still reports the tracker hit at its own exit code (#231)", () => {
779
- // The blocking arm, where a perturbation costs most: exit 3 comes from the
780
- // verdict alone, so the new field has to be shown not to reach it here.
781
- const r = run("Non-zero column audit 11 rows", { ledgerDirExists: false, hits: [HIT_114] });
782
- assert.equal(r.json.ledger.ok, false, "a tracker hit says nothing about whether the ledger was read");
783
- assert.equal(r.json.verdict, "tracker-hit");
784
- assert.equal(r.status, 3, "the blocking exit code is unchanged by the new field");
785
- });
786
-
787
- test("the already-filed payload names the ledger it read, and stays exit 1 (#231)", () => {
788
- // The other payload `check` emits. A consumer testing `!payload.ledger.ok`
789
- // reads a missing field as falsy — "never read" — on the one answer that
790
- // proves the ledger WAS read, so the field cannot be scoped to one arm.
791
- const r = run("Non-zero column audit 11 rows", { filed: [FILED_114] });
792
- assert.equal(r.status, 1, "the strong signal is unchanged");
793
- assert.equal(r.json.verdict, "already-filed");
794
- assert.equal(r.json.ledger.ok, true, "a matched row can only have come from a ledger that was read");
795
- });
796
-
797
- // The other half of the same question, and the half the field got wrong when
798
- // it was first added: `--file` landing on a file that EXISTS but is not a
799
- // ledger — a typo resolving to a real neighbouring path, or a ledger whose
800
- // header lost a byte. An existence probe answers "read it" for both, which is
801
- // a machine-readable claim that is simply false, and the arm it is false on is
802
- // the one where the intact ledger says ALREADY FILED (#231).
803
- test("a --file that exists but does not parse as a ledger is not reported as read (#231)", () => {
804
- const notALedger = run(UNFILED_SUBJECT, { ledgerBody: "not a ledger at all\n" });
805
- assert.equal(notALedger.json.ledger.ok, false, "a file that is not a ledger was never read AS one, whatever stat() says");
806
-
807
- // One byte. This is the fixture that separates a parse from a stat: every
808
- // other property of the file is intact.
809
- const mangled = run("Non-zero column audit 11 rows", { ledgerBody: ledgerText([FILED_114]).replace("## Filed", "##Filed") });
810
- assert.equal(mangled.json.ledger.ok, false, "a corrupt header means the filed rows were never read, and the payload must say so");
811
- assert.equal(mangled.json.found, false, "the corrupt header is WHY nothing matched — the subject is one the intact ledger answers already-filed");
812
-
813
- // The two halves answer different questions now, so the warning must not
814
- // start claiming absence for a file that is sitting right there.
815
- for (const r of [notALedger, mangled]) assert.doesNotMatch(r.stderr, /ledger file not found/);
816
-
817
- // --require-file's contract is absence, not shape. Gating it on the parse
818
- // would turn these runs into exit 2 — a caller-visible change #231 does not
819
- // authorise — so it is pinned here rather than left to drift.
820
- const required = run(UNFILED_SUBJECT, { ledgerBody: "not a ledger at all\n", args: ["--require-file"] });
821
- assert.equal(required.status, 0, "--require-file still gates on absence alone");
822
- assert.equal(required.json.ledger.ok, false, "and the field still reports the parse, under --require-file too");
823
- });
824
-
825
- // The human-readable half of the same gap (#817): the test above pins that
826
- // stderr must NOT claim absence for two of these three shapes (`notALedger`
827
- // and `mangled` — the empty-file case is new here), but until now it pinned
828
- // only silence past that — no line at all told an operator watching a
829
- // terminal that their `--file` opened something that did not parse. `ok`
830
- // already answers false for all three; this checks the second, differently
831
- // worded line that says so out loud and names the path.
832
- test("--file pointing at an existing-but-unparseable file now warns on stderr, worded apart from the absent-file case (#817)", () => {
833
- const notALedger = run(UNFILED_SUBJECT, { ledgerBody: "not a ledger at all\n" });
834
- const mangled = run("Non-zero column audit 11 rows", { ledgerBody: ledgerText([FILED_114]).replace("## Filed", "##Filed") });
835
- // 0 bytes: `ledgerBody` bypasses ledgerText()'s always-structured output
836
- // (`??` only falls back on null/undefined, not on ""), so this is the one
837
- // fixture ledgerText() itself cannot produce.
838
- const empty = run(UNFILED_SUBJECT, { ledgerBody: "" });
839
-
840
- for (const r of [notALedger, mangled, empty]) {
841
- assert.equal(r.json.ledger.ok, false, "unchanged by this ticket — the machine-readable half already reported these as unread (#231)");
842
- assert.match(r.stderr, /WARNING/, "the human-readable half must now say something went wrong too");
843
- assert.match(r.stderr, /ledger\.md/, "the warning must name the path it opened");
844
- assert.doesNotMatch(r.stderr, /ledger file not found/, "the file exists — reusing the absent-file wording would be a fresh false claim on this half");
845
- }
846
-
847
- // The control: a real, parseable ledger must not trip the new line. Widening
848
- // the condition past "did not parse" — firing on every check regardless of
849
- // shape — would be a fresh false claim in the other direction, on a file
850
- // that parsed fine.
851
- const valid = run(UNFILED_SUBJECT, { filed: [] });
852
- assert.equal(valid.json.ledger.ok, true);
853
- assert.doesNotMatch(valid.stderr, /does not look like a ledger/, "a real, parseable ledger must not trip the new warning");
854
- });
855
-
856
- test("gh failing degrades to the ledger-only answer and never reads as a bare safe-to-file", () => {
857
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], ghFails: true });
858
- assert.equal(r.status, 0, "offline must not block filing — it degrades, per the ledger-only answer");
859
- assert.equal(r.json.tracker.ok, false);
860
- assert.equal(r.json.tracker.hits, undefined, "hits must be absent, not [], on a failure arm — a consumer testing .length must fail loudly, not read this as clean");
861
- assert.equal(r.json.verdict, "unverified");
862
- assert.match(r.json.tracker.error, /\S/, "the failure reason must reach the caller");
863
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
864
- // The exact fail-open this guards: a stderr line that reads like a clean bill
865
- // of health when the tracker was never consulted at all.
866
- assert.doesNotMatch(r.stderr, /^ledger: not previously filed$/m);
867
- });
868
-
869
- test("gh missing from PATH entirely degrades the same way", () => {
870
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], gh: false });
871
- assert.equal(r.status, 0);
872
- assert.equal(r.json.tracker.ok, false);
873
- assert.equal(r.json.tracker.hits, undefined, "gh ENOENT is the same failure arm — hits stays absent");
874
- assert.equal(r.json.verdict, "unverified");
875
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
876
- assert.doesNotMatch(r.stderr, /^ledger: not previously filed$/m);
877
- });
878
-
879
- test("gh exiting 0 with unparseable stdout is a failed read, not a clean tracker", () => {
880
- // gh can succeed and still print something that is not the JSON asked for — a
881
- // first-run banner, a deprecation notice. Parsing lives inside the try for
882
- // exactly this reason. Treating the parse failure as an empty hit list would
883
- // report a tracker that was never actually read as clean, which is the #145
884
- // fail-open one layer up.
885
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], ghGarbage: true });
886
- assert.equal(r.status, 0, "it still degrades rather than blocking the filing");
887
- assert.equal(r.json.tracker.ok, false, "an unparseable payload is NOT a clean tracker");
888
- assert.equal(r.json.tracker.hits, undefined, "an unread tracker must not be representable as an empty result set");
889
- assert.equal(r.json.verdict, "unverified");
890
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
891
- assert.doesNotMatch(r.stderr, /found no related issues/, "never claim the tracker was searched clean");
892
- });
893
-
894
- // The tests below pin what `tracker.error` CARRIES, not merely that it is
895
- // present. `execFileSync` runs gh with an explicit `stdio` that does not
896
- // forward the child's stderr, so this field is the only copy of the cause that
897
- // exists anywhere — a cause dropped here is dropped for good (#638).
898
- //
899
- // Each asserts `verdict` and `tracker.ok` as well: this arm's contract is that
900
- // only the diagnostic prose moves, and the dedupe guard's whole payload reads
901
- // off those two fields.
902
-
903
- test("a gh stderr that overruns the cap keeps the end, where the cause is, and says it was cut", () => {
904
- // gh prints its warnings before the error that killed it, so keeping the
905
- // FIRST bytes throws the cause away and hands back a string cut mid-word
906
- // that reads as complete.
907
- const noise = Array.from({ length: 40 }, (_, i) => `gh: warning line ${i + 1} ${"-".repeat(60)}`).join("\n");
908
- const r = run(UNFILED_SUBJECT, { filed: [], ghStderr: `${noise}\ngh: FATAL — HTTP 403 rate limit exceeded, resets at 14:02 UTC\n` });
909
- assert.equal(r.status, 0, "an unreadable tracker still degrades rather than blocking the filing");
910
- assert.equal(r.json.tracker.ok, false);
911
- assert.equal(r.json.verdict, "unverified");
912
- assert.match(r.json.tracker.error, /FATAL — HTTP 403 rate limit exceeded/, "the error gh actually died of must survive the cap");
913
- assert.match(r.json.tracker.error, /^…/, "a clipped string with no marker reads as the whole of what gh printed");
914
- // Still capped. The field ships on stdout inside a machine-parsed contract,
915
- // so unbounded gh stderr in it is a payload problem however the cause is
916
- // chosen — 500 is the ceiling the script names, marker included.
917
- assert.ok(r.json.tracker.error.length <= 500, `the cause must stay bounded, got ${r.json.tracker.error.length}`);
918
- // Astral input too. The cap is on `.length`, which counts UTF-16 code UNITS,
919
- // so a tail sliced by code POINTS keeps up to twice as many — measured 999
920
- // under the remedy proposed for the lone surrogate this cut can leave behind.
921
- // The ASCII fixture above cannot see that: there one code point is one code
922
- // unit, and the suite stays green while the payload ships 999 characters.
923
- const astral = run(UNFILED_SUBJECT, { filed: [], ghStderr: "\u{1F525}".repeat(400) });
924
- assert.ok(astral.json.tracker.error.length <= 500, `the cap counts code units, got ${astral.json.tracker.error.length}`);
925
- });
926
-
927
- test("a gh that fails with a whitespace-only stderr still names a cause", () => {
928
- // Whitespace-only stderr is truthy, so it wins a choice made before the trim
929
- // and then trims away to nothing — the warning line then has an empty
930
- // parenthesis where the reason belongs, and exit 0 carries no cause at all.
931
- const r = run(UNFILED_SUBJECT, { filed: [], ghStderr: "\n \n" });
932
- assert.equal(r.status, 0);
933
- assert.equal(r.json.tracker.ok, false);
934
- assert.equal(r.json.verdict, "unverified");
935
- assert.doesNotMatch(r.stderr, /TRACKER NOT CHECKED \(\)/, "the warning must never print an empty cause");
936
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
937
- // Non-empty is not enough to pin the fall-through: the last-resort literal
938
- // satisfies that on its own, and measured, it does — with the choice made on
939
- // the raw values again, this test read green off that literal while the
940
- // reader had lost the command. Pin the thing only the thrown message can
941
- // supply: the argv gh was given.
942
- assert.match(
943
- r.json.tracker.error,
944
- /issue list --search/,
945
- "the cause must be the thrown message, which names the command that failed",
946
- );
947
- assert.doesNotMatch(
948
- r.json.tracker.error,
949
- /without saying why/,
950
- "the last resort is for a failure carrying no diagnostic anywhere, not for one whose message names the command",
951
- );
952
- });
953
-
954
- test("a gh stderr short enough to fit reaches the caller unchanged", () => {
955
- // The must-ACCEPT half: a marker on a string that was never cut is a fresh
956
- // false signal, and re-choosing the cause must not rewrite one that was
957
- // already fine.
958
- const r = run(UNFILED_SUBJECT, { filed: [], ghStderr: "gh: HTTP 403 rate limit exceeded, resets at 14:02 UTC\n" });
959
- assert.equal(r.json.tracker.ok, false);
960
- assert.equal(r.json.verdict, "unverified");
961
- assert.equal(
962
- r.json.tracker.error,
963
- "gh: HTTP 403 rate limit exceeded, resets at 14:02 UTC",
964
- "trimmed at the ends and otherwise exactly what gh printed",
965
- );
966
- });
967
-
968
- test("a gh stderr of exactly the cap reaches the caller unchanged — the cut is ABOVE CAUSE_MAX, not at it", () => {
969
- // The cap's own boundary, which every other fixture here misses by hundreds
970
- // of characters: the overrunning one is ~3400, the accept-unchanged one ~54.
971
- // So `>` to `>=` marks a cause as cut when nothing was cut, and measured,
972
- // that one-character mutation passes the entire suite.
973
- //
974
- // `printf '%s'` adds no newline and neither end of the fixture is
975
- // whitespace, so cause()'s trim is a no-op here and exactly CAUSE_MAX
976
- // characters reach the comparison. The em dash is one UTF-16 code unit, so
977
- // `.length` and the character count agree.
978
- const head = "gh: FATAL — HTTP 403 rate limit exceeded, resets at 14:02 UTC ";
979
- const exact = head + "-".repeat(500 - head.length - 1) + ".";
980
- assert.equal(exact.length, 500, "test setup: the fixture must BE the cap, or this pins nothing");
981
- const r = run(UNFILED_SUBJECT, { filed: [], ghStderr: exact });
982
- assert.equal(r.json.tracker.ok, false);
983
- assert.equal(r.json.verdict, "unverified");
984
- assert.equal(r.json.tracker.error, exact, "a cause exactly at the cap is not over it — nothing cut, nothing marked");
985
- });
986
-
987
- test("a gh that hangs after printing names the timeout, not whatever it last warned about", () => {
988
- // Costs the full 20 s the script waits, and cannot cost less: that timeout is
989
- // execFileSync's own, on the parent side, so no stub can shorten it. It buys
990
- // the one failure class where this catch's ordering is observable at all —
991
- // every other abort Node performs leaves `e.stderr` undefined, so the thrown
992
- // message wins there whichever field is asked for first.
993
- //
994
- // Measured before this pin existed: this exact shape reported
995
- // `tracker.error = "gh: warning: using cached credentials for github.com"`
996
- // and named the 20-second stall nowhere, in the payload or in the operator
997
- // warning (#638).
998
- const r = run(UNFILED_SUBJECT, { filed: [], ghHang: "gh: warning: using cached credentials for github.com\n" });
999
- assert.equal(r.status, 0, "a hung tracker still degrades rather than blocking the filing");
1000
- assert.equal(r.json.tracker.ok, false);
1001
- assert.equal(r.json.verdict, "unverified");
1002
- assert.match(
1003
- r.json.tracker.error,
1004
- /ETIMEDOUT/,
1005
- "the abort is named in the thrown message alone; a stray warning on stderr must not stand in for it",
1006
- );
1007
- });
1008
-
1009
- test("a filed row contained in a longer subject scores on the smaller set, not the union", () => {
1010
- // Pins the overlap coefficient against Jaccard and against dividing by the
1011
- // larger set: either would dilute a fully-contained row toward zero and the
1012
- // ranking would stop discriminating. Swapping Math.min for Math.max here
1013
- // otherwise reds nothing in this file.
1014
- const r = run("the merge loop exit 2 behaviour is undocumented in run-merge-bot.md and elsewhere", {
1015
- filed: ["#1 merge loop exit"],
1016
- });
1017
- assert.equal(r.json.near[0].score, 1, "a fully contained filed row scores 1.0");
1018
- });
1019
-
1020
- test("gh returning JSON of the wrong shape is a failed read, not a tracker hit", () => {
1021
- // Parsing succeeded, so the parse guard above does not fire — but the rows are
1022
- // not issues. Reported as hits, this escalates to exit 3 and prints
1023
- // "TRACKER HIT — #undefined", blocking a filing on an answer nobody can read.
1024
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], hits: [1, 2, 3] });
1025
- assert.equal(r.status, 0, "an unreadable answer must not escalate to a tracker hit");
1026
- assert.equal(r.json.tracker.ok, false);
1027
- assert.equal(r.json.tracker.hits, undefined, "wrong-shape output is the same failure arm — hits stays absent");
1028
- assert.equal(r.json.verdict, "unverified");
1029
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
1030
- assert.doesNotMatch(r.stderr, /TRACKER HIT/);
1031
- assert.doesNotMatch(r.stderr, /undefined/, "never print a hit the payload cannot describe");
1032
- });
1033
-
1034
- test("a tracker row carrying only an issue number is a failed read, not a tracker hit", () => {
1035
- // The sibling above feeds bare integers, which `!h` and the issue-number check
1036
- // already rejected before this ticket — so it could never reach the case that
1037
- // motivated the invariant it asserts. This one can: an object row passes both
1038
- // of those and still cannot describe itself, because the hit line interpolates
1039
- // the state and the url too. Left unvalidated it printed
1040
- // "TRACKER HIT — #114 (undefined) — undefined" at the blocking exit code (#232).
1041
- const r = run("candidates.mjs row states the opposite of its code", { filed: [], hits: [{ number: 114 }] });
1042
- assert.equal(r.status, 0, "a row the payload cannot describe must not escalate to a tracker hit");
1043
- assert.equal(r.json.tracker.ok, false);
1044
- assert.equal(r.json.tracker.hits, undefined, "a partial row is the same failure arm — hits stays absent");
1045
- assert.equal(r.json.verdict, "unverified");
1046
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
1047
- assert.doesNotMatch(r.stderr, /TRACKER HIT/);
1048
- assert.doesNotMatch(r.stderr, /undefined/, "never print a hit the payload cannot describe");
1049
- });
1050
-
1051
- // Both fields at once is what the sibling above feeds, and that is precisely
1052
- // what it cannot pin: either surviving half of the predicate still rejects a row
1053
- // missing both, so dropping ONE `typeof` check leaves the whole suite green
1054
- // while production prints "TRACKER HIT — #114 (undefined)" or "— undefined" at
1055
- // the blocking exit code — the #232 defect itself, back with nothing red (#232).
1056
- // One row per field is what makes each half individually mutation-killable.
1057
- for (const [missing, drop] of [["state", ({ state: _s, ...rest }) => rest], ["url", ({ url: _u, ...rest }) => rest]]) {
1058
- test(`a tracker row missing only its ${missing} is a failed read, not a tracker hit`, () => {
1059
- const r = run("Non-zero column audit 11 rows", { filed: [], hits: [drop(HIT_114)] });
1060
- assert.equal(r.status, 0, `a row without ${missing} cannot describe itself and must not escalate`);
1061
- assert.equal(r.json.tracker.ok, false);
1062
- assert.equal(r.json.tracker.hits, undefined, "one field short is the same failure arm — hits stays absent");
1063
- assert.equal(r.json.verdict, "unverified");
1064
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
1065
- assert.doesNotMatch(r.stderr, /TRACKER HIT/);
1066
- assert.doesNotMatch(r.stderr, /undefined/, "never print a hit the payload cannot describe");
1067
- });
1068
- }
1069
-
1070
- test("a tracker row missing only its title is still reported, not degraded to unverified", () => {
1071
- // The other half of the guard above, and the reason it stops where it does.
1072
- // `title` is the one interpolated field with a defined absent-value — the row
1073
- // builder substitutes `h.title || ""` for it in the row and in the score alike
1074
- // — so this row is fully describable and refusing it would trade a real
1075
- // tracker read for a non-answer. Without this pin a later "tighten the guard"
1076
- // pass adds `title` to the predicate and nothing goes red (#232).
1077
- //
1078
- // Where it lands changed with #388: no title is no tokens, so the row scores
1079
- // 0.00 and the answer is the advisory one rather than the blocking one. The
1080
- // row is still read, still described and still shipped — which is the whole
1081
- // of what #232 asked for. What it must never be is `unverified`.
1082
- const { title: _title, ...noTitle } = HIT_114;
1083
- const r = run("Non-zero column audit 11 rows", { filed: [], hits: [noTitle] });
1084
- assert.equal(r.status, 0, "an unscoreable row is rows to read, not a duplicate finding");
1085
- assert.equal(r.json.tracker.ok, true);
1086
- assert.equal(r.json.verdict, "soft-hit");
1087
- assert.equal(r.json.tracker.hits[0].number, 114);
1088
- assert.equal(r.json.tracker.hits[0].title, "", "the absent title reaches the row as the builder's substitute");
1089
- assert.equal(r.json.tracker.hits[0].state, "OPEN");
1090
- assert.equal(r.json.tracker.hits[0].score, 0, "no title is no tokens to score, which the overlap treats as no overlap");
1091
- assert.match(r.stderr, /TRACKER ROW — #114 \(OPEN, score 0\.00\)/, "the row still reaches stderr, describing itself and its score");
1092
- assert.doesNotMatch(r.stderr, /undefined/, "an empty title is not an undescribable one");
1093
- });
1094
-
1095
- test("a ledger hit short-circuits: gh is never invoked", () => {
1096
- const r = run("Non-zero column audit 11 rows", { filed: [FILED_114], hits: [HIT_114] });
1097
- assert.equal(r.status, 1);
1098
- assert.equal(r.ghRan, false, "exit 1 already stops the filing; the query cannot change the answer");
1099
- });
1100
-
1101
- test("a subject with no distinctive terms is never sent as an empty search", () => {
1102
- // `gh issue list --search ""` matches every issue in the repo, which would
1103
- // report every such subject as a tracker hit. Not searching is the honest
1104
- // answer, and it still may not read as safe.
1105
- const r = run("the of it", { filed: [], hits: [HIT_114] });
1106
- assert.equal(r.ghRan, false);
1107
- assert.equal(r.json.tracker.ok, false);
1108
- assert.equal(r.json.tracker.hits, undefined, "the no-distinctive-terms arm is the other construction site for `tracker` — hits stays absent there too");
1109
- assert.equal(r.json.verdict, "unverified");
1110
- assert.match(r.stderr, /TRACKER NOT CHECKED/);
1111
- assert.equal(r.status, 0);
1112
- });
1113
-
1114
- test("the search query carries at most three sanitised terms and no qualifiers", () => {
1115
- // `is:open` and `candidates.mjs:164` must not reach gh as search qualifiers —
1116
- // they would silently change what was searched for. A fourth term is dropped
1117
- // by design: gh ANDs terms, so the least distinctive one can only subtract
1118
- // (measured — adding it loses #114, the issue this feature exists to catch).
1119
- const r = run("candidates.mjs:164 is:open states the opposite of its code", { filed: [] });
1120
- const query = r.ghArgv[r.ghArgv.indexOf("--search") + 1];
1121
- assert.doesNotMatch(query, /:/, "a colon would let a subject smuggle a search qualifier into the query");
1122
- const terms = query.split(" ").filter(Boolean);
1123
- assert.ok(terms.length <= 3, `expected at most 3 terms, got ${terms.length}: ${query}`);
1124
- const subjectWords = "candidates mjs 164 is open states the opposite of its code".split(" ");
1125
- for (const t of terms) assert.ok(subjectWords.includes(t), `term '${t}' is not from the subject`);
1126
- assert.ok(r.ghArgv.includes("--state") && r.ghArgv.includes("all"), "closed issues are duplicates too");
1127
- });
1128
-
1129
- // ---------------------------------------------------------------------------
1130
- // Term selection (issue #153). Exact-equality pins, not <=3/subset checks —
1131
- // this is the regression gate the issue says did not exist: change the
1132
- // stoplist, the >= 3 floor, the sort, or the top-3 cut and one of these must
1133
- // go red. Each subject is one of the four the issue measured, kept verbatim
1134
- // so the pin is against the reported defect, not a paraphrase of it.
1135
- // ---------------------------------------------------------------------------
1136
-
1137
- test("term selection: a subject with no modal/negation/temporal noise is unchanged by the widened stoplist", () => {
1138
- // Ceiling, stated: longest-first still prefers long ordinary words over a
1139
- // short distinctive one. "postgres" (8) loses to "connection" (10) and its
1140
- // near-tied neighbours regardless of the stoplist — none of the displacing
1141
- // words are modal/negation/temporal, so widening STOP cannot reach this
1142
- // case. Frequency weighting is the named, not-attempted upgrade path.
1143
- const r = run("postgres connection pooling exhausted under sustained load", { filed: [] });
1144
- assert.equal(queryOf(r), "connection exhausted sustained");
1145
- });
1146
-
1147
- test("term selection: a modal and a negation no longer outrank the subject's content words", () => {
1148
- const r = run("the guard should never fail open on a fork", { filed: [] });
1149
- assert.equal(queryOf(r), "guard fail open", "was 'should guard never' before #153 widened STOP");
1150
- });
1151
-
1152
- test("term selection: erasing CI/PR is a stated ceiling, not something this issue fixes", () => {
1153
- // "CI" and "PR" are still dropped by the >= 3 floor — lowering it is
1154
- // explicitly out of scope (#153: it interacts with the whole stoplist and
1155
- // has no gate of its own). Widening STOP with a temporal ("still") is not
1156
- // enough on its own either: "but" is ordinary generic length-3 filler, not
1157
- // a modal/negation/temporal, so it is deliberately left unstopped and still
1158
- // wins the third slot.
1159
- const r = run("CI is red but the PR still merged", { filed: [] });
1160
- assert.equal(queryOf(r), "merged red but");
1161
- });
1162
-
1163
- test("term selection: the >= 3 floor itself is pinned, in both directions", () => {
1164
- // The header above claims a floor change must red one of these. It did not:
1165
- // the subject in the ceiling test is invariant under the floor, because `ci`
1166
- // and `pr` lose the longest-first top-3 cut to `merged`/`red`/`but` whether
1167
- // the floor is 3, 2 or 1 — so the whole block was vacuous for the one knob
1168
- // #153 names ("`>= 3` -> `>= 1` currently reds no test").
1169
- //
1170
- // This subject is not invariant: it has exactly two content words at length
1171
- // >= 3, so the third slot is EMPTY at the real floor and gets filled by the
1172
- // short `gh` the moment the floor drops. Measured on the pipeline: "fails
1173
- // cap" at 3, "fails cap gh" at both 2 and 1 — the assertion reds on any
1174
- // loosening, and a tightening to >= 4 drops `cap` and reds it too.
1175
- //
1176
- // `contentWords` in ledger.mjs is the single definition of that floor, so
1177
- // this one pin reaches the scoring path as well as the query path.
1178
- const r = run("gh CI cap fails", { filed: [] });
1179
- assert.equal(queryOf(r), "fails cap");
1180
- });
1181
-
1182
- test("term selection: a modal is dropped, but the freed slot goes to another long generic word", () => {
1183
- // "should" is still excluded by the widened STOP, but the freed slot goes
1184
- // to another long generic word ("drops"), not to the short, genuinely
1185
- // distinctive "cap" or "near"/"miss" — the same longest-first ceiling as
1186
- // the postgres case above, left honestly unfixed.
1187
- const r = run("the near-miss cap silently drops rows that should have surfaced", { filed: [] });
1188
- assert.equal(queryOf(r), "silently surfaced drops", "was 'silently surfaced should' before #153 widened STOP");
1189
- });
1190
-
1191
- test("term selection: near-miss scoring shares the same widened stoplist", () => {
1192
- // scoreTokens() and the tracker query terms both filter through STOP. Two
1193
- // subjects that use DIFFERENT modal/negation words ("should never" vs.
1194
- // "could still") share no raw token subset — isMatch() correctly misses —
1195
- // but must score as a full 1.0 near-miss once both sides' noise words drop
1196
- // out, or the widened stoplist is only reaching term selection, not scoring.
1197
- const r = run("the fix should never fail open on merge", { filed: ["#9 the fix could still fail open on merge"] });
1198
- assert.equal(r.json.found, false, "raw token sets differ (should/never vs could/still) — not a subset match");
1199
- assert.equal(r.json.near[0].score, 1, "'should'/'never'/'could'/'still' must not count as shared content words");
1200
- });
1201
-
1202
- test("a tracker search returning zero hits reports what was established, not a clean bill", () => {
1203
- // #153's ceiling paragraph: a searched-and-empty tracker is not the same
1204
- // claim as "no related issues" — the query is a 3-term heuristic that can
1205
- // itself be why nothing came back.
1206
- const r = run("postgres connection pooling exhausted under sustained load", { filed: [], hits: [] });
1207
- assert.equal(r.json.verdict, "clean", "the JSON contract from #152 is unchanged — only the prose changes");
1208
- assert.match(r.stderr, /returned no matches/);
1209
- assert.doesNotMatch(r.stderr, /found no related issues/, "must not assert the tracker itself is clean");
1210
- });
1211
-
1212
- test("the measured #114 rewording surfaces, weakly — it is the tracker query that catches this class", () => {
1213
- // Straight from the issue body: this subject describes the same defect as
1214
- // #114 and `check` reported it safe to file. Token overlap alone barely sees
1215
- // it (one shared content word), so the assertion is deliberately weak — it
1216
- // pins that the row is offered to the caller at all, and documents that
1217
- // near-miss scoring is NOT what covers the #114 class.
1218
- const r = run("candidates.mjs row states the opposite of its code", { filed: [FILED_114] });
1219
- assert.equal(r.json.found, false);
1220
- assert.ok(r.json.near.length >= 1, "the filed row should still be offered for the caller to judge");
1221
- assert.match(r.json.near[0].row, /^#114 /);
1222
- assert.ok(r.json.near[0].score > 0);
1223
- });
1224
-
1225
- // ---------------------------------------------------------------------------
1226
- // #155 — the tracker query binds to the ledger's own repository, not to
1227
- // this process's ambient cwd. `run()`'s spawned `ledger.mjs check` by default
1228
- // inherits the outer test-runner's cwd (this checkout), which is itself a
1229
- // different repository from the `git init`'d fixture directory the ledger
1230
- // lives in below — that mismatch IS the "unrelated working directory" the
1231
- // acceptance criteria call for, no second fixture repo needed.
1232
- // ---------------------------------------------------------------------------
1233
-
1234
- test("an explicit ledger inside a repository targets that ledger's repository, not the caller's cwd", () => {
1235
- const r = run("some distinctive subject words entirely", { filed: [], hits: [] });
1236
- assert.equal(r.ghRan, true);
1237
- assert.equal(
1238
- r.ghCwd,
1239
- r.ledgerRepoDir,
1240
- "gh must run from the ledger's own repository, not from wherever ledger.mjs's own process happened to start",
1241
- );
1242
- assert.notEqual(
1243
- r.ghCwd,
1244
- realpathSync(process.cwd()),
1245
- "sanity: the test runner's own cwd is a different repository from the fixture — otherwise this test cannot tell the fix from the bug it fixes",
1246
- );
1247
- });
1248
-
1249
- test("an explicit ledger outside any git repository reports the tracker unchecked, same shape as any other unread tracker", () => {
1250
- const r = run("some distinctive subject words entirely", { filed: [], hits: [], gitRepo: false });
1251
- assert.equal(r.ghRan, false, "no repository to bind to means gh is never invoked at all");
1252
- assert.equal(r.status, 0, "an unreadable tracker must never block filing — same exit-code contract as every other degrade");
1253
- assert.equal(r.json.tracker.ok, false);
1254
- assert.equal(r.json.tracker.hits, undefined, "hits stays absent, not [], on this arm too");
1255
- assert.equal(r.json.verdict, "unverified");
1256
- assert.match(
1257
- r.stderr,
1258
- /WARNING — TRACKER NOT CHECKED/,
1259
- "reuses the existing unchecked-tracker warning rather than inventing a second one",
1260
- );
1261
- // Pins the repository guard itself, not merely that SOMETHING degraded.
1262
- // Without this the guard is an equivalent mutant: delete it and `ghCwd`
1263
- // becomes "", `execFileSync` throws ENOENT on `cwd: ""` into the gh catch,
1264
- // and every assertion above still reads green off the identical
1265
- // `{ok:false}` shape. Measured: 29/29 passed with the guard removed.
1266
- assert.match(
1267
- r.json.tracker.error,
1268
- /cannot resolve the ledger's repository/,
1269
- "the failure must be attributed to the repository probe, not to gh",
1270
- );
1271
- assert.match(
1272
- r.json.tracker.error,
1273
- /not a git repository/,
1274
- "and it must carry git's OWN reason — the probe pipes git's stderr, so this string is the only place the cause is ever seen",
1275
- );
1276
- });
1277
-
1278
- test("a repository probe that fails behind an overrunning git stderr keeps the end, where the cause is", () => {
1279
- // #638's second call site, the one the ticket names alongside the gh catch.
1280
- // This probe pipes git's stderr too, so `tracker.error` is the only copy of
1281
- // it that exists anywhere. Real git puts the reason LAST — it echoes the
1282
- // offending input first and the line saying what actually killed it comes
1283
- // after — so keeping the FIRST bytes hands back the padding and drops the
1284
- // cause.
1285
- //
1286
- // Driven through the REAL git the fixture symlinks, in a directory that IS a
1287
- // repository: an oversized command-line config key. ledger.mjs scrubs
1288
- // GIT_DIR and GIT_WORK_TREE off this probe and nothing else, so a malformed
1289
- // ambient GIT_CONFIG_* reaches it — which is what makes the shape reachable
1290
- // in production and not merely constructible in a fixture.
1291
- //
1292
- // The two matches below are git's own wording. A git that words either
1293
- // differently reds here rather than degrading quietly, which is the
1294
- // direction to fail in.
1295
- const r = run(UNFILED_SUBJECT, {
1296
- filed: [],
1297
- spawnEnv: { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "z".repeat(600), GIT_CONFIG_VALUE_0: "x" },
1298
- });
1299
- assert.equal(r.ghRan, false, "the probe failed, so there is no repository for the query to bind to");
1300
- assert.equal(r.status, 0, "an unresolvable repository still degrades rather than blocking the filing");
1301
- assert.equal(r.json.tracker.ok, false);
1302
- assert.equal(r.json.verdict, "unverified");
1303
- assert.match(r.json.tracker.error, /cannot resolve the ledger's repository/, "attributed to the probe, not to gh");
1304
- assert.match(
1305
- r.json.tracker.error,
1306
- /unable to parse command-line config/,
1307
- "git's own last line is the cause — keeping the first bytes drops it for the echoed input ahead of it",
1308
- );
1309
- assert.match(r.json.tracker.error, /: …/, "a clipped cause with no marker reads as the whole of what git printed");
1310
- assert.doesNotMatch(r.json.tracker.error, /z{500}/, "the cause must stay bounded — 600 padding characters went in");
1311
- });
1312
-
1313
- test("a repository probe against a long ledger directory reports the WHOLE path, never cause()'s `…`-clipped form (#940)", () => {
1314
- // #940's own decision, pinned executably: the comment above the repository
1315
- // probe (ledger.mjs ~line 682) argues `tracker.error` must stay uncapped on
1316
- // the directory even though cause() — the helper that DOES cap, at
1317
- // CAUSE_MAX=500 — sits right there and would be the obvious thing to reach
1318
- // for. Capping the directory with cause() passes every other fixture in
1319
- // this file unchanged, because none of them builds a path anywhere near
1320
- // 500 characters. This one does, deliberately past CAUSE_MAX, so a
1321
- // regression that wraps `ledgerDir` in cause() is observable here: the
1322
- // directory would arrive `…`-prefixed with its root dropped, exactly the
1323
- // "reads like a path and is not one" damage the comment warns against.
1324
- //
1325
- // Built as real nested directories (not one long segment) so no OS
1326
- // path-component limit is hit, and deliberately never `git init`-ed so the
1327
- // probe fails and `tracker.error` is the only place this path is echoed.
1328
- const base = mkdtempSync(join(tmpdir(), "ledger-longpath-"));
1329
- let dir = base;
1330
- while (dir.length < 540) dir = join(dir, "a".repeat(40));
1331
- mkdirSync(dir, { recursive: true });
1332
- try {
1333
- const file = join(dir, "ledger.md");
1334
- writeFileSync(file, ledgerText([]));
1335
- const bin = join(base, "bin");
1336
- mkdirSync(bin, { recursive: true });
1337
- symlinkSync(REAL_GIT, join(bin, "git"));
1338
- const env = { ...process.env, PATH: bin };
1339
- delete env.GIT_DIR;
1340
- delete env.GIT_WORK_TREE;
1341
- const r = spawnSync(process.execPath, [SCRIPT, "--file", file, "check", "some distinctive subject words entirely"], {
1342
- encoding: "utf8",
1343
- env,
1344
- });
1345
- assert.equal(r.status, 0, "an unresolvable repository still degrades rather than blocking the filing");
1346
- const json = JSON.parse(r.stdout);
1347
- assert.equal(json.tracker.ok, false);
1348
- assert.ok(
1349
- dir.length > 500,
1350
- "sanity: the fixture directory must itself exceed CAUSE_MAX (500) or this test cannot tell cause() apart from no cap at all",
1351
- );
1352
- assert.ok(
1353
- json.tracker.error.includes(dir),
1354
- "the interpolated directory must arrive VERBATIM — cause() would have kept only its last CAUSE_MAX-1 characters",
1355
- );
1356
- assert.doesNotMatch(
1357
- json.tracker.error,
1358
- /\(…/,
1359
- "a `(…`-prefixed pseudo-path means cause() wrongly swallowed the directory and dropped its root, the #940 remedy this comment exists to rule out",
1360
- );
1361
- } finally {
1362
- rmSync(base, { recursive: true, force: true });
1363
- }
1364
- });
1365
-
1366
- test("the documented flow — no --file, run from inside the repo — is unchanged: tracker still gets checked", () => {
1367
- // defaultLedgerPath() resolves `.fleet/ledger.md` from --git-common-dir when
1368
- // no --file is given; `noFile` + `procCwd` drive that path instead of
1369
- // --file. This is the "must ACCEPT" pin: a normal invocation must not start
1370
- // reporting the tracker as unchecked just because #155 added a repository
1371
- // check to the diverging arm.
1372
- const r = run("some distinctive subject words entirely", { filed: [], hits: [], noFile: true });
1373
- assert.equal(r.ghRan, true, "the documented flow must still reach the tracker query");
1374
- assert.equal(r.json.tracker.ok, true);
1375
- assert.equal(r.json.verdict, "clean");
1376
- assert.doesNotMatch(r.stderr, /TRACKER NOT CHECKED/, "a normal invocation must not degrade");
1377
- assert.doesNotMatch(r.stderr, /cannot resolve the ledger's repository/, "the new guard must not fire on the documented flow");
1378
- });
1379
-
1380
- test("the documented flow on a FRESH clone — no --file, .fleet/ not created yet — still reaches the tracker query", () => {
1381
- // The accept-pin above pre-creates the ledger directory, so it cannot see
1382
- // this state — and this state is the normal one: `.fleet/` is gitignored
1383
- // (.gitignore) and created lazily by save()'s mkdirSync, so on every fresh
1384
- // clone or worktree it is absent until the run's first write, which `check`
1385
- // by definition precedes. `git -C <missing dir>` exits 128, so a probe
1386
- // aimed at the ledger's own directory read "no repository" and dropped the
1387
- // query outright — verdict clean -> unverified on the flow the fix promised
1388
- // to leave alone. This is the pin that fixture could not be.
1389
- const r = run("some distinctive subject words entirely", { noFile: true, ledgerDirExists: false });
1390
- assert.equal(r.ghRan, true, "a ledger directory that does not exist YET is still inside its repository");
1391
- assert.equal(r.json.tracker.ok, true);
1392
- assert.equal(r.json.verdict, "clean");
1393
- // The state the #231 ruling protects: this run legitimately has no ledger
1394
- // to read, so the flag says so — and the verdict still does not move.
1395
- assert.equal(r.json.ledger.ok, false, "a fresh clone's first check reports the ledger unread, not the run unverified (#231)");
1396
- assert.doesNotMatch(r.stderr, /TRACKER NOT CHECKED/);
1397
- assert.doesNotMatch(r.stderr, /cannot resolve the ledger's repository/);
1398
- assert.equal(r.ghCwd, r.ledgerRepoDir, "and the query is still bound to the ledger's own repository, not the runner's cwd");
1399
- });
1400
-
1401
- test("an inherited GIT_DIR or GH_REPO cannot retarget the query away from the ledger's repository", () => {
1402
- // Binding gh's cwd does not, on its own, make the ledger and the queried
1403
- // tracker agree — two env vars outrank the binding, from opposite sides:
1404
- //
1405
- // GIT_DIR/GIT_WORK_TREE outrank cwd for git, so an ambient one (a git
1406
- // hook, `rebase --exec`, `bisect run`) reached both the repository probe
1407
- // and gh unchanged and made gh's remote resolution answer for the other
1408
- // repository.
1409
- //
1410
- // GH_REPO is read by gh BEFORE it consults git at all, so the bound cwd
1411
- // is simply ignored — and this repo's own
1412
- // .github/workflows/release-label.yml exports it to every gh step.
1413
- //
1414
- // Either way the result is `ok: true` with `hits: []` on the wrong
1415
- // tracker — #155 straight back through its own fix. Each assertion below
1416
- // pins one of the three scrubs, and each fails alone.
1417
- const r = run("some distinctive subject words entirely", {
1418
- spawnEnv: { GIT_DIR: join(tmpdir(), "ledger-no-such-git-dir"), GH_REPO: "someowner/some-other-repo" },
1419
- });
1420
- assert.equal(r.ghRan, true, "the probe must not inherit GIT_DIR either — it resolves the repo gh is bound to");
1421
- assert.equal(r.ghEnv.GIT_DIR, "", "gh must see no GIT_DIR, or its remote resolution outranks the bound cwd");
1422
- assert.equal(r.ghEnv.GH_REPO, "", "gh must see no GH_REPO, which outranks the bound cwd outright");
1423
- assert.equal(r.ghCwd, r.ledgerRepoDir);
1424
- assert.equal(r.json.verdict, "clean");
1425
- });
1426
-
1427
- test("an inherited GIT_DIR cannot relocate defaultLedgerPath() into another repository (#1599)", () => {
1428
- // The three scrubs above protect the TRACKER query once ledger.mjs already
1429
- // knows which ledger to read. defaultLedgerPath() itself — the call that
1430
- // decides that in the first place, exercised only on this documented
1431
- // no-`--file` flow — passed no env at all until #1599: an ambient GIT_DIR
1432
- // answers `--git-common-dir` for a DIFFERENT repository, and ledger.mjs
1433
- // resolves `.fleet/ledger.md` underneath THAT answer instead of the
1434
- // caller's own. Measured directly against a checkout of this repo:
1435
- // `GIT_DIR=/tmp/other/.git node ledger.mjs row 357 "…"` wrote
1436
- // `/tmp/other/.fleet/ledger.md`, silently, at exit 0.
1437
- //
1438
- // The fixture: a row already sitting in the CALLER's own ledger. Relocated,
1439
- // `check` reads an empty (or wholly absent) ledger at the wrong path and
1440
- // reports the subject safe to file — #155's "confident, empty result"
1441
- // shape, one call earlier in this same file.
1442
- const otherRepo = mkdtempSync(join(tmpdir(), "ledger-other-repo-"));
1443
- try {
1444
- const initOther = spawnSync("git", ["init", "-q"], { cwd: otherRepo, stdio: "ignore" });
1445
- assert.equal(initOther.status, 0,
1446
- "test setup: the OTHER repository the ambient var points at must itself be real — an unresolvable GIT_DIR takes the pre-existing cwd-relative fallback instead, which is the different code path the test above this one pins");
1447
- const r = run("some distinctive subject words entirely", {
1448
- filed: ["#357 some distinctive subject words entirely"],
1449
- noFile: true,
1450
- spawnEnv: { GIT_DIR: join(otherRepo, ".git") },
1451
- });
1452
- assert.equal(r.json.found, true,
1453
- "the subject IS already filed in the caller's own ledger — an ambient GIT_DIR must not make defaultLedgerPath() read a different one");
1454
- assert.equal(r.json.verdict, "already-filed");
1455
- assert.equal(r.status, 1);
1456
- } finally {
1457
- rmSync(otherRepo, { recursive: true, force: true });
1458
- }
1459
- });
1460
-
1461
- test("defaultLedgerPath(): an ambient GIT_COMMON_DIR is not canonicalised — this caller does not opt in (#1658)", () => {
1462
- // git-env.mjs's own docstring: `canonicalise` is board.mjs's opt-in alone
1463
- // (#1582, a symlinked cockpit route deriving a second port); ledger.mjs
1464
- // stays on the default because `check` PRINTS the path it resolves — the
1465
- // "ledger file not found" warning below — and realpath would change that
1466
- // output without changing which file it names. board.test.mjs pins
1467
- // board.mjs's OPPOSITE choice; git-env.test.mjs pins the HELPER's own
1468
- // default, which cannot see whether THIS caller opted in — nothing before
1469
- // this test pinned that fact, so an accidental `{ canonicalise: true }`
1470
- // added to defaultLedgerPath() would break no test in this file.
1471
- const root = mkdtempSync(join(tmpdir(), "ledger-ws-link-"));
1472
- try {
1473
- const real = join(root, "repo");
1474
- assert.equal(spawnSync("git", ["init", "-q", real], { stdio: "ignore" }).status, 0);
1475
- const link = join(root, "link");
1476
- symlinkSync(real, link);
1477
- const r = run("some distinctive subject words entirely", {
1478
- noFile: true,
1479
- spawnEnv: { GIT_COMMON_DIR: join(link, ".git") },
1480
- });
1481
- const expected = `ledger file not found: ${join(link, ".fleet", "ledger.md")}`;
1482
- assert.ok(r.stderr.includes(expected),
1483
- `defaultLedgerPath() must keep the symlinked spelling — canonicalising here is board.mjs's opt-in alone. stderr: ${r.stderr}`);
1484
- } finally { rmSync(root, { recursive: true, force: true }); }
1485
- });
1486
-
1487
- test("a working directory that is not a repository at all still degrades exactly as before (no --file)", () => {
1488
- // defaultLedgerPath()'s own pre-existing fallback: --git-common-dir fails,
1489
- // so it warns and returns a cwd-relative path — which #155 leaves alone
1490
- // (out of scope: changing ledger path resolution). The tracker query then
1491
- // finds no repository either, for the same underlying reason, and degrades
1492
- // through the identical `!tracker.ok` branch as the outside-any-repo case.
1493
- const dir = mkdtempSync(join(tmpdir(), "ledger-noreop-"));
1494
- try {
1495
- // `gitRepo: false`: `procCwd` moves ledger resolution to `dir`, so the
1496
- // fixture's own repo and ledger are never consulted — git-initialising it
1497
- // would only imply it were part of what this test pins.
1498
- const r = run("some distinctive subject words entirely", { filed: [], hits: [], noFile: true, gitRepo: false, procCwd: dir });
1499
- assert.equal(r.ghRan, false);
1500
- assert.equal(r.status, 0);
1501
- assert.equal(r.json.tracker.ok, false);
1502
- assert.match(r.stderr, /could not resolve --git-common-dir/, "defaultLedgerPath()'s own existing warning still fires");
1503
- assert.match(r.stderr, /WARNING — TRACKER NOT CHECKED/);
1504
- } finally {
1505
- rmSync(dir, { recursive: true, force: true });
1506
- }
1507
- });
1508
-
1509
- // The design spec's script-surface row advertised `set/filed/ruled/read`: a
1510
- // subcommand that has never existed, and two real ones — `row` and `check` —
1511
- // left out, `check` being the entire subject of that same row's
1512
- // `Non-zero when` cell (#48). Derived from the script's own dispatch rather
1513
- // than a hand-written list, for the reason the table proves: a list typed here
1514
- // drifts from the script exactly the way the table did. The three other
1515
- // hand-typed copies of the list — the row, the usage line, and the
1516
- // unknown-subcommand die() message — are all measured against that dispatch
1517
- // below.
1518
- test("the design spec's script-surface row admits exactly the subcommands ledger.mjs accepts", () => {
1519
- // Read off the dispatch, not the usage line. The usage line is itself a
1520
- // hand-typed list, so deriving the "real" set from it compares one doc-string
1521
- // against another: a branch added to the dispatch without a usage edit left
1522
- // this pin green while the script accepted a subcommand neither the usage line
1523
- // nor the row named (measured). The dispatch is the only thing that decides
1524
- // which subcommand names the script actually accepts.
1525
- const scriptSrc = readFileSync(SCRIPT, "utf8");
1526
- const real = [...new Set([...scriptSrc.matchAll(/cmd === "([^"]+)"/g)].map((m) => m[1]))].sort();
1527
- assert.ok(real.length, "ledger.mjs must still dispatch on `cmd === \"...\"`");
1528
-
1529
- const spec = readFileSync(
1530
- fileURLToPath(new URL("../../docs/specs/2026-07-23-fleet-plugin-design.md", import.meta.url)),
1531
- "utf8",
1532
- );
1533
- const row = spec.split("\n").find((l) => l.startsWith("| `ledger.mjs` |"));
1534
- assert.ok(row, "the script-surface table must still carry a ledger.mjs row");
1535
-
1536
- // The In cell leads with the subcommand alternation and only then reaches the
1537
- // optional flags, so everything before the first `[` is the claim under test.
1538
- const advertised = row.split("|")[2].replaceAll("`", "").split("[")[0].trim().split("/").map((x) => x.trim()).sort();
1539
-
1540
- // Set equality, both directions: a phantom subcommand sends a caller to an
1541
- // exit 2 it cannot diagnose, and a missing one hides a capability the row's
1542
- // own neighbouring cell already documents.
1543
- assert.deepEqual(advertised, real, `the In cell and ledger.mjs disagree on the subcommand set`);
1544
-
1545
- // The usage line is another hand-typed copy of this list — the one a caller
1546
- // sees when no subcommand is given at all — so it gets pinned to the same
1547
- // dispatch rather than being the thing everything else is measured against.
1548
- const usage = spawnSync(process.execPath, [SCRIPT], { encoding: "utf8" }).stderr;
1549
- const alternation = usage.match(/([a-z]+(?:\|[a-z]+)+)/)?.[1];
1550
- assert.ok(alternation, `ledger.mjs's usage line must still name its subcommands; got: ${usage}`);
1551
- assert.deepEqual(alternation.split("|").sort(), real, `the usage line and ledger.mjs's dispatch disagree on the subcommand set`);
1552
-
1553
- // The unknown-subcommand die() message is the third hand-typed copy of this
1554
- // list — the one a caller sees for a misspelled subcommand rather than no
1555
- // subcommand at all — so it gets pinned to the same dispatch too.
1556
- const dieList = scriptSrc.match(/unknown subcommand '\$\{cmd\}' — expected ([^`]+)`/)?.[1];
1557
- assert.ok(dieList, "ledger.mjs's unknown-subcommand die() must still name its subcommands");
1558
- const diePin = dieList.replace(" or ", ", ").split(",").map((x) => x.trim()).filter(Boolean).sort();
1559
- assert.deepEqual(diePin, real, "the unknown-subcommand die() message and ledger.mjs's dispatch disagree on the subcommand set");
1560
- });
1561
-
1562
- // The Out cell is the other copy of the same claim, and it is the copy that
1563
- // drifted: `ledger` reached both of `check`'s payloads while the row still
1564
- // typed check as `{subject, found, match, verdict}` (#231). The pin its two
1565
- // siblings carry (no-undo-audit.test.mjs, worktree-audit.test.mjs) does not
1566
- // transfer verbatim — those cells are bare type signatures, this one documents
1567
- // five subcommands in prose, and that prose calls the ledger a ledger ("`read`
1568
- // the whole ledger as"), so a word-boundary match over the whole cell reports
1569
- // `ledger` present while no payload field is named anywhere. Two things fix
1570
- // that: slice to `check`'s own clause, and count only what the cell puts in
1571
- // backticks, since a field name is backticked in this table and prose is not.
1572
- test("the design spec's script-surface row names every field `check` emits", () => {
1573
- // Both arms. `check` emits two shapes and the already-filed one is the
1574
- // subset, so measuring the row against it alone would let every field the
1575
- // wider arm adds drop out of the row unnoticed.
1576
- const arms = [run(UNFILED_SUBJECT, { filed: [] }), run("Non-zero column audit 11 rows", { filed: [FILED_114] })];
1577
- const keys = [...new Set(arms.flatMap((r) => Object.keys(r.json)))].sort();
1578
- assert.ok(keys.length, "check must still emit a payload for the row to be measured against");
1579
-
1580
- const spec = readFileSync(
1581
- fileURLToPath(new URL("../../docs/specs/2026-07-23-fleet-plugin-design.md", import.meta.url)),
1582
- "utf8",
1583
- );
1584
- const row = spec.split("\n").find((l) => l.startsWith("| `ledger.mjs` |"));
1585
- assert.ok(row, "the script-surface table must still carry a ledger.mjs row");
1586
-
1587
- // `check`'s clause runs from its own name to the next subcommand the cell
1588
- // types. Everything after that belongs to `read` or to the per-field glosses,
1589
- // where these same words appear without naming a field of this payload.
1590
- const out = row.split("|")[3];
1591
- const start = out.indexOf("`check`");
1592
- const end = out.indexOf("`read`", start);
1593
- assert.ok(start >= 0 && end > start, "the Out cell must still type `check`'s payload ahead of `read`'s");
1594
- const named = (out.slice(start + "`check`".length, end).match(/`[^`]+`/g) ?? []).join(" ");
1595
-
1596
- // Word boundaries on top of the backtick scoping, so `near` cannot be
1597
- // satisfied by the `nearTotal` standing next to it.
1598
- const missing = keys.filter((k) => !new RegExp(`\\b${k}\\b`).test(named));
1599
- assert.deepEqual(missing, [], `the spec row omits fields check emits: ${missing.join(", ")}`);
1600
- });
1601
-
1602
- // ── The --file / --require-file parser (#362) ────────────────────────────────
1603
- //
1604
- // Nothing above this line reaches these guards: every test enters through
1605
- // run(), which always builds a well-formed `--file <path>` pair, so the whole
1606
- // suite stayed green while `--file --require-file` silently disabled the
1607
- // duplicate-filing guard at exit 0 (measured, #362). These spawn the CLI
1608
- // directly, the way pr-overlap.test.mjs pins its own `--a --b 5` case — the
1609
- // identical fail-open shape, in the hand-rolled reader arg.mjs's shared arg()
1610
- // deliberately does not reach.
1611
- function cliFixture(t) {
1612
- const dir = mkdtempSync(join(tmpdir(), "ledger-cli-"));
1613
- const bin = join(dir, "bin");
1614
- mkdirSync(bin, { recursive: true });
1615
- // Same isolation rule the rest of this file follows: the real `gh` must
1616
- // never be reachable, or these assertions would ride on this repo's live
1617
- // issue list. `git` is symlinked in for the same reason run() does it, not
1618
- // because anything below needs it: every test here passes `--file`, so
1619
- // defaultLedgerPath() never shells out, and none reaches the tracker query
1620
- // that runs the second `git`. Kept so the next test added here fails on its
1621
- // own terms rather than silently taking defaultLedgerPath()'s cwd-relative
1622
- // fallback.
1623
- symlinkSync(REAL_GIT, join(bin, "git"));
1624
- const env = { ...process.env, PATH: bin };
1625
- delete env.GIT_DIR;
1626
- delete env.GIT_WORK_TREE;
1627
- t.after(() => rmSync(dir, { recursive: true, force: true }));
1628
- // `cwd` is bound here rather than threaded per call because every caller
1629
- // wants this fixture's own dir — and one test needs it to be exactly that:
1630
- // the accept-pin hands ledger.mjs a RELATIVE path, which begins with `-`
1631
- // only because the spawn resolves it against `dir`.
1632
- return { dir, cli: (args) => spawnSync(process.execPath, [SCRIPT, ...args], { encoding: "utf8", env, cwd: dir }) };
1633
- }
1634
-
1635
- test("CLI: --file followed by --require-file is refused, not taken as the path (#362)", (t) => {
1636
- const { cli } = cliFixture(t);
1637
- const r = cli(["--file", "--require-file", "check", "dup subject"]);
1638
- assert.equal(r.status, 2, `--file must not swallow the next flag; got exit ${r.status}\n${r.stderr}`);
1639
- assert.match(r.stderr, /--file needs a path/);
1640
- // The harm, asserted directly rather than inferred from the exit code:
1641
- // the swallowed token used to become the ledger PATH, which is how
1642
- // --require-file — the flag whose entire job is to make a missing ledger
1643
- // a hard failure — went missing from the run that named it.
1644
- assert.doesNotMatch(r.stderr, /ledger file not found: --require-file/);
1645
- });
1646
-
1647
- test("CLI: --file given a whitespace-only value is refused (#362)", (t) => {
1648
- const { cli } = cliFixture(t);
1649
- const r = cli(["--file", " ", "check", "dup subject"]);
1650
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
1651
- assert.match(r.stderr, /--file needs a path/);
1652
- });
1653
-
1654
- // #362's guard is additive: the trailing case already died, with its own
1655
- // wording, and that is the one behaviour the issue's own Measured block
1656
- // records as correct. Pinned so the new clause cannot quietly restate it.
1657
- test("CLI: a truly trailing --file still dies with its own pre-existing message (#362)", (t) => {
1658
- const { cli } = cliFixture(t);
1659
- const r = cli(["--file"]);
1660
- assert.equal(r.status, 2);
1661
- assert.match(r.stderr, /--file given with no path/);
1662
- });
1663
-
1664
- // The other half of the guard. Every case above is input it must REFUSE, and
1665
- // a guard that refused EVERYTHING would pass all of them — `startsWith("--")`
1666
- // forfeits a path beginning with `--`, deliberately and in line with arg.mjs,
1667
- // but it must not cost the far likelier neighbours: a single leading `-`, or
1668
- // a `--` anywhere but the front.
1669
- test("CLI: a path beginning with '-' or containing '--' is accepted and actually read (#362)", (t) => {
1670
- const { dir, cli } = cliFixture(t);
1671
- // Passed RELATIVE, against the spawn's cwd, so the value ledger.mjs sees
1672
- // genuinely begins with `-`. Handing it join(dir, ...) would begin with
1673
- // `/` instead and pin only the `--`-inside half — measured: a guard
1674
- // widened to `startsWith("-")` kept this test green until the value was
1675
- // relative.
1676
- const name = "-weird--ledger.md";
1677
- writeFileSync(join(dir, name), ledgerText(["#42 some distinctive filed subject words"]));
1678
- const r = cli(["--file", name, "check", "some distinctive filed subject words"]);
1679
- // Exit 1 is reachable only by loading and parsing the file at that path:
1680
- // it is the `already filed` branch, which matches against rows read from
1681
- // it. Exit 0 would mean the path was accepted but never read; exit 2
1682
- // would mean the guard refused it.
1683
- assert.equal(r.status, 1, `the odd-looking path must be accepted AND read; got exit ${r.status}\n${r.stderr}`);
1684
- assert.match(r.stderr, /ALREADY FILED/);
1685
- });
1686
-
1687
- // --require-file's own exposure, which is NOT --file's: it takes no value, so
1688
- // its `splice(idx, 1)` can swallow nothing. Its one way to go missing was
1689
- // being eaten by the flag before it. This is the invocation #362 measured as
1690
- // correct — exit 2 — next to the exit 0 the swallow produced.
1691
- test("CLI: --require-file survives a well-formed --file and still hard-fails a missing ledger (#362)", (t) => {
1692
- const { dir, cli } = cliFixture(t);
1693
- const r = cli(["--file", join(dir, "nope", "ledger.md"), "--require-file", "check", "dup subject"]);
1694
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
1695
- assert.match(r.stderr, /--require-file given but ledger file does not exist/);
1696
- });
1697
-
1698
- // The `=` spelling, which `indexOf` cannot see at all. BOTH POSITIONS, because
1699
- // the only one that ever failed was the one that happened to land in the
1700
- // SUBCOMMAND slot, where `unknown subcommand` fires — a different refusal, and
1701
- // the single sample that made the `=` form read as already-covered. Elsewhere
1702
- // it is not refused at all: it falls through
1703
- // to `rest` and `check`'s `rest.join(" ")` folds it into the SUBJECT, so the
1704
- // path is lost AND the checked text is corrupted, and the answer is exit 0
1705
- // "safe to file" for a subject this fixture's ledger has already filed. The
1706
- // exit-1 assertion below is what makes that concrete: the same subject against
1707
- // the same file, spelled with a space, is ALREADY FILED.
1708
- test("CLI: --file=<path> is refused in either position, never folded into the subject (#362)", (t) => {
1709
- const { dir, cli } = cliFixture(t);
1710
- const other = join(dir, "other-ledger.md");
1711
- const subject = "some distinctive filed subject words";
1712
- writeFileSync(other, ledgerText([`#42 ${subject}`]));
1713
- // The control: spelled with a space, this exact invocation reads the file
1714
- // and answers "already filed". Without it, exit 2 below would pin only
1715
- // "something refused it", not "the fail-open it replaced was real".
1716
- const ok = cli(["--file", other, "check", subject]);
1717
- assert.equal(ok.status, 1, `the space-separated control must read the file; got exit ${ok.status}\n${ok.stderr}`);
1718
- for (const args of [
1719
- [`--file=${other}`, "check", subject],
1720
- ["check", `--file=${other}`, subject],
1721
- ]) {
1722
- const r = cli(args);
1723
- assert.equal(r.status, 2, `\`${args.join(" ")}\` must be refused; got exit ${r.status}\n${r.stdout}${r.stderr}`);
1724
- assert.match(r.stderr, /--file needs a space-separated value/);
1725
- }
1726
- });
1727
-
1728
- // --require-file's own `=` spelling. Its wording differs from --file's on
1729
- // purpose and matches has()'s in arg.mjs: the flag takes no value, so "needs a
1730
- // space-separated value" would be a lie. Same two positions, same reason.
1731
- test("CLI: --require-file=<value> is refused in either position (#362)", (t) => {
1732
- const { dir, cli } = cliFixture(t);
1733
- const missing = join(dir, "nope", "ledger.md");
1734
- for (const args of [
1735
- ["--require-file=true", "--file", missing, "check", "dup subject"],
1736
- ["--file", missing, "check", "--require-file=true", "dup subject"],
1737
- ]) {
1738
- const r = cli(args);
1739
- assert.equal(r.status, 2, `\`${args.join(" ")}\` must be refused; got exit ${r.status}\n${r.stdout}${r.stderr}`);
1740
- assert.match(r.stderr, /--require-file is a boolean flag/);
1741
- }
1742
- });
1743
-
1744
- // The one thing every test above is blind to: cleanup. All seven pass, and all
1745
- // seven would still pass with the removal deleted — #569 replaced their
1746
- // hand-rolled `finally` blocks with cliFixture()'s own `t.after()`, so this is
1747
- // what reddens if that registration is ever dropped. Run as a SUBTEST, because
1748
- // a test's `after` hooks have not fired while its own body is still running;
1749
- // the parent's `await` resolves only once they have.
1750
- test("CLI: cliFixture removes its tmpdir when the test that made it ends (#569)", async (t) => {
1751
- let dir;
1752
- await t.test("a fixture, made and finished with", (inner) => {
1753
- ({ dir } = cliFixture(inner));
1754
- assert.ok(existsSync(dir), "sanity: a fixture's dir exists while its own test runs");
1755
- });
1756
- assert.equal(existsSync(dir), false, `cliFixture registered no cleanup on its test: ${dir} survived it`);
1757
- });
1758
-
1759
- // ── A stray flag in check's subject tail, or the id slot ahead of a tail (#584) ──
1760
- //
1761
- // `--file`/`--require-file` are spliced out of argv by NAME before `cmd`/
1762
- // `rest` are ever split, so a misspelled flag is the ordinary way one reaches
1763
- // here — though not the only way: the splice is `indexOf`-based and takes one
1764
- // occurrence, so a REPEATED correctly-spelled flag survives into the tail too
1765
- // and meets the same rules. #362 closed the swallow at the
1766
- // `--file`/`--require-file` positions; this is the tail beyond them, where a
1767
- // stray token used to fold straight into the duplicate-filing subject.
1768
- //
1769
- // The measured defect: `check --requre-file "widget guard missing"` searched
1770
- // for subject "--requre-file widget guard missing" — a DIFFERENT subject than
1771
- // the seeded one — and answered exit 0 where the correctly-spelled invocation
1772
- // answers ALREADY FILED at exit 1.
1773
- //
1774
- // Two rules, not one, and they answer different slots. The tail LENGTH rule is
1775
- // `check`'s alone (#1161 — refuseStrayInCheckTail()'s own comment in ledger.mjs
1776
- // carries why), so the other three are pinned ACCEPTING that shape below. The
1777
- // id-slot prefix test is those three's, and is where #584's own signature
1778
- // reaches them.
1779
- test("CLI: a stray flag in check's tail is refused, naming it (#584)", (t) => {
1780
- const { dir, cli } = cliFixture(t);
1781
- const file = join(dir, "ledger.md");
1782
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
1783
- const r = cli(["--file", file, "check", "--requre-file", "widget guard missing"]);
1784
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
1785
- assert.match(r.stderr, /unknown flag --requre-file/);
1786
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
1787
- });
1788
-
1789
- // The pin a prefix test with no length gate fails: `rest.find(a =>
1790
- // a.startsWith("--"))` refuses exactly this invocation — a subject that
1791
- // legitimately begins with `--`, given as ONE argument. It must stay
1792
- // accepted, and the payload's `subject` field must carry it unchanged. That
1793
- // field, specifically: `check` normalises and reorders the subject before it
1794
- // becomes `tracker.query`, so unchanged there is not a claim about the query.
1795
- test("CLI: a subject legitimately starting with '--' is accepted unchanged, given as one argument (#584)", (t) => {
1796
- const { dir, cli } = cliFixture(t);
1797
- const file = join(dir, "ledger.md");
1798
- writeFileSync(file, ledgerText([]));
1799
- const subject = "--require-file silently absent when value missing";
1800
- const r = cli(["--file", file, "check", subject]);
1801
- assert.equal(r.status, 0, `got exit ${r.status}\n${r.stderr}`);
1802
- assert.equal(JSON.parse(r.stdout).subject, subject, "the payload's subject field must carry it unchanged");
1803
- });
1804
-
1805
- // The guard's own false-positive class, distinct from the legitimate
1806
- // `--`-leading subject: an unquoted multi-word subject carrying NO `--` at all must stay
1807
- // accepted exactly as before — tail LENGTH alone must never be what triggers
1808
- // the refusal, only a `--`-prefixed element sharing the tail with it.
1809
- test("CLI: an unquoted multi-word subject with no stray flag is still accepted (#584)", (t) => {
1810
- const { dir, cli } = cliFixture(t);
1811
- const file = join(dir, "ledger.md");
1812
- writeFileSync(file, ledgerText(["#1 widget guard missing"]));
1813
- const r = cli(["--file", file, "check", "widget", "guard", "missing"]);
1814
- assert.equal(r.status, 1, `got exit ${r.status}\n${r.stderr}`);
1815
- assert.match(r.stderr, /ALREADY FILED/);
1816
- });
1817
-
1818
- // Known residual, deliberately left open: a stray flag with no subject at all
1819
- // is a ONE-element tail, so refuseStrayInCheckTail() never fires on it — it is
1820
- // accepted as the subject itself. Left open because closing it costs the
1821
- // legitimate one-argument `--`-leading subject, which is the case #584 exists
1822
- // to keep working, and the residual is harmless: the run searches for the
1823
- // stray's own normalised text (`--requre-file` queries `requre file`), which
1824
- // matches no real row. The exit 0 this asserts also rests on cliFixture's
1825
- // stubbed, unreachable gh — it is not a claim that a live tracker would find
1826
- // nothing, where a scoring row would exit 3. Pinned so a future change does not
1827
- // start refusing it under the belief that widening the guard closes a gap.
1828
- test("CLI: a stray flag alone, with no subject, is accepted as the degenerate subject (#584)", (t) => {
1829
- const { dir, cli } = cliFixture(t);
1830
- const file = join(dir, "ledger.md");
1831
- writeFileSync(file, ledgerText([]));
1832
- const r = cli(["--file", file, "check", "--requre-file"]);
1833
- assert.equal(r.status, 0, `got exit ${r.status}\n${r.stderr}`);
1834
- assert.equal(JSON.parse(r.stdout).subject, "--requre-file");
1835
- });
1836
-
1837
- // #1161's acceptance side: the three subcommands the length rule is NOT read
1838
- // on. Why it is `check`'s alone — which docs spell which convention, and the
1839
- // measurement that settled it — is stated once on refuseStrayInCheckTail() in
1840
- // ledger.mjs.
1841
- //
1842
- // The recorded TEXT is asserted, not only the exit code: accepting the call
1843
- // and then dropping or mangling the `--` word would pass a status-only pin,
1844
- // and that record is what a later `check` and a replacement controller read.
1845
- // A file per subcommand and word, so a failure names which one lost the text.
1846
- //
1847
- // #1744's one-dash name clause lives inside the same guard, so it is `check`'s
1848
- // alone on the same reasoning: its stray, `-require-file`, is driven through
1849
- // here too, as the word the other three must keep as data.
1850
- test("CLI: filed/row/ruled accept an unquoted multi-word subject carrying a '--' or one-dash flag word (#1161, #1744)", (t) => {
1851
- const { dir, cli } = cliFixture(t);
1852
- for (const word of ["--basee", "-require-file"]) {
1853
- for (const [cmd, id, field] of [
1854
- ["filed", "999", "subject"],
1855
- ["row", "42", "line"],
1856
- ["ruled", "77", "decision"],
1857
- ]) {
1858
- const file = join(dir, `${cmd}${word}.md`);
1859
- const r = cli(["--file", file, cmd, id, "the", word, "flag", "is", "unread"]);
1860
- assert.equal(r.status, 0, `${cmd} ${word}: got exit ${r.status}\n${r.stderr}`);
1861
- assert.match(
1862
- JSON.parse(r.stdout)[field],
1863
- new RegExp(`the ${word} flag is unread$`),
1864
- `${cmd} ${word}: the tail must reach the payload with its flag-like word intact`,
1865
- );
1866
- assert.match(
1867
- readFileSync(file, "utf8"),
1868
- new RegExp(`^- #\\d+ the ${word} flag is unread$`, "m"),
1869
- `${cmd} ${word}: and the ledger on disk`,
1870
- );
1871
- }
1872
- }
1873
- });
1874
-
1875
- // filed's own subject-legitimately-starting-with-'--' pin, the counterpart of
1876
- // check's. It answers the id-slot rule rather than the tail one: the prefix
1877
- // test reads `issue` and must never be extended to `subjectParts[0]`, which
1878
- // is where a quoted `--`-leading subject lands.
1879
- test("CLI: filed accepts a subject legitimately starting with '--', given as one argument (#584)", (t) => {
1880
- const { dir, cli } = cliFixture(t);
1881
- const file = join(dir, "ledger.md");
1882
- const subject = "--flag-like subject text";
1883
- const r = cli(["--file", file, "filed", "888", subject]);
1884
- assert.equal(r.status, 0, `got exit ${r.status}\n${r.stderr}`);
1885
- assert.equal(JSON.parse(r.stdout).subject, subject, "the subject must reach the ledger unchanged");
1886
- });
1887
-
1888
- // The stray-flag refusal pins above put the flag FIRST in the tail, so they
1889
- // stay green against a guard that only ever inspects `tail[0]` — a narrowing a
1890
- // future reader could make believing the tests still cover it. This drives the
1891
- // flag into a later position instead. `check` alone now: the loop this used to
1892
- // run over all four tail-reading subcommands is the acceptance pin above for
1893
- // the other three (#1161).
1894
- test("CLI: a stray flag in check's tail is refused from a later position too (#584)", (t) => {
1895
- const { dir, cli } = cliFixture(t);
1896
- const file = join(dir, "ledger.md");
1897
- const r = cli(["--file", file, "check", "widget", "guard", "--typo-flag"]);
1898
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
1899
- assert.match(r.stderr, /unknown flag --typo-flag/, "the refusal must name the stray");
1900
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
1901
- assert.equal(existsSync(file), false, "the refusal must not write a ledger");
1902
- });
1903
-
1904
- // #1744: the `--` clause above left this script's own flag, one dash short,
1905
- // folding into the subject — `check -require-file widget guard missing`
1906
- // scored "-require-file widget guard missing" against the ledger and answered
1907
- // exit 0 where the correctly-spelled call answers ALREADY FILED at exit 1.
1908
- // Both calls are driven, so the pin shows the two parting ways on purpose:
1909
- // the flag spelled right is read, the flag one dash short is refused by name.
1910
- test("CLI: this script's own flag spelled with one dash is refused in check's tail, naming it (#1744)", (t) => {
1911
- const { dir, cli } = cliFixture(t);
1912
- const file = join(dir, "ledger.md");
1913
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
1914
- const right = cli(["--file", file, "check", "--require-file", "widget", "guard", "missing"]);
1915
- assert.equal(right.status, 1, `the correctly-spelled call: got exit ${right.status}\n${right.stderr}`);
1916
- assert.match(right.stderr, /ALREADY FILED/);
1917
- const r = cli(["--file", file, "check", "-require-file", "widget", "guard", "missing"]);
1918
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
1919
- assert.match(r.stderr, /unknown flag -require-file in subject/, "the refusal must name the stray");
1920
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
1921
- });
1922
-
1923
- // The name clause matches only a tail element's FIRST whitespace-split word
1924
- // (ahead of any `=value`), not the whole element — the half of the
1925
- // extraction ledger.mjs's own comment above OWN_FLAGS explains and nothing
1926
- // before this test drove: every case above either hands the flag name its
1927
- // own argv element or dilutes it with `=value` alone, both of which a
1928
- // whole-element match (`a.split("=")[0]`, no leading whitespace split) would
1929
- // also catch. The shape that whitespace split alone catches is a quoted
1930
- // multi-word tail element — one argv token carrying a space, as a shell
1931
- // would deliver `check "-require-file widget" guard missing` — where the
1932
- // flag name leads the element. Reconstructed whole, "-require-file widget"
1933
- // is not itself in OWN_FLAGS; only splitting on whitespace first exposes
1934
- // "-require-file" as its first word.
1935
- test("CLI: this script's own flag name leading a quoted multi-word tail element is refused (#1744)", (t) => {
1936
- const { dir, cli } = cliFixture(t);
1937
- const file = join(dir, "ledger.md");
1938
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
1939
- const r = cli(["--file", file, "check", "-require-file widget", "guard", "missing"]);
1940
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
1941
- assert.match(
1942
- r.stderr,
1943
- /unknown flag -require-file widget in subject/,
1944
- "the refusal must name the whole stray element",
1945
- );
1946
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
1947
- });
1948
-
1949
- // The same slip on the rule's other inputs: the OTHER flag this script reads,
1950
- // a later tail position (a guard reading only `tail[0]` passes the pin above),
1951
- // and the `=value` spelling, which hasEqualsForm() refuses only with two
1952
- // dashes. `-file` is the costlier slip of the two: outside this fixture no
1953
- // `--file` is given, so the path joins the subject AND the default ledger is
1954
- // the one checked.
1955
- test("CLI: a one-dash spelling of either flag is refused anywhere in check's tail, =value too (#1744)", (t) => {
1956
- const { dir, cli } = cliFixture(t);
1957
- const file = join(dir, "ledger.md");
1958
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
1959
- for (const [stray, tail] of [
1960
- ["-file", ["-file", "other.md", "widget guard missing"]],
1961
- ["-require-file", ["widget", "guard", "missing", "-require-file"]],
1962
- ["-require-file=true", ["-require-file=true", "widget guard missing"]],
1963
- ]) {
1964
- const r = cli(["--file", file, "check", ...tail]);
1965
- assert.equal(r.status, 2, `${tail.join(" ")}: got exit ${r.status}\n${r.stderr}`);
1966
- assert.match(r.stderr, new RegExp(`unknown flag ${stray} in subject`), `${tail.join(" ")}: must name the stray`);
1967
- assert.equal(r.stdout, "", `${tail.join(" ")}: a refusal must not also emit a payload`);
1968
- }
1969
- });
1970
-
1971
- // The length gate fronts the name clause too: the same text given as the ONE
1972
- // argument check's convention prescribes is a subject, not a stray — the
1973
- // one-dash counterpart of the `--`-leading pin above. A name clause read
1974
- // ahead of the gate fails this.
1975
- test("CLI: a subject opening with a one-dash flag name is accepted unchanged, given as one argument (#1744)", (t) => {
1976
- const { dir, cli } = cliFixture(t);
1977
- const file = join(dir, "ledger.md");
1978
- writeFileSync(file, ledgerText([]));
1979
- const subject = "-require-file typo folds into the subject";
1980
- const r = cli(["--file", file, "check", subject]);
1981
- assert.equal(r.status, 0, `got exit ${r.status}\n${r.stderr}`);
1982
- assert.equal(JSON.parse(r.stdout).subject, subject, "the payload's subject field must carry it unchanged");
1983
- // The multi-word subject above never reaches the name clause either way —
1984
- // it is a ONE-element tail regardless of ordering, so that alone does not
1985
- // pin the gate running first. This second call closes that: its sole tail
1986
- // token IS an own-flag name outright, with nothing diluting the match, so
1987
- // a name clause read ahead of the length gate would refuse it here where
1988
- // the correct order accepts it — the one-dash counterpart of the #584
1989
- // pin at line 1889, which proves the same shape for a two-dash flag.
1990
- const bare = cli(["--file", file, "check", "-require-file"]);
1991
- assert.equal(bare.status, 0, `got exit ${bare.status}\n${bare.stderr}`);
1992
- assert.equal(JSON.parse(bare.stdout).subject, "-require-file", "the payload's subject field must carry it unchanged");
1993
- });
1994
-
1995
- // Why the clause is a NAME test and not a prefix or shape one: single-dash
1996
- // words are ordinary free text in this repo's subjects — another tool's short
1997
- // flag, a lone `-` standing in for a dash, a negative number — and an
1998
- // unquoted subject carrying them must be scored as that subject, not refused.
1999
- // Seeded, so the exit 1 proves every word reached the match intact.
2000
- // `startsWith("-")` fails this on all three words; `/^-[A-Za-z]/` on `-q`.
2001
- test("CLI: an unquoted subject carrying single-dash words that are not this script's flags is still accepted (#1744)", (t) => {
2002
- const { dir, cli } = cliFixture(t);
2003
- const file = join(dir, "ledger.md");
2004
- const subject = "reap.sh grep -q misreads - exit -1 as clean";
2005
- writeFileSync(file, ledgerText([`#1419 ${subject}`]));
2006
- const r = cli(["--file", file, "check", ...subject.split(" ")]);
2007
- assert.equal(r.status, 1, `got exit ${r.status}\n${r.stderr}`);
2008
- assert.match(r.stderr, /ALREADY FILED/);
2009
- });
2010
-
2011
- // #1766: the extraction above still matched only a's FIRST whitespace-split
2012
- // word, taken exact-case. A case-variant spelling of either own-flag name
2013
- // never lower-cases to anything the OWN_FLAGS.includes() check recognizes,
2014
- // so it fell through to exit 0 the same way the exact spelling did before
2015
- // #1744 — confirmed by direct probe against the shipped script.
2016
- test("CLI: a case-variant spelling of this script's own flag name is refused in check's tail (#1766)", (t) => {
2017
- const { dir, cli } = cliFixture(t);
2018
- const file = join(dir, "ledger.md");
2019
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2020
- for (const stray of ["-REQUIRE-FILE", "-Require-File", "-FILE"]) {
2021
- const r = cli(["--file", file, "check", stray, "widget", "guard", "missing"]);
2022
- assert.equal(r.status, 2, `${stray}: got exit ${r.status}\n${r.stderr}`);
2023
- assert.match(r.stderr, new RegExp(`unknown flag ${stray} in subject`), `${stray}: must name the stray`);
2024
- assert.equal(r.stdout, "", `${stray}: a refusal must not also emit a payload`);
2025
- }
2026
- });
2027
-
2028
- // #1766: whitespace ahead of the dash lands in `a.split(/\s/)[0]` too — the
2029
- // leading space becomes an empty first word, not `-require-file`, so the
2030
- // OWN_FLAGS.includes() check on that empty word never matches and the real
2031
- // word one index over is never reached — confirmed by direct probe.
2032
- test("CLI: leading whitespace ahead of this script's own flag name still lets the clause refuse it (#1766)", (t) => {
2033
- const { dir, cli } = cliFixture(t);
2034
- const file = join(dir, "ledger.md");
2035
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2036
- const stray = " -require-file";
2037
- const r = cli(["--file", file, "check", stray, "widget", "guard", "missing"]);
2038
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
2039
- assert.match(
2040
- r.stderr,
2041
- new RegExp(`unknown flag ${stray} in subject`),
2042
- "the refusal must name the whole stray element, leading whitespace included",
2043
- );
2044
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
2045
- });
2046
-
2047
- // #1766: U+00A0 (no-break space) is matched by `\s` in a JS split, same as
2048
- // plain space — but ahead of the dash it hits the identical empty-first-word
2049
- // loss the plain-whitespace case above does, so it is pinned as its own case
2050
- // rather than assumed covered by that fix alone — confirmed by direct probe.
2051
- test("CLI: a leading no-break space (U+00A0) ahead of this script's own flag name still lets the clause refuse it (#1766)", (t) => {
2052
- const { dir, cli } = cliFixture(t);
2053
- const file = join(dir, "ledger.md");
2054
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2055
- const stray = "\u00A0-require-file";
2056
- const r = cli(["--file", file, "check", stray, "widget", "guard", "missing"]);
2057
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
2058
- assert.match(
2059
- r.stderr,
2060
- new RegExp(`unknown flag ${stray} in subject`),
2061
- "the refusal must name the whole stray element, the no-break space included",
2062
- );
2063
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
2064
- });
2065
-
2066
- // #1766: the quoted-multi-word pin above (#1744/#1762) only closed the flag
2067
- // name LEADING such an element — that fix still reads only the element's
2068
- // first whitespace-split word, so the mirror shape, the flag name trailing
2069
- // instead, is invisible to it just as the bare exact-case miss was —
2070
- // confirmed by direct probe.
2071
- test("CLI: this script's own flag name trailing a quoted multi-word tail element is refused (#1766)", (t) => {
2072
- const { dir, cli } = cliFixture(t);
2073
- const file = join(dir, "ledger.md");
2074
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2075
- const r = cli(["--file", file, "check", "widget -require-file", "guard", "missing"]);
2076
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
2077
- assert.match(
2078
- r.stderr,
2079
- /unknown flag widget -require-file in subject/,
2080
- "the refusal must name the whole stray element",
2081
- );
2082
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
2083
- });
2084
-
2085
- // #1766 follow-up (review): the four pins above each exercise one axis in
2086
- // isolation — case, leading whitespace, leading U+00A0, or trailing
2087
- // position — so a narrower fix that special-cased only word[0]/word[-1], or
2088
- // only handled one axis at a time, could still pass all four. This combines
2089
- // two axes (case AND leading whitespace together) and lands the flag word
2090
- // in the MIDDLE of a three-word quoted element, neither leading nor
2091
- // trailing it, to pin that the per-word scan really does check every word,
2092
- // not just the ends.
2093
- test("CLI: a case-variant flag combined with leading whitespace, and a flag word in the middle of a longer quoted element, are both refused (#1766)", (t) => {
2094
- const { dir, cli } = cliFixture(t);
2095
- const file = join(dir, "ledger.md");
2096
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2097
-
2098
- const mixed = " -REQUIRE-FILE";
2099
- const r1 = cli(["--file", file, "check", mixed, "widget", "guard", "missing"]);
2100
- assert.equal(r1.status, 2, `got exit ${r1.status}\n${r1.stderr}`);
2101
- assert.match(r1.stderr, new RegExp(`unknown flag ${mixed} in subject`), "case + leading whitespace together must still be refused");
2102
-
2103
- const r2 = cli(["--file", file, "check", "widget -require-file extra", "guard", "missing"]);
2104
- assert.equal(r2.status, 2, `got exit ${r2.status}\n${r2.stderr}`);
2105
- assert.match(r2.stderr, /unknown flag widget -require-file extra in subject/, "a flag word in the middle of a 3-word element must still be refused");
2106
- });
2107
-
2108
- // #1850: the trailing-position pin above (#1766) only ever exercises the
2109
- // one-dash spelling of this script's own flag name. The same trailing
2110
- // position, spelled with this script's own TWO dashes instead, reaches
2111
- // neither clause: the outer `startsWith("--")` test only fires when a
2112
- // two-dash name LEADS the whole tail element, and the per-word test below
2113
- // it, before this fix, only ever built the one-dash-prepended form of a
2114
- // word — never a word's own two-dash form — so a two-dash own-flag name
2115
- // trailing a quoted multi-word element folded back into the subject
2116
- // silently. Reproduced against the shipped script exactly as the ticket
2117
- // gives it.
2118
- test("CLI: this script's own flag name, two dashes, trailing a quoted multi-word tail element is refused (#1850)", (t) => {
2119
- const { dir, cli } = cliFixture(t);
2120
- const file = join(dir, "ledger.md");
2121
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2122
- const r = cli(["--file", file, "check", "widget --require-file", "guard", "missing"]);
2123
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
2124
- assert.match(
2125
- r.stderr,
2126
- /unknown flag widget --require-file in subject/,
2127
- "the refusal must name the whole stray element",
2128
- );
2129
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
2130
- });
2131
-
2132
- // #1850: the same three inputs #1744 drove through the one-dash clause —
2133
- // the OTHER flag, a flag word in the MIDDLE rather than at either end of a
2134
- // longer quoted element, and the `=value` spelling — driven through the
2135
- // two-dash form instead, so a fix that only special-cased the trailing word
2136
- // or only the one flag name could not still pass this. A case-variant
2137
- // spelling and a case-variant combined with a leading NBSP (the #1766
2138
- // axes, one dash count over) are driven too, since neither #1850 pin above
2139
- // exercised case at all: a mutant that keeps the new branch's shape but
2140
- // drops `.toLowerCase()` from just the as-spelled lookup passed every
2141
- // existing test in the file (review finding, PR #1875). A generic two-dash
2142
- // word that is NOT one of this script's own flags is driven alongside
2143
- // them, pinned staying accepted — including one that extends an own flag
2144
- // by suffix (`--files` over `--file`), since a mutant that swaps the NAME
2145
- // match for a `startsWith` prefix match also passed every existing test
2146
- // (same review finding): the per-word clause is a NAME match against
2147
- // OWN_FLAGS, never a "starts with two dashes" shape test or a prefix test —
2148
- // the shape test is the outer clause's alone, and only over the whole
2149
- // element.
2150
- test("CLI: a two-dash spelling of either flag is refused anywhere in a quoted tail element, =value, a case variant, NBSP-prefixed case variant, and non-own two-dash words (including one sharing an own flag's prefix) too (#1850)", (t) => {
2151
- const { dir, cli } = cliFixture(t);
2152
- const file = join(dir, "ledger.md");
2153
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2154
- for (const [stray, tail] of [
2155
- ["widget --file", ["widget --file", "guard", "missing"]],
2156
- ["widget --require-file extra", ["widget --require-file extra", "guard", "missing"]],
2157
- ["widget --require-file=true", ["widget --require-file=true", "guard", "missing"]],
2158
- ["widget --REQUIRE-FILE", ["widget --REQUIRE-FILE", "guard", "missing"]],
2159
- ["widget\u00A0--Require-File", ["widget\u00A0--Require-File", "guard", "missing"]],
2160
- ]) {
2161
- const r = cli(["--file", file, "check", ...tail]);
2162
- assert.equal(r.status, 2, `${tail.join(" ")}: got exit ${r.status}\n${r.stderr}`);
2163
- assert.match(r.stderr, new RegExp(`unknown flag ${stray} in subject`), `${tail.join(" ")}: must name the stray`);
2164
- assert.equal(r.stdout, "", `${tail.join(" ")}: a refusal must not also emit a payload`);
2165
- }
2166
-
2167
- const bareFile = join(dir, "bare.md");
2168
- for (const nonOwn of ["widget --basee", "widget --files"]) {
2169
- const subject = `${nonOwn} guard missing`;
2170
- writeFileSync(bareFile, ledgerText([`#1419 ${subject}`]));
2171
- const accepted = cli(["--file", bareFile, "check", nonOwn, "guard", "missing"]);
2172
- assert.equal(accepted.status, 1, `${nonOwn}: got exit ${accepted.status}\n${accepted.stderr}`);
2173
- assert.match(
2174
- accepted.stderr,
2175
- /ALREADY FILED/,
2176
- `${nonOwn}: a two-dash word that is not this script's own flag must still be scored as subject text`,
2177
- );
2178
- }
2179
- });
2180
-
2181
- // #1851: a Unicode format character (general category Cf) is invisible and
2182
- // sits outside `\s`, so the per-word split above never cuts on it and it rides
2183
- // along inside the word it touches — `\u200B-require-file` never equalled an
2184
- // own-flag spelling, and the call fell through to scoring the subject: the
2185
- // verdict flip #1744/#1766/#1850 exist to refuse. The ticket's own probe
2186
- // (U+200B and U+2060 leading the flag as its own argv element) is driven
2187
- // first. Trailing, inside the name, a Latin-1 Cf (U+00AD), U+180E (in `\s`
2188
- // before Unicode 6.3, Cf only since), and an astral one (U+E0020 TAG SPACE)
2189
- // are each cases at least one of a leading-only strip, a two-character
2190
- // strip, or a BMP-only hand-written class would still miss. `=value` and
2191
- // the two-dash as-spelled branch with a case variant do not: the Cf
2192
- // character leads the word in both, so all three of those narrower fixes
2193
- // still catch it — those two entries instead cover that `split("=")` and
2194
- // `toLowerCase()` still see the stripped name correctly. The U+FEFF case
2195
- // was refused before this fix and is here for the strip-after-split
2196
- // ordering rationale refuseStrayInCheckTail()'s own comment gives in full
2197
- // — it is the one Cf code point that is also `\s`.
2198
- test("CLI: a format (Cf) character ahead of, inside or behind this script's own flag name still lets the clause refuse it (#1851)", (t) => {
2199
- const { dir, cli } = cliFixture(t);
2200
- const file = join(dir, "ledger.md");
2201
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2202
- for (const stray of [
2203
- "\u200B-require-file",
2204
- "\u2060-require-file",
2205
- "widget -file\u200B",
2206
- "-require\u2060-file",
2207
- "\u200B-require-file=true",
2208
- "widget \u2060--REQUIRE-FILE",
2209
- "\u00AD-file",
2210
- "\u180E-require-file",
2211
- "\u{E0020}-file",
2212
- "widget\uFEFF-require-file",
2213
- ]) {
2214
- const r = cli(["--file", file, "check", stray, "widget", "guard", "missing"]);
2215
- const label = JSON.stringify(stray);
2216
- assert.equal(r.status, 2, `${label}: got exit ${r.status}\n${r.stderr}`);
2217
- assert.ok(
2218
- r.stderr.includes(`unknown flag ${stray} in subject`),
2219
- `${label}: the refusal must name the whole stray element, format character included\n${r.stderr}`,
2220
- );
2221
- assert.equal(r.stdout, "", `${label}: a refusal must not also emit a payload`);
2222
- }
2223
- });
2224
-
2225
- // #1851's false-positive side: the fix strips format characters out of a
2226
- // word, it does not split on them. A word the character sits INSIDE of stays
2227
- // one word, so `pre\u200B-file` is looked up as `pre-file` — the word a reader
2228
- // sees — and not as a `-file` that splitting on U+200B would expose. A
2229
- // one-dash word sharing an own name's prefix and a non-own two-dash word stay
2230
- // subject text with a format character ahead of them too: still a NAME match.
2231
- test("CLI: a word carrying a format (Cf) character that is not this script's own flag name is still scored as subject text (#1851)", (t) => {
2232
- const { dir, cli } = cliFixture(t);
2233
- const file = join(dir, "ledger.md");
2234
- for (const word of ["pre\u200B-file", "widget \u2060-files", "widget \u200B--basee"]) {
2235
- const subject = `${word} guard missing`;
2236
- writeFileSync(file, ledgerText([`#1419 ${subject}`]));
2237
- const r = cli(["--file", file, "check", word, "guard", "missing"]);
2238
- const label = JSON.stringify(word);
2239
- assert.equal(r.status, 1, `${label}: got exit ${r.status}\n${r.stderr}`);
2240
- assert.match(r.stderr, /ALREADY FILED/, `${label}: must still be scored as subject text`);
2241
- }
2242
- });
2243
-
2244
- // #1904: invisible characters OUTSIDE Cf that Unicode still marks
2245
- // Default_Ignorable_Code_Point — the Hangul fillers (U+3164, U+115F, U+1160,
2246
- // U+FFA0; category Letter) and the combining grapheme joiner plus the
2247
- // variation selectors (U+034F, U+FE00, astral U+E0100; category Mark) — rode
2248
- // through #1851's Cf-only strip the same way a zero-width space did before
2249
- // it, and the call scored the subject. Each code point the ticket names is
2250
- // driven leading the flag as its own argv element, the ticket's own probe;
2251
- // then trailing and inside the name, the positions a leading-only strip
2252
- // would miss. U+17B4 and U+180B are DICP members the ticket does not name:
2253
- // a hand-curated block list of the named ranges would still miss both,
2254
- // which is why the strip is the property union and not such a list. And
2255
- // U+0600 is the other half of that union: a visible Cf mark DICP leaves
2256
- // out, which #1851 already stripped — swapping DICP in for Cf rather than
2257
- // adding it would stop refusing this one, and no #1851 pin covers it.
2258
- test("CLI: a non-Cf default-ignorable character (Hangul filler, variation selector) ahead of, inside or behind this script's own flag name still lets the clause refuse it (#1904)", (t) => {
2259
- const { dir, cli } = cliFixture(t);
2260
- const file = join(dir, "ledger.md");
2261
- writeFileSync(file, ledgerText(["#123 widget guard missing"]));
2262
- for (const stray of [
2263
- "\u3164-require-file",
2264
- "\uFE00-require-file",
2265
- "\u115F-require-file",
2266
- "\u1160-file",
2267
- "\uFFA0-require-file",
2268
- "\u034F-file",
2269
- "\u{E0100}-require-file",
2270
- "widget -file\uFE0F",
2271
- "-require\u3164-file",
2272
- "widget \u034F--REQUIRE-FILE",
2273
- "\u17B4-file",
2274
- "\u180B-require-file",
2275
- "\u0600-file",
2276
- ]) {
2277
- const r = cli(["--file", file, "check", stray, "widget", "guard", "missing"]);
2278
- const label = JSON.stringify(stray);
2279
- assert.equal(r.status, 2, `${label}: got exit ${r.status}\n${r.stderr}`);
2280
- assert.ok(
2281
- r.stderr.includes(`unknown flag ${stray} in subject`),
2282
- `${label}: the refusal must name the whole stray element, invisible character included\n${r.stderr}`,
2283
- );
2284
- assert.equal(r.stdout, "", `${label}: a refusal must not also emit a payload`);
2285
- }
2286
- });
2287
-
2288
- // #1904's false-positive side, the #1851 pin's shape over the new classes:
2289
- // an emoji's own presentation selector (U+FE0F) glued directly ahead of a
2290
- // dash-suffixed near-miss of an own flag name, a Hangul filler inside an
2291
- // unrelated word, and one ahead of a word that only shares an own name's
2292
- // prefix all stay subject text — the strip only ever makes an own-flag
2293
- // spelling out of a word that already was one plus invisible characters.
2294
- // The first case is glued, not merely adjacent, so a split-instead-of-strip
2295
- // bug refuses it too (the same shape the second case already catches with
2296
- // a different DICP class) — a bare emoji ahead of an unrelated word stays
2297
- // accepted under every strip-shaped mutant and would prove nothing.
2298
- test("CLI: a word carrying a non-Cf default-ignorable character that is not this script's own flag name is still scored as subject text (#1904)", (t) => {
2299
- const { dir, cli } = cliFixture(t);
2300
- const file = join(dir, "ledger.md");
2301
- for (const word of ["\u2764\uFE0F-file", "pre\u3164-file", "widget \u3164-files", "widget \u{E0100}--basee"]) {
2302
- const subject = `${word} guard missing`;
2303
- writeFileSync(file, ledgerText([`#1419 ${subject}`]));
2304
- const r = cli(["--file", file, "check", word, "guard", "missing"]);
2305
- const label = JSON.stringify(word);
2306
- assert.equal(r.status, 1, `${label}: got exit ${r.status}\n${r.stderr}`);
2307
- assert.match(r.stderr, /ALREADY FILED/, `${label}: must still be scored as subject text`);
2308
- }
2309
- });
2310
-
2311
- // The tail guard cannot reach the slot ahead of it: a stray flag one token
2312
- // earlier becomes the id, and the tail behind it holds no `--` element to
2313
- // find. Each subcommand loses something different to that — `filed` its
2314
- // duplicate-filing answer, `row` its rewrite-in-place key, `ruled` its
2315
- // decision record — so each is driven here on its own.
2316
- function assertStrayIdSlotRefused(t, strayFlag) {
2317
- const { dir, cli } = cliFixture(t);
2318
- const file = join(dir, "ledger.md");
2319
- for (const [cmd, expected] of [
2320
- ["filed", new RegExp(`unknown flag ${strayFlag} — expected an issue number`)],
2321
- ["row", new RegExp(`unknown flag ${strayFlag} — expected a ticket number`)],
2322
- ["ruled", new RegExp(`unknown flag ${strayFlag} — expected a PR number`)],
2323
- ]) {
2324
- const r = cli(["--file", file, cmd, strayFlag, "999", "widget guard missing"]);
2325
- assert.equal(r.status, 2, `${cmd}: got exit ${r.status}\n${r.stderr}`);
2326
- assert.match(r.stderr, expected, `${cmd}: must name the stray and the slot it displaced`);
2327
- assert.equal(r.stdout, "", `${cmd}: a refusal must not also emit a payload`);
2328
- }
2329
- assert.equal(existsSync(file), false, "no refusal may write a ledger");
2330
- }
2331
-
2332
- test("CLI: a stray flag in the id slot ahead of the tail is refused, naming it (#584)", (t) => {
2333
- assertStrayIdSlotRefused(t, "--requre-file");
2334
- });
2335
-
2336
- // #1678: the double-dash-only prefix test above left a single-dash id
2337
- // silently accepted as the row/issue/PR key — nothing refused it and nothing
2338
- // reported it, and the slip is an ordinary one: dropping one dash from this
2339
- // CLI's own `--require-file` produces exactly this shape, which is why the
2340
- // refused value below is that realistic one-dash-short misspelling rather
2341
- // than an abstract single letter.
2342
- test("CLI: a single-dash argument in the id slot is refused too, naming it (#1678)", (t) => {
2343
- assertStrayIdSlotRefused(t, "-require-file");
2344
- });
2345
-
2346
- // The id guard's own false-positive class: an id argument is still accepted
2347
- // with or without its `#`, and the legitimate-subject pins still hold, so the bare
2348
- // prefix test on that slot cannot be what refuses a legitimate call.
2349
- test("CLI: an ordinary id is unaffected by the id-slot guard, with or without '#' (#584)", (t) => {
2350
- const { dir, cli } = cliFixture(t);
2351
- const file = join(dir, "ledger.md");
2352
- const r = cli(["--file", file, "filed", "#999", "widget guard missing"]);
2353
- assert.equal(r.status, 0, `got exit ${r.status}\n${r.stderr}`);
2354
- assert.equal(JSON.parse(r.stdout).issue, "#999");
2355
- const r2 = cli(["--file", file, "row", "42", "some state text"]);
2356
- assert.equal(r2.status, 0, `got exit ${r2.status}\n${r2.stderr}`);
2357
- assert.equal(JSON.parse(r2.stdout).ticket, "#42");
2358
- });
2359
-
2360
- // ── The payload subcommands on a pipe (#246) ─────────────────────────────────
2361
- //
2362
- // `console.log(payload)` followed by `process.exit()` truncates on a pipe.
2363
- // process.exit() abandons the queued async write, so the consumer receives
2364
- // whatever the kernel had already accepted — at exit 0, which types a corrupt
2365
- // payload as a successful one. Measured on this script before the fix: `read`
2366
- // of an oversized ledger handed a prefix that JSON.parse rejects to a
2367
- // spawnSync consumer at status 0, while the identical command redirected to a
2368
- // file delivered all of it and parsed. `board.mjs` is the consumer that made
2369
- // it visible — it reads `read` through execFileSync, which pipes stdout just
2370
- // the same — and it has no flag that would let it read the ledger any other
2371
- // way, so it served a cockpit with an empty board.
2372
- //
2373
- // Every assertion below is "the payload parses" and "the tail arrived", never
2374
- // a byte count. The cut is a pipe-buffer boundary raced against the consumer's
2375
- // draining rather than a constant — the same defect has been measured
2376
- // delivering one buffer, and on a minority of runs two — so a test pinning
2377
- // either number passes only until the race goes the other way.
2378
- //
2379
- // cli() spawns through spawnSync, whose stdout is a pipe, so these run the
2380
- // defect's own path rather than a simulation of it.
2381
-
2382
- // A floor, not a boundary pin: a fixture has to be too large for any observed
2383
- // drain outcome to deliver whole by accident, or a still-truncating script
2384
- // passes these tests and they pin nothing. Several times the buffer rather
2385
- // than merely past it, since two buffers have been measured getting through on
2386
- // a minority of runs — and not larger still because three of the four
2387
- // subcommands can only be fed an oversized payload through argv, which has two
2388
- // separate ceilings: a total across every argument, and a far lower one on any
2389
- // single argument. The sweep below stays under the second by splitting its
2390
- // tail across several elements, asserted there rather than assumed here.
2391
- //
2392
- // Asserted in BYTES. String.length counts UTF-16 units, and the `·` these rows
2393
- // carry (as real ones do) makes the two disagree, so a cut that is exact in
2394
- // bytes reads as a smaller and untidy character count, inviting the false
2395
- // conclusion that the cut is fuzzy. No figure is quoted for that: a character
2396
- // count belongs to the fixture that produced it, and one carried over from a
2397
- // different measurement reads as if it were this one's.
2398
- const OVERSIZED = 200_000;
2399
-
2400
- // Linux caps a single argv element at MAX_ARG_STRLEN, 32 pages; darwin caps
2401
- // only the total. So a tail sent as one element passes locally and execve
2402
- // refuses it on CI — and that refusal is not a truncation: spawnSync returns
2403
- // status null, failing the exit-code assertion below and reading exactly like
2404
- // the defect these tests exist to catch.
2405
- const ARG_STRLEN_MAX = 131_072;
2406
-
2407
- // Built here rather than read from the repo's own `.fleet/ledger.md`: that
2408
- // file is whatever the last run left, it has been well under the pipe buffer
2409
- // for entire days, and a fixture that small makes every assertion below
2410
- // vacuous while still passing.
2411
- function oversizedLedger() {
2412
- const rows = [], filed = [], ruled = [];
2413
- for (let i = 0; i < 1600; i++) {
2414
- rows.push(`#${i} impl-${i} · class=routine · ports=81${i} · a row of the width these reach once a run has been going a while`);
2415
- filed.push(`#${i} a filed finding subject with enough distinctive words in it to read like a real one, number ${i}`);
2416
- ruled.push(`#${i} MERGE · the review cleared and the checks were green · entry ${i}`);
2417
- }
2418
- const section = (entries) => entries.map((e) => `- ${e}`).join("\n");
2419
- const text = `# Fleet run ledger\n\n## Rows\n\n${section(rows)}\n\n## Filed\n\n${section(filed)}\n\n## Ruled\n\n${section(ruled)}\n`;
2420
- assert.ok(
2421
- Buffer.byteLength(text) > OVERSIZED,
2422
- `fixture must be far past the pipe buffer or this test pins nothing, got ${Buffer.byteLength(text)} bytes`,
2423
- );
2424
- return { text, rows, filed, ruled };
2425
- }
2426
-
2427
- function parsePayload(r, what) {
2428
- try {
2429
- return JSON.parse(r.stdout);
2430
- } catch (e) {
2431
- // Report what was observed, never the cause. Truncation is not the only
2432
- // way to get here — an empty stdout, or one a stray line polluted, parses
2433
- // just as badly at exit 0 — and naming the pipe would send a reader after
2434
- // #246 for a defect that is not it. The byte count already says whether
2435
- // the payload stopped on a buffer boundary.
2436
- assert.fail(`${what} payload did not parse — ${Buffer.byteLength(r.stdout)} bytes on stdout at exit ${r.status}: ${e.message}`);
2437
- }
2438
- }
2439
-
2440
- test("read hands a pipe the whole ledger — a truncated payload must never read as exit 0 (#246)", (t) => {
2441
- const { dir, cli } = cliFixture(t);
2442
- const file = join(dir, "ledger.md");
2443
- const { text, rows, filed, ruled } = oversizedLedger();
2444
- writeFileSync(file, text);
2445
-
2446
- const r = cli(["--file", file, "read"]);
2447
- assert.equal(r.status, 0, `read must still exit 0; got ${r.status}\n${r.stderr}`);
2448
- const payload = parsePayload(r, "read's");
2449
-
2450
- // The whole payload, not a named tail. A truncated one never reaches this
2451
- // line at all — it is unterminated JSON and dies in parsePayload above — so
2452
- // a separate tail assertion discriminated nothing. That is the same thing
2453
- // the grep-shaped reading of this defect got wrong: a consumer that greps
2454
- // still finds the earlier keys, which made it look milder than it is, while
2455
- // a parsing consumer loses every key, the survivors included, because the
2456
- // object is unterminated. Comparing the whole object also catches a key the
2457
- // payload should not carry, which the per-key assertions let through.
2458
- // The fixture predates `## Dispatched` and `## Drain`, so both read empty.
2459
- assert.deepEqual(payload, { rows, filed, ruled, dispatched: [], drain: null });
2460
- });
2461
-
2462
- // The same mechanism in the three siblings. Their payloads echo the free-text
2463
- // tail they were given, which is the only unbounded thing in them, so that is
2464
- // what an oversized case has to be built from. Swept with `read` rather than
2465
- // after it: fixing only the subcommand a report happens to name is the failure
2466
- // this repo keeps re-recording, and all four ended `console.log` + exit 0.
2467
- //
2468
- // The tail goes over as several argv elements, not one. All three subcommands
2469
- // join their trailing arguments with a space, so what they echo is identical
2470
- // either way — but one element this size is refused outright by execve on
2471
- // Linux, which is a spawn that never happened rather than a payload that
2472
- // arrived short.
2473
- for (const cmd of ["row", "filed", "ruled"]) {
2474
- test(`${cmd} hands a pipe its whole payload, at its unchanged exit code (#246)`, (t) => {
2475
- const { dir, cli } = cliFixture(t);
2476
- const file = join(dir, "ledger.md");
2477
- writeFileSync(file, ledgerText([]));
2478
- const parts = Array.from({ length: 4 }, () => "alpha bravo charlie delta ".repeat(2000).trim());
2479
- const text = parts.join(" ");
2480
- assert.ok(Buffer.byteLength(text) > OVERSIZED, `tail must be far past the pipe buffer, got ${Buffer.byteLength(text)} bytes`);
2481
- assert.ok(
2482
- parts.every((p) => Buffer.byteLength(p) < ARG_STRLEN_MAX),
2483
- `every argv element must stay under the per-argument ceiling, or execve refuses the spawn and the exit-code assertion below fails for a reason that has nothing to do with a pipe`,
2484
- );
2485
-
2486
- const r = cli(["--file", file, cmd, "4242", ...parts]);
2487
- assert.equal(r.status, 0, `${cmd} must still exit 0; got ${r.status}\n${r.stderr}`);
2488
- const payload = parsePayload(r, `${cmd}'s`);
2489
- // Each subcommand names its echoed text differently; the guarantee is the
2490
- // same one — whatever it chose to send arrived intact.
2491
- assert.ok(
2492
- JSON.stringify(payload).includes(text),
2493
- `${cmd}'s payload parsed but lost the text it echoes`,
2494
- );
2495
- });
2496
- }
2497
-
2498
- // The other half. Everything above is a payload that must ARRIVE; these are
2499
- // the invocations that must still be refused or still succeed exactly as they
2500
- // did, because dropping a process.exit() from a branch changes where control
2501
- // goes next — a `read` branch that merely stops calling exit() runs on into
2502
- // the unknown-subcommand die() and turns a good invocation into exit 2, and a
2503
- // dispatch rearranged to prevent that can just as easily stop refusing a bad
2504
- // one. `check`'s own exit codes are pinned by the whole first half of this
2505
- // file, which is why they are not restated here.
2506
- test("an ordinary ledger still round-trips through a pipe, and an unknown subcommand still refuses (#246)", (t) => {
2507
- const { dir, cli } = cliFixture(t);
2508
- const file = join(dir, "ledger.md");
2509
- writeFileSync(file, ledgerText([]));
2510
-
2511
- const row = cli(["--file", file, "row", "7", "impl-7 · class=routine"]);
2512
- assert.equal(row.status, 0, `row: got ${row.status}\n${row.stderr}`);
2513
- assert.deepEqual(parsePayload(row, "row's"), { ticket: "#7", line: "#7 impl-7 · class=routine", created: true });
2514
-
2515
- const filed = cli(["--file", file, "filed", "8", "a short filed subject"]);
2516
- assert.equal(filed.status, 0, `filed: got ${filed.status}\n${filed.stderr}`);
2517
- assert.deepEqual(parsePayload(filed, "filed's"), { issue: "8", subject: "a short filed subject", total: 1 });
2518
-
2519
- const ruled = cli(["--file", file, "ruled", "9", "MERGE · green"]);
2520
- assert.equal(ruled.status, 0, `ruled: got ${ruled.status}\n${ruled.stderr}`);
2521
- assert.deepEqual(parsePayload(ruled, "ruled's"), { pr: "9", decision: "MERGE · green", total: 1 });
2522
-
2523
- const read = cli(["--file", file, "read"]);
2524
- assert.equal(read.status, 0, `read: got ${read.status}\n${read.stderr}`);
2525
- assert.deepEqual(parsePayload(read, "read's"), {
2526
- rows: ["#7 impl-7 · class=routine"],
2527
- filed: ["#8 a short filed subject"],
2528
- ruled: ["#9 MERGE · green"],
2529
- dispatched: [],
2530
- drain: null,
2531
- });
2532
-
2533
- // Nothing in this suite spawned an unknown subcommand before, so the die()
2534
- // every payload branch used to jump over was pinned by nothing at all.
2535
- const unknown = cli(["--file", file, "reed"]);
2536
- assert.equal(unknown.status, 2, `an unknown subcommand must still exit 2; got ${unknown.status}\n${unknown.stderr}`);
2537
- assert.match(unknown.stderr, /unknown subcommand 'reed'/);
2538
- assert.equal(unknown.stdout, "", "a refusal must not also emit a payload");
2539
- });
2540
-
2541
- // ── `filed` on a repeat call (#2087) ─────────────────────────────────────────
2542
- //
2543
- // Both callers of `filed` retry once on failure, and a failure the CALLER saw
2544
- // is not proof the write failed: a harness timeout after the row landed reads
2545
- // as one. The retry must not append a second row for the same issue. The
2546
- // assertions read the ledger file back, because a payload can claim a no-op
2547
- // that the file does not show.
2548
- const filedLines = (file) => readFileSync(file, "utf8").split("\n").filter((l) => l.startsWith("- #"));
2549
-
2550
- test("filed: a repeat call for an issue already filed writes nothing and says so, at exit 0 (#2087)", (t) => {
2551
- const { dir, cli } = cliFixture(t);
2552
- const file = join(dir, "ledger.md");
2553
- const first = cli(["--file", file, "filed", "8", "subject a"]);
2554
- assert.equal(first.status, 0, first.stderr);
2555
- assert.deepEqual(parsePayload(first, "the first filing's"), { issue: "8", subject: "subject a", total: 1 });
2556
- const before = readFileSync(file, "utf8");
2557
-
2558
- for (const [issue, subject] of [["8", "subject a"], ["8", "different wording"], ["#8", "subject a"]]) {
2559
- const again = cli(["--file", file, "filed", issue, subject]);
2560
- assert.equal(again.status, 0, `${issue} ${subject}: ${again.stderr}`);
2561
- const payload = parsePayload(again, "the repeat filing's");
2562
- assert.equal(payload.alreadyRecorded, true, `${issue} ${subject}: ${again.stdout}`);
2563
- assert.equal(payload.row, "#8 subject a", "the payload must name the row already on file");
2564
- assert.equal(payload.total, 1);
2565
- assert.deepEqual(filedLines(file), ["- #8 subject a"], `${issue} ${subject} changed the filed rows`);
2566
- }
2567
- assert.equal(readFileSync(file, "utf8"), before, "a repeat filing rewrote the ledger");
2568
- });
2569
-
2570
- test("filed: identity is the exact issue number — #8 neither dedupes against nor is deduped by #80 or #18 (#2087)", (t) => {
2571
- const { dir, cli } = cliFixture(t);
2572
- for (const order of [["80", "18", "8"], ["8", "80", "18"]]) {
2573
- const file = join(dir, `ledger-${order.join("-")}.md`);
2574
- for (const issue of order) {
2575
- const r = cli(["--file", file, "filed", issue, `subject for ${issue}`]);
2576
- assert.equal(r.status, 0, r.stderr);
2577
- assert.equal("alreadyRecorded" in parsePayload(r, `${issue}'s`), false, `${issue} after ${order.join(",")} was read as a repeat`);
2578
- }
2579
- assert.deepEqual(filedLines(file), order.map((n) => `- #${n} subject for ${n}`));
2580
- }
2581
- });
2582
-
2583
- test("filed: identity is matched numerically, so a non-canonical spelling of an already-filed issue is still a repeat (#2087)", (t) => {
2584
- const { dir, cli } = cliFixture(t);
2585
- const file = join(dir, "ledger.md");
2586
- const first = cli(["--file", file, "filed", "8", "subject a"]);
2587
- assert.equal(first.status, 0, first.stderr);
2588
- const before = readFileSync(file, "utf8");
2589
-
2590
- const again = cli(["--file", file, "filed", "08", "different wording"]);
2591
- assert.equal(again.status, 0, again.stderr);
2592
- const payload = parsePayload(again, "the leading-zero repeat filing's");
2593
- assert.equal(payload.alreadyRecorded, true, again.stdout);
2594
- assert.equal(payload.row, "#8 subject a", "the payload must name the row already on file");
2595
- assert.deepEqual(filedLines(file), ["- #8 subject a"], "a leading-zero repeat spelling appended a row");
2596
- assert.equal(readFileSync(file, "utf8"), before, "a leading-zero repeat filing rewrote the ledger");
2597
- });
2598
-
2599
- test("filed: an id that is not all digits is refused, not silently appended (#2087)", (t) => {
2600
- const { dir, cli } = cliFixture(t);
2601
- const file = join(dir, "ledger.md");
2602
- for (const issue of ["abc", "#", "8a", " 8", "8 "]) {
2603
- const r = cli(["--file", file, "filed", issue, "subject a"]);
2604
- assert.equal(r.status, 2, `'${issue}': got exit ${r.status}\n${r.stderr}`);
2605
- assert.match(r.stderr, /is not an issue number/, `'${issue}': ${r.stderr}`);
2606
- assert.equal(r.stdout, "", `'${issue}': a refusal must not also emit a payload`);
2607
- }
2608
- assert.equal(existsSync(file), false, "a refused filing must not create the ledger");
2609
- });
2610
-
2611
- // ── `check` on a pipe (#808) ─────────────────────────────────────────────────
2612
- //
2613
- // The sweep above cannot reach `check`: it drives the three subcommands whose
2614
- // payload echoes an argv tail, and `check`'s does not. Its wide field is
2615
- // `match` — a row read straight back out of `data.filed` — so the fixture that
2616
- // makes it oversized is a wide LEDGER, not a wide argv, and no ceiling on an
2617
- // argv element applies. `filed` caps neither the subject it stores nor the
2618
- // ledger it stores it into, so an ordinary four-word `check` reaches the cut
2619
- // against a ledger holding one wide row.
2620
- //
2621
- // Both arms are driven, because the exit these pin is mid-branch. The
2622
- // already-filed arm leaves early, and the arm below it is everything that
2623
- // early departure exists to skip — a restructure that gets the departure
2624
- // wrong breaks one or the other, and only exercising both tells them apart.
2625
- //
2626
- // run() spawns through spawnSync, whose stdout is a pipe, so these run the
2627
- // defect's own path rather than a simulation of it. Its parse is the
2628
- // assertion: a truncated payload leaves `json` null, which is what the
2629
- // oversized cases below test for, quoting the byte count rather than naming
2630
- // the pipe — an empty or polluted stdout fails to parse just as badly.
2631
- const WIDE_FILED_ROW = `#4242 ${"alpha bravo charlie delta ".repeat(8000).trim()}`;
2632
-
2633
- test("check hands a pipe its whole ALREADY FILED payload, at its unchanged exit 1 (#808)", () => {
2634
- assert.ok(
2635
- Buffer.byteLength(WIDE_FILED_ROW) > OVERSIZED,
2636
- `the filed row must be far past the pipe buffer or this test pins nothing, got ${Buffer.byteLength(WIDE_FILED_ROW)} bytes`,
2637
- );
2638
- const r = run("alpha bravo charlie delta", { filed: [WIDE_FILED_ROW] });
2639
- // Exit first: this is the ALREADY FILED signal callers gate on, and it is
2640
- // the one thing the defect never moved — a fix that delivers the payload by
2641
- // weakening the signal would trade a corrupt payload for a duplicate filing.
2642
- assert.equal(r.status, 1, `the ALREADY FILED signal must not move; got ${r.status}\n${r.stderr.slice(0, 400)}`);
2643
- assert.ok(
2644
- r.json,
2645
- `check's already-filed payload did not parse — ${Buffer.byteLength(r.stdout)} bytes on stdout at exit ${r.status}`,
2646
- );
2647
- assert.equal(r.json.match, WIDE_FILED_ROW, "the payload parsed but lost the filed row it exists to name");
2648
- assert.equal(r.json.verdict, "already-filed");
2649
- });
2650
-
2651
- // What the early departure exists to SKIP, asserted on the payload rather than
2652
- // on `gh` alone. The tracker query is only half of it: the near-miss ranking
2653
- // runs entirely in this process and never touches `gh`, so a run that never
2654
- // invoked it is no evidence the ranking was skipped. The key set is, and it
2655
- // also catches the opposite restructure — one that reaches the wider arm's
2656
- // fields and merges them in.
2657
- test("check's ALREADY FILED payload carries the already-filed shape alone (#808)", () => {
2658
- const r = run("Non-zero column audit 11 rows", { filed: [FILED_114, FILED_131], hits: [HIT_114] });
2659
- assert.equal(r.status, 1, `got ${r.status}\n${r.stderr}`);
2660
- assert.ok(r.json, `already-filed payload did not parse — ${Buffer.byteLength(r.stdout)} bytes on stdout`);
2661
- assert.deepEqual(
2662
- Object.keys(r.json).sort(),
2663
- ["found", "ledger", "match", "subject", "verdict"],
2664
- "the already-filed arm must not pick up the fields of the arm it departs before",
2665
- );
2666
- assert.equal(r.ghRan, false, "the tracker search stays skipped");
2667
- // The emission's own shape — a score follows the phrase — rather than the
2668
- // bare word, so a filed row that happens to use it cannot trip this.
2669
- assert.doesNotMatch(r.stderr, /near-miss \d/, "the near-miss ranking stays skipped");
2670
- });
2671
-
2672
- // The other half, and the one the arm above can only be tested against: input
2673
- // this must still ACCEPT and carry all the way through. Every case above stops
2674
- // early, and a restructure that stopped early ALWAYS would pass all of them —
2675
- // so the arm past the departure gets an oversized payload of its own. `near`
2676
- // is sliced from `data.filed`, so it is ledger-bounded exactly as `match` is.
2677
- //
2678
- // The rows share content words with the subject without matching it: each
2679
- // carries a term the subject lacks and the subject carries one they lack, so
2680
- // neither token set is the other's subset and the exact path cannot fire —
2681
- // while the overlap that ranks them stays well above zero.
2682
- test("check hands a pipe its whole not-filed payload, and still reaches the tracker (#808)", () => {
2683
- const filed = ["alpha", "bravo", "charlie"].map(
2684
- (tag, i) => `#${800 + i} ${"delta echo foxtrot ".repeat(6000).trim()} ${tag}`,
2685
- );
2686
- const r = run("delta echo foxtrot zulu", { filed, hits: [] });
2687
- assert.equal(r.status, 0, `a ledger with no exact match and a tracker that returns nothing stays exit 0; got ${r.status}\n${r.stderr.slice(0, 400)}`);
2688
- assert.ok(
2689
- r.json,
2690
- `check's not-filed payload did not parse — ${Buffer.byteLength(r.stdout)} bytes on stdout at exit ${r.status}`,
2691
- );
2692
- assert.ok(
2693
- Buffer.byteLength(JSON.stringify(r.json.near)) > OVERSIZED,
2694
- `the near-miss rows must be far past the pipe buffer or this test pins nothing, got ${Buffer.byteLength(JSON.stringify(r.json.near))} bytes`,
2695
- );
2696
- // The peer of the already-filed arm's shape pin, and not symmetric with it:
2697
- // that one guards against fields LEAKING in, which the design-spec row above
2698
- // already catches on its own. This one guards against a field going missing,
2699
- // which that row cannot see — it reads the emitted keys, so a key that stops
2700
- // being emitted stops being checked. `subject` is the one field of this arm
2701
- // no other test reads, so dropping it is the mutation that survives the
2702
- // whole suite otherwise.
2703
- assert.deepEqual(
2704
- Object.keys(r.json).sort(),
2705
- ["found", "ledger", "match", "near", "nearTotal", "subject", "tracker", "verdict"],
2706
- "the not-filed arm must still carry every field it names",
2707
- );
2708
- assert.equal(r.json.found, false, "none of these rows is a match, or the ranking below them never runs");
2709
- assert.deepEqual(r.json.near.map((n) => n.row), filed, "the payload parsed but lost the near-miss rows it ranked");
2710
- assert.equal(r.ghRan, true, "the arm past the early departure must still reach the tracker query");
2711
- // These rows share most of the subject's content words, so they sit far
2712
- // above the soft-hit floor — the oversized payload and the verdict it
2713
- // carries are the same statement, and the pipe test is what proves the
2714
- // verdict travelled with it.
2715
- assert.equal(r.json.verdict, "soft-hit");
2716
- });
2717
-
2718
- // ── `--require-file` past `check` (#816) ─────────────────────────────────────
2719
- //
2720
- // An absent ledger and a real empty one produced byte-identical stdout at exit
2721
- // 0 with nothing on stderr — measured with `cmp` on both streams — and `read`
2722
- // is the subcommand board.mjs consumes, so the cockpit rendered "no ledger
2723
- // yet", "ledger read, nothing in it" and "the read did not parse" as one thing.
2724
- //
2725
- // The flag that separates them already existed. What was missing is where it
2726
- // was read: the guard sat inside runCheck(), so `check` honoured it and the
2727
- // other four subcommands did not. It is read ahead of the dispatch now, which
2728
- // is what docs/specs/2026-07-23-fleet-plugin-design.md's `ledger.mjs` row
2729
- // already documented
2730
- // ("Exit 2 on any subcommand — ... `--require-file` with no ledger file") and
2731
- // what the implementation had never matched.
2732
- //
2733
- // So the sweep below is the whole class, not the one member #816's title names:
2734
- // fixing only `read` leaves three siblings holding the same defect behind the
2735
- // same flag. `check` is the fourth and was already correct; the tests above
2736
- // pin it, and hoisting the guard leaves its message and its exit code alone.
2737
-
2738
- const READ_EMPTY = { rows: [], filed: [], ruled: [], dispatched: [], drain: null };
2739
-
2740
- test("read --require-file refuses an absent ledger, naming the path, with no payload (#816)", (t) => {
2741
- const { dir, cli } = cliFixture(t);
2742
- const missing = join(dir, "nope.md");
2743
-
2744
- const r = cli(["--file", missing, "--require-file", "read"]);
2745
- assert.equal(r.status, 2, `got exit ${r.status}\n${r.stderr}`);
2746
- assert.match(r.stderr, /--require-file given but ledger file does not exist/);
2747
- assert.ok(r.stderr.includes(missing), `the reason must name the path that was looked for; got: ${r.stderr}`);
2748
- // Not "the payload is not the empty shape" but "there is no payload at all".
2749
- // board.mjs's tryParse takes whatever lands on stdout and never sees the exit
2750
- // code, so a refusal that still printed something parseable would be this
2751
- // defect in a new spelling rather than a fix for it.
2752
- assert.equal(r.stdout, "", "a refusal must not also emit a payload");
2753
- });
2754
-
2755
- // The pin that separates the two states, and the one that keeps this fix from
2756
- // being a new bug: before it, both of these succeeded identically, so a guard
2757
- // that refused any ledger holding nothing would satisfy the refusal test above
2758
- // and break the first read of every real run — a ledger with no rows yet is
2759
- // the normal state of a run that has just started.
2760
- test("read --require-file accepts a real EMPTY ledger, unchanged (#816)", (t) => {
2761
- const { dir, cli } = cliFixture(t);
2762
- const file = join(dir, "ledger.md");
2763
- writeFileSync(file, ledgerText([]));
2764
-
2765
- const r = cli(["--file", file, "--require-file", "read"]);
2766
- assert.equal(r.status, 0, `an empty ledger is still a ledger; got exit ${r.status}\n${r.stderr}`);
2767
- assert.deepEqual(parsePayload(r, "read's"), READ_EMPTY);
2768
- assert.equal(r.stderr, "", "an accepted read says nothing on stderr");
2769
- });
2770
-
2771
- // The other half of the ruling. The flag is an opt-in, so every caller that
2772
- // does not pass it — board.mjs as it stood, and anything else spawning `read`
2773
- // — must still see today's bytes. This is #816's own `cmp`-on-both-streams
2774
- // measurement kept as an assertion rather than a paragraph.
2775
- test("read WITHOUT the flag is unchanged on both streams, absent and empty alike (#816)", (t) => {
2776
- const { dir, cli } = cliFixture(t);
2777
- const file = join(dir, "ledger.md");
2778
- writeFileSync(file, ledgerText([]));
2779
-
2780
- for (const [what, path] of [["absent", join(dir, "nope.md")], ["empty", file]]) {
2781
- const r = cli(["--file", path, "read"]);
2782
- assert.equal(r.status, 0, `${what}: a bare read must still exit 0; got ${r.status}\n${r.stderr}`);
2783
- assert.equal(r.stdout, `${JSON.stringify(READ_EMPTY)}\n`, `${what}: read's stdout moved`);
2784
- assert.equal(r.stderr, "", `${what}: read's stderr moved`);
2785
- }
2786
- });
2787
-
2788
- // The siblings. These three WRITE, so a missing file is ordinarily legitimate
2789
- // — save() creates it, and that is how the first row of a run gets written.
2790
- // `--require-file` is precisely the opt-in for a caller that knows the ledger
2791
- // must already exist, and the measured behaviour was that `row` under the flag
2792
- // happily CREATED the file whose absence the flag exists to refuse. Both
2793
- // directions are driven, because a guard that refused unconditionally would
2794
- // break every run's first write.
2795
- for (const [cmd, args] of [["row", ["7", "impl-7 · class=routine"]], ["filed", ["8", "a short filed subject"]], ["ruled", ["9", "MERGE · green"]]]) {
2796
- test(`${cmd} --require-file refuses an absent ledger and writes nothing, while a bare ${cmd} still creates it (#816)`, (t) => {
2797
- const { dir, cli } = cliFixture(t);
2798
- const missing = join(dir, "nope.md");
2799
-
2800
- const refused = cli(["--file", missing, "--require-file", cmd, ...args]);
2801
- assert.equal(refused.status, 2, `got exit ${refused.status}\n${refused.stderr}`);
2802
- assert.ok(refused.stderr.includes(missing), `the reason must name the path; got: ${refused.stderr}`);
2803
- assert.equal(refused.stdout, "", "a refusal must not also emit a payload");
2804
- // The harm, not just the exit code: the flag's whole job is to stop a
2805
- // write against a ledger that is not there, and a refusal that had already
2806
- // written would leave the path existing for every later call.
2807
- assert.equal(existsSync(missing), false, "a refused write must not have created the ledger it refused");
2808
-
2809
- const created = cli(["--file", missing, cmd, ...args]);
2810
- assert.equal(created.status, 0, `without the flag ${cmd} must still create the ledger; got ${created.status}\n${created.stderr}`);
2811
- assert.equal(existsSync(missing), true, "a bare write still creates the ledger it was given");
2812
- });
2813
- }
2814
-
2815
- // ---------------------------------------------------------------------------
2816
- // #1199: what `check`'s children are bounded BY.
2817
- //
2818
- // The tracker query has carried a 20 s bound since #638 and the test above
2819
- // pins it. The two `git` probes on either side of it carried NONE, and that
2820
- // asymmetry is what this block closes. Measured on the unfixed script against
2821
- // a `git` that answers and then never returns: `check` — the fleet's
2822
- // pre-filing duplicate guard — was still running at 60 s with zero bytes on
2823
- // stdout, where the identical shape on the `gh` side degrades at its own bound
2824
- // and still prints a payload. One probe reached, no payload, no upper bound.
2825
- //
2826
- // These drive `git` rather than `gh`, so they build their own `bin/`: run()
2827
- // symlinks the REAL git in on purpose (#155) and must keep doing so.
2828
- // `LEDGER_GIT_TIMEOUT` buys a short budget instead of paying the default one
2829
- // per case — the reason net_budget's override exists at all — and the one case
2830
- // that has to prove the DEFAULT is a bound pays it in full.
2831
- // ---------------------------------------------------------------------------
2832
-
2833
- // `rev-parse` is the only argv either probe uses, so keying on it leaves every
2834
- // other invocation instant. `/bin/sleep` absolute: PATH is this
2835
- // fixture's own bin, which holds `git` and `gh` and nothing else.
2836
- //
2837
- // The stall RELEASES the captured pipes before it begins, and that detail is
2838
- // what keeps a regression here loud. `exec`ing the sleep while it still holds
2839
- // this probe's stdout leaves spawnSync reading an open pipe long after the
2840
- // caller's own backstop has killed the run — measured on the unbounded script,
2841
- // the backstop fired at 45 s and the call did not return for the sleep's full
2842
- // 600, so removing the bound would look like a hung suite rather than a failed
2843
- // assertion. Closed, an absent bound reds at the backstop instead. Same shape
2844
- // inflight.test.mjs names: killing the named process is not enough while a
2845
- // descendant still holds the stderr the caller is draining.
2846
- const GIT_HANGS = `#!/bin/sh
2847
- case " $* " in *" rev-parse "*) exec /bin/sleep 600 >/dev/null 2>&1 ;; esac
2848
- exit 0
2849
- `;
2850
- // Slow but WORKING, and the answer is real: `--show-toplevel`'s stdout becomes
2851
- // the cwd the tracker query is bound to, so it has to name a directory that
2852
- // exists or gh dies of ENOENT and the accept case would pass for the wrong
2853
- // reason.
2854
- const gitSlow = (seconds, toplevel) => `#!/bin/sh
2855
- case " $* " in
2856
- *" rev-parse "*) /bin/sleep ${seconds}; printf '%s\\n' '${toplevel}'; exit 0 ;;
2857
- esac
2858
- exit 0
2859
- `;
2860
-
2861
- function gitFixture(t, gitBody) {
2862
- const dir = mkdtempSync(join(tmpdir(), "ledger-gitprobe-"));
2863
- t.after(() => rmSync(dir, { recursive: true, force: true }));
2864
- const bin = join(dir, "bin");
2865
- mkdirSync(bin, { recursive: true });
2866
- const file = join(dir, "ledger.md");
2867
- writeFileSync(file, ledgerText([]));
2868
-
2869
- const gitPath = join(bin, "git");
2870
- writeExecStub(gitPath, gitBody.replace("__DIR__", dir));
2871
- // Records that it was reached, so an accepted probe is told from a degraded
2872
- // one by something better than an exit code both of them share. Neither stub
2873
- // is warmed: `writeExecStub` links an already-scanned inode, so no first-exec
2874
- // scan lands inside the bounded region these cases measure.
2875
- const ghSentinel = join(dir, "gh-ran");
2876
- const ghPath = join(bin, "gh");
2877
- writeExecStub(ghPath, `#!/bin/sh\n: > '${ghSentinel}'\nprintf '[]\\n'\n`);
2878
-
2879
- const env = { ...process.env, PATH: bin };
2880
- delete env.GIT_DIR;
2881
- delete env.GIT_WORK_TREE;
2882
-
2883
- // `timeout` here is the CALLER's backstop and the detector for an absent
2884
- // bound: generous against every budget below, so a run held to it means the
2885
- // script stopped bounding its own child rather than that the box was slow.
2886
- // The same instrument inflight.test.mjs uses for its own bound.
2887
- return (subject, { extraEnv = {}, noFile = false } = {}) => {
2888
- const args = noFile ? ["check", subject] : ["--file", file, "check", subject];
2889
- const r = spawnSync(process.execPath, [SCRIPT, ...args], {
2890
- encoding: "utf8", cwd: dir, timeout: 45_000, env: { ...env, ...extraEnv },
2891
- });
2892
- let json = null;
2893
- try { json = JSON.parse(r.stdout); } catch { /* a degraded run still parses; a killed one does not */ }
2894
- return { ...r, json, ghRan: existsSync(ghSentinel) };
2895
- };
2896
- }
2897
-
2898
- const PROBE_SUBJECT = "candidates mjs states the opposite of its code";
2899
-
2900
- test("a git that never answers the repository probe is bounded, not waited on (#1199)", (t) => {
2901
- const check = gitFixture(t, GIT_HANGS);
2902
- const r = check(PROBE_SUBJECT, { extraEnv: { LEDGER_GIT_TIMEOUT: "2" } });
2903
-
2904
- assert.equal(r.error, undefined,
2905
- `the run was held to the CALLER's backstop — the script's own bound on git is gone: ${JSON.stringify(r.error)}`);
2906
- assert.equal(r.status, 0, "a stalled probe degrades; it does not block the filing");
2907
- assert.ok(r.json, `a bounded run still emits its payload; got stdout ${JSON.stringify(r.stdout)}`);
2908
- assert.equal(r.json.tracker.ok, false);
2909
- assert.match(r.json.tracker.error, /ETIMEDOUT/,
2910
- "the bound has to name itself in the payload — this is the only copy of the cause");
2911
- assert.equal(r.ghRan, false,
2912
- "a probe that never resolved the repository must not go on to query the tracker against an unknown one");
2913
- });
2914
-
2915
- // The sibling probe, and it is a different call site with a different degrade:
2916
- // defaultLedgerPath() does not report an unchecked tracker, it falls back to a
2917
- // cwd-relative ledger — a pre-existing fallback #155 leaves alone, not one it
2918
- // introduces — so an unbounded hang there wedges the run before a ledger is
2919
- // ever chosen.
2920
- test("a git that never answers the ledger-path resolution is bounded too (#1199)", (t) => {
2921
- const check = gitFixture(t, GIT_HANGS);
2922
- const r = check(PROBE_SUBJECT, { extraEnv: { LEDGER_GIT_TIMEOUT: "2" }, noFile: true });
2923
-
2924
- assert.equal(r.error, undefined,
2925
- `the run was held to the CALLER's backstop — defaultLedgerPath()'s git is unbounded: ${JSON.stringify(r.error)}`);
2926
- assert.match(r.stderr, /could not resolve --git-common-dir/,
2927
- "the fallback must still announce itself; a silent degrade here is the guard failing open");
2928
- assert.match(r.stderr, /ETIMEDOUT/,
2929
- "an ETIMEDOUT stall and an instant \"not a repository\" print the same generic text otherwise — cause() must name which one, matching runCheck()'s sibling probe above");
2930
- });
2931
-
2932
- // The other half. Every case above is a probe the budget must CUT, and a bound
2933
- // that cut everything would satisfy all of them while breaking every real run
2934
- // on a loaded machine — which is the harm #1099 named when it refused to widen
2935
- // a budget rather than stop spending it. This one feeds a probe that is slow
2936
- // and CORRECT and must be accepted whole.
2937
- test("a slow but working repository probe still reaches the tracker — the budget is not a stopwatch on success (#1199)", (t) => {
2938
- const check = gitFixture(t, gitSlow(3, "__DIR__"));
2939
- const r = check(PROBE_SUBJECT);
2940
-
2941
- assert.equal(r.error, undefined, `the run did not come back: ${JSON.stringify(r.error)}`);
2942
- assert.equal(r.status, 0, r.stderr);
2943
- assert.equal(r.ghRan, true,
2944
- "a healthy probe, however slow, must still bind and run the tracker query");
2945
- assert.equal(r.json.tracker.ok, true, `the slow probe was treated as a failure: ${r.stderr}`);
2946
- assert.doesNotMatch(r.stderr, /ETIMEDOUT/, "nothing was killed here, and nothing may claim it was");
2947
- });
2948
-
2949
- // What makes the acceptance above meaningful rather than a budget so wide it
2950
- // could never fire: the SAME probe, cut, once the budget is shortened under it.
2951
- test("the same slow probe is cut once the budget is shortened below it (#1199)", (t) => {
2952
- const check = gitFixture(t, gitSlow(3, "__DIR__"));
2953
- const r = check(PROBE_SUBJECT, { extraEnv: { LEDGER_GIT_TIMEOUT: "1" } });
2954
-
2955
- assert.equal(r.error, undefined, `the run did not come back: ${JSON.stringify(r.error)}`);
2956
- assert.match(r.json.tracker.error, /ETIMEDOUT/, "a budget under the probe's own latency must fire");
2957
- assert.equal(r.ghRan, false, "and the tracker query must not run on a repository that was never resolved");
2958
- });
2959
-
2960
- // The override's direction, which is the whole reason it is an override and not
2961
- // a setting: net_budget's rule is that configuration may shorten a bound and
2962
- // may never remove it. Costs the full default budget and cannot cost less —
2963
- // the only observable that separates "the default stood" from "the override was
2964
- // taken" is which of the two elapses, so this case has to let one of them.
2965
- // Asserted categorically against the caller's backstop rather than against a
2966
- // stopwatch, so the verdict does not ride on machine load.
2967
- test("LEDGER_GIT_TIMEOUT cannot lengthen the bound, only shorten it (#1199)", (t) => {
2968
- const check = gitFixture(t, GIT_HANGS);
2969
- const r = check(PROBE_SUBJECT, { extraEnv: { LEDGER_GIT_TIMEOUT: "600" } });
2970
-
2971
- assert.equal(r.error, undefined,
2972
- `a 600 s override became the bound, so configuration can remove it: ${JSON.stringify(r.error)}`);
2973
- assert.match(r.json.tracker.error, /ETIMEDOUT/, "the default must still have fired");
2974
- });
2975
-
2976
- // isDigits()'s whole job, named in the block comment above gitBudget(): the
2977
- // accepted spelling is the shell rule's `*[!0-9]*`, so anything Number()
2978
- // would still happily parse — a decimal point, a leading `-`, exponent
2979
- // notation — has to be rejected FLAT, not clamped or truncated, leaving the
2980
- // default bound standing in silence. `-5` and `5e3` both fail the `seconds >
2981
- // 0` / `seconds < defaultSeconds` clauses on their own even with isDigits()
2982
- // deleted outright, so neither exercises anything the guard alone still
2983
- // catches. `3.5` is the discriminating case: Number("3.5") is 3.5, strictly
2984
- // between 0 and the 10 s default, so a regression that swapped
2985
- // `isDigits(String(override)) ? Number(override) : 0` for a bare
2986
- // `Number(override ?? 0)` takes it as a genuine 3.5 s bound (measured: that
2987
- // exact substitution still passes every other #1199 test above unmodified).
2988
- //
2989
- // The probe sleeps 5 s: past a 3.5 s bound (cut, ETIMEDOUT) and comfortably
2990
- // short of the untouched 10 s default (accepted, real answer) — the same
2991
- // margin the slow-but-working acceptance test above uses against its own
2992
- // bound.
2993
- test("a malformed LEDGER_GIT_TIMEOUT override is rejected outright, not coerced by Number() (#1199)", (t) => {
2994
- const check = gitFixture(t, gitSlow(5, "__DIR__"));
2995
- const r = check(PROBE_SUBJECT, { extraEnv: { LEDGER_GIT_TIMEOUT: "3.5" } });
2996
-
2997
- assert.equal(r.error, undefined, `the run did not come back: ${JSON.stringify(r.error)}`);
2998
- assert.equal(r.status, 0, r.stderr);
2999
- assert.equal(r.ghRan, true,
3000
- "a malformed override must not shorten the bound — the probe should still be accepted at the untouched 10 s default");
3001
- assert.equal(r.json.tracker.ok, true, `a malformed override cut the probe short: ${r.stderr}`);
3002
- assert.doesNotMatch(r.stderr, /ETIMEDOUT/, "the default bound must not have fired");
3003
- });
3004
-
3005
- // ── The write lock (#531) ────────────────────────────────────────────────────
3006
- //
3007
- // Every write subcommand rewrites the whole ledger from what it loaded, so an
3008
- // unlocked pair of writers is last-writer-wins — measured before the lock, 8
3009
- // concurrent `filed` kept 2-5 of 8 rows, and the losers exited 2 on a shared
3010
- // temp file's rename. These spawn REAL concurrent processes and assert
3011
- // invariants that hold on every run under the lock, rather than timing a
3012
- // window; nothing here sleeps. The timeout tests hold the lock explicitly, as a
3013
- // file carrying a pid, and shorten the wait through LEDGER_LOCK_TIMEOUT_MS.
3014
- function lockFixture(t) {
3015
- const dir = mkdtempSync(join(tmpdir(), "ledger-lock-"));
3016
- t.after(() => rmSync(dir, { recursive: true, force: true }));
3017
- const file = join(dir, "ledger.md");
3018
- const lock = `${file}.lock`;
3019
- // PATH holds `git` alone, as in cliFixture(): nothing below reaches the
3020
- // tracker, and the real `gh` must not be reachable if something ever does.
3021
- const bin = join(dir, "bin");
3022
- mkdirSync(bin);
3023
- symlinkSync(REAL_GIT, join(bin, "git"));
3024
- const env = { ...process.env, PATH: bin };
3025
- delete env.LEDGER_LOCK_TIMEOUT_MS;
3026
- delete env.GIT_DIR;
3027
- delete env.GIT_WORK_TREE;
3028
- const argvOf = (args) => [SCRIPT, "--file", file, ...args];
3029
- // Bounded, so a writer that never gives up waiting fails its test instead
3030
- // of hanging the suite: spawnSync blocks the event loop the runner's own
3031
- // --test-timeout needs.
3032
- const cli = (args, extraEnv = {}) =>
3033
- spawnSync(process.execPath, argvOf(args), { encoding: "utf8", env: { ...env, ...extraEnv }, cwd: dir, timeout: 20_000 });
3034
- // Resolves on `close`, not `exit`, so stdout/stderr are complete.
3035
- const cliAsync = (args) => new Promise((resolve, reject) => {
3036
- const c = spawn(process.execPath, argvOf(args), { env, cwd: dir });
3037
- let stderr = "";
3038
- c.stderr.on("data", (b) => { stderr += b; });
3039
- c.on("error", reject);
3040
- c.on("close", (status) => resolve({ status, stderr }));
3041
- });
3042
- // Every sibling of the ledger this suite's lock could leave behind: the
3043
- // lock, the reap lock, and a per-pid temp file.
3044
- const residue = () => readdirSync(dir).filter((f) => f.startsWith("ledger.md") && f !== "ledger.md");
3045
- return { dir, file, lock, cli, cliAsync, residue };
3046
- }
3047
-
3048
- // A pid that is certainly not running: spawnSync has already reaped the
3049
- // child. Asserted rather than assumed, so a recycled pid fails here loudly
3050
- // instead of turning a takeover test into a timeout.
3051
- function deadPid() {
3052
- const { pid } = spawnSync(process.execPath, ["-e", ""]);
3053
- assert.throws(() => process.kill(pid, 0), { code: "ESRCH" }, `pid ${pid} was recycled before the test could use it`);
3054
- return pid;
3055
- }
3056
-
3057
- const psStat = (pid) => {
3058
- const r = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" });
3059
- assert.ifError(r.error);
3060
- return r.stdout.trim();
3061
- };
3062
-
3063
- // A zombie, which deadPid() above deliberately is not: a pid whose process has
3064
- // exited but whose parent has not yet wait()-ed on it. The parent here is a
3065
- // node process holding its own event loop blocked in a synchronous read of its
3066
- // stdin. libuv's SIGCHLD handler only queues the child's exit; the waitpid()
3067
- // that reaps it runs on that loop, so the child stays a zombie until reap()
3068
- // closes the stdin — then the parent reaps it and says so. Its own parent does
3069
- // the reaping, not init after an orphaning, so reap() waits on exactly the
3070
- // reap and on nothing the test cannot see. The zombie state is read back from
3071
- // `ps` rather than assumed: a platform that reaped it early would otherwise
3072
- // turn every assertion made against it into one about an ordinary dead pid.
3073
- async function zombiePid(t) {
3074
- const parent = spawn(process.execPath, ["-e", `
3075
- const { spawn } = require("node:child_process");
3076
- const { readFileSync, writeSync } = require("node:fs");
3077
- const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" });
3078
- child.on("exit", () => writeSync(1, "reaped\\n"));
3079
- writeSync(1, child.pid + "\\n");
3080
- readFileSync(0);
3081
- `], { stdio: ["pipe", "pipe", "inherit"] });
3082
- // The handle, never the bare pid: once exited, ChildProcess.kill() signals
3083
- // nothing, so a recycled pid is never hit.
3084
- t.after(() => parent.kill("SIGKILL"));
3085
- const lines = [];
3086
- let partial = "";
3087
- let closed = false;
3088
- const waiting = new Set();
3089
- const wake = () => { for (const w of waiting) w(); };
3090
- parent.stdout.setEncoding("utf8").on("data", (s) => {
3091
- const parts = (partial + s).split("\n");
3092
- partial = parts.pop();
3093
- lines.push(...parts);
3094
- wake();
3095
- });
3096
- parent.on("close", () => { closed = true; wake(); });
3097
- const line = (n) => new Promise((resolve, reject) => {
3098
- const done = (err) => {
3099
- clearTimeout(timer);
3100
- waiting.delete(check);
3101
- if (err) reject(err);
3102
- else resolve(lines[n - 1]);
3103
- };
3104
- const fail = (why) => done(new Error(`zombie fixture: no line ${n} (${why}); got ${JSON.stringify(lines)}`));
3105
- const timer = setTimeout(() => fail("5 s passed"), 5000);
3106
- const check = () => {
3107
- if (lines.length >= n) done();
3108
- else if (closed) fail("its parent exited");
3109
- };
3110
- waiting.add(check);
3111
- check();
3112
- });
3113
- const pid = Number(await line(1));
3114
- const deadline = Date.now() + 5000;
3115
- for (let stat; !(stat = psStat(pid)).startsWith("Z"); ) {
3116
- assert.ok(Date.now() < deadline, `pid ${pid} never became a zombie — ps stat ${JSON.stringify(stat)}`);
3117
- await new Promise((r) => setTimeout(r, 10));
3118
- }
3119
- const reap = async () => {
3120
- parent.stdin.end();
3121
- assert.equal(await line(2), "reaped", "the zombie's parent never reaped it");
3122
- };
3123
- return { pid, reap };
3124
- }
3125
-
3126
- const filedRows = (file) => (readFileSync(file, "utf8").match(/^- #\d+ /gm) ?? []).length;
3127
-
3128
- test("lock: 8 concurrent `filed` on a fresh ledger keep all 8 rows and all exit 0 (#531)", async (t) => {
3129
- const { file, cliAsync, residue } = lockFixture(t);
3130
- const results = await Promise.all(Array.from({ length: 8 }, (_, i) => cliAsync(["filed", String(100 + i), `concurrent subject ${i}`])));
3131
- assert.deepEqual(results.map((r) => r.status), Array(8).fill(0), results.map((r) => r.stderr).join("\n"));
3132
- assert.equal(filedRows(file), 8, `a concurrent writer lost a row:\n${readFileSync(file, "utf8")}`);
3133
- assert.deepEqual(residue(), []);
3134
- });
3135
-
3136
- test("lock: a lock left by a dead pid is taken over and the write lands (#531)", (t) => {
3137
- const { file, lock, cli, residue } = lockFixture(t);
3138
- writeFileSync(lock, String(deadPid()));
3139
- const r = cli(["filed", "7", "survives a dead holder"], { LEDGER_LOCK_TIMEOUT_MS: "2000" });
3140
- assert.equal(r.status, 0, r.stderr);
3141
- assert.match(readFileSync(file, "utf8"), /^- #7 survives a dead holder$/m);
3142
- assert.deepEqual(residue(), [], "the dead holder's lock, the reap lock or a temp file was left behind");
3143
- });
3144
-
3145
- test("lock: concurrent takeover of a dead-pid lock yields one holder at a time — all rows, all exit 0, no residue (#531)", async (t) => {
3146
- // The takeover is the part a naive unlink-then-create gets wrong: two
3147
- // waiters that both saw the dead pid each remove the other's fresh lock and
3148
- // write at once. All N rows surviving is what "one holder at a time" looks
3149
- // like from outside.
3150
- //
3151
- // THE CEILING: this pins the invariant, not the re-read under the reap lock
3152
- // that keeps it. That re-read only matters when a second waiter's stale
3153
- // read of the dead pid straddles the first waiter's whole takeover, a
3154
- // window of microseconds — measured, a mutant that unlinks unconditionally
3155
- // there lost a row in 3 of 40 rounds of this test. It is green on every
3156
- // round of the real lock, so a red here is always real; a green is not
3157
- // proof the re-read is still there.
3158
- const { file, lock, cliAsync, residue } = lockFixture(t);
3159
- writeFileSync(lock, String(deadPid()));
3160
- const results = await Promise.all(Array.from({ length: 8 }, (_, i) => cliAsync(["filed", String(200 + i), `takeover subject ${i}`])));
3161
- assert.deepEqual(results.map((r) => r.status), Array(8).fill(0), results.map((r) => r.stderr).join("\n"));
3162
- assert.equal(filedRows(file), 8, `a writer lost a row across the takeover:\n${readFileSync(file, "utf8")}`);
3163
- assert.deepEqual(residue(), []);
3164
- });
3165
-
3166
- test("lock: a lock held by a live pid times out at exit 2 naming it, and the ledger is byte-for-byte unchanged (#531)", (t) => {
3167
- const { file, lock, cli } = lockFixture(t);
3168
- writeFileSync(file, ledgerText(["#1 already here"]));
3169
- const before = readFileSync(file);
3170
- writeFileSync(lock, String(process.pid));
3171
- const r = cli(["filed", "2", "must not land"], { LEDGER_LOCK_TIMEOUT_MS: "150" });
3172
- assert.equal(r.status, 2, r.stderr);
3173
- assert.ok(r.stderr.includes(`ledger: cannot lock ${file} — held by pid ${process.pid}`), r.stderr);
3174
- assert.equal(r.stdout, "", "a timed-out write printed a payload");
3175
- assert.deepEqual(readFileSync(file), before, "the ledger changed under a lock this writer never got");
3176
- assert.equal(readFileSync(lock, "utf8"), String(process.pid), "a live holder's lock was taken over or removed");
3177
- });
3178
-
3179
- test("lock: every write subcommand takes the lock, before it validates anything (#531)", (t) => {
3180
- // One set names the writers; a subcommand missing from it writes unlocked
3181
- // and silently races every locked writer. Each call here would otherwise
3182
- // succeed or fail on its own terms, so exit 2 WITH the lock message is only
3183
- // reachable through the lock.
3184
- const { lock, cli } = lockFixture(t);
3185
- writeFileSync(lock, String(process.pid));
3186
- for (const args of [
3187
- ["row", "5", "a row"],
3188
- ["filed", "5", "a subject"],
3189
- ["ruled", "5", "a decision"],
3190
- ["dispatch", "5", "impl-5"],
3191
- ["settle", "impl-5", "PR#6"],
3192
- ["drain", "a reason"],
3193
- ]) {
3194
- const r = cli(args, { LEDGER_LOCK_TIMEOUT_MS: "50" });
3195
- assert.equal(r.status, 2, `${args[0]}: ${r.stderr}`);
3196
- assert.match(r.stderr, /cannot lock .* held by pid/, `${args[0]} wrote without the lock`);
3197
- }
3198
- });
3199
-
3200
- test("lock: reads take no lock — `check` and `read` answer while a live writer holds it (#531)", (t) => {
3201
- // The accept half: a lock that also gated the reads would put the
3202
- // duplicate-filing guard behind every concurrent write, and turn a slow
3203
- // writer into a `check` that refuses at exit 2 — nothing checked at all.
3204
- const { file, lock, cli } = lockFixture(t);
3205
- writeFileSync(file, ledgerText(["#9 widget guard missing"]));
3206
- writeFileSync(lock, String(process.pid));
3207
- const read = cli(["read"], { LEDGER_LOCK_TIMEOUT_MS: "50" });
3208
- assert.equal(read.status, 0, read.stderr);
3209
- assert.deepEqual(JSON.parse(read.stdout).filed, ["#9 widget guard missing"]);
3210
- const check = cli(["check", "widget guard missing"], { LEDGER_LOCK_TIMEOUT_MS: "50" });
3211
- assert.equal(check.status, 1, `check must still reach its ledger arm under a held lock: ${check.stderr}`);
3212
- assert.match(check.stderr, /ALREADY FILED/);
3213
- });
3214
-
3215
- test("lock: an unparseable holder is a live one — waited on, never signalled, never taken over, and the timeout names the lock file (#531, #2162)", (t) => {
3216
- // O_EXCL create and pid write are two steps, so an empty or partial lock is
3217
- // a normal thing for a waiter to read. process.kill(NaN, 0) throws
3218
- // ERR_INVALID_ARG_TYPE — a crash where a wait belongs. With no pid to name,
3219
- // the timeout names the lock file itself: an empty lock whose writer died
3220
- // mid-create never clears, and that path is what the operator removes.
3221
- const { file, lock, cli } = lockFixture(t);
3222
- for (const content of ["", "12ab", "0", "-5"]) {
3223
- writeFileSync(lock, content);
3224
- const r = cli(["filed", "3", "x"], { LEDGER_LOCK_TIMEOUT_MS: "50" });
3225
- assert.equal(r.status, 2, `${JSON.stringify(content)}: ${r.stderr}`);
3226
- assert.ok(
3227
- r.stderr.includes(`ledger: cannot lock ${file} — ${lock} holds ${JSON.stringify(content)}, not a pid`),
3228
- `${JSON.stringify(content)}: stderr does not name the lock file: ${r.stderr}`,
3229
- );
3230
- assert.match(r.stderr, /remove it by hand/, `${JSON.stringify(content)}: ${r.stderr}`);
3231
- assert.doesNotMatch(r.stderr, /held by pid/, `${JSON.stringify(content)}: an unparseable holder was reported as a pid: ${r.stderr}`);
3232
- assert.doesNotMatch(r.stderr, /ERR_INVALID_ARG_TYPE/);
3233
- assert.equal(readFileSync(lock, "utf8"), content, `an unparseable holder ${JSON.stringify(content)} was taken over`);
3234
- }
3235
- });
3236
-
3237
- test("lock: a reap lock left behind fails closed — the dead holder is named, nothing is removed (#531)", (t) => {
3238
- // A reap lock outliving its reaper means a takeover was in flight when it
3239
- // was SIGKILLed. Reclaiming it would need exactly the age heuristic the lock
3240
- // refuses, so waiters time out and the operator removes it.
3241
- const { file, lock, cli } = lockFixture(t);
3242
- const dead = deadPid();
3243
- writeFileSync(lock, String(dead));
3244
- writeFileSync(`${lock}.reap`, "");
3245
- const r = cli(["filed", "4", "x"], { LEDGER_LOCK_TIMEOUT_MS: "50" });
3246
- assert.equal(r.status, 2, r.stderr);
3247
- assert.ok(r.stderr.includes(`held by pid ${dead}`), r.stderr);
3248
- assert.ok(r.stderr.includes(`${lock}.reap`), `stderr does not name the stale reap lock: ${r.stderr}`);
3249
- assert.equal(readFileSync(lock, "utf8"), String(dead));
3250
- assert.ok(existsSync(`${lock}.reap`), "a stale reap lock was reclaimed");
3251
- assert.equal(existsSync(file), false, "a write landed without the lock");
3252
- });
3253
-
3254
- test("lock: a holder this process may not signal (EPERM) is live, never taken over (#531)", (t) => {
3255
- // pid 1 always exists. Unprivileged, kill(1, 0) is EPERM; as root it
3256
- // succeeds. Either way the holder is alive, and only ESRCH reads as dead —
3257
- // a takeover on EPERM would remove a running writer's lock.
3258
- const { file, lock, cli } = lockFixture(t);
3259
- writeFileSync(lock, "1");
3260
- const r = cli(["filed", "8", "x"], { LEDGER_LOCK_TIMEOUT_MS: "50" });
3261
- assert.equal(r.status, 2, r.stderr);
3262
- assert.ok(r.stderr.includes("held by pid 1"), r.stderr);
3263
- assert.ok(!r.stderr.includes("which is dead"), `a live EPERM holder was reported as dead: ${r.stderr}`);
3264
- assert.equal(readFileSync(lock, "utf8"), "1", "a live holder's lock was taken over");
3265
- assert.equal(existsSync(file), false, "a write landed without the lock");
3266
- });
3267
-
3268
- test("lock: a zombie holder — exited, never reaped — is live and times out, and is taken over once its parent reaps it (#2163)", async (t) => {
3269
- // run-team/SKILL.md's writer-policy runbook and ledger.mjs's lock header
3270
- // both promise this: kill(pid, 0) still succeeds on a zombie, because the OS
3271
- // keeps its pid reserved until reaped, so isDead() reads it as alive — and
3272
- // that clears on its own, with no hand removal, once the pid is reaped.
3273
- //
3274
- // A regression that skips isDead() in acquireLock()'s gate — treating any
3275
- // held lock as dead outright — does not fail this test with a clean
3276
- // assertion: `dead` is then always true, so the loop takes the
3277
- // reapDeadHolder() branch and `continue`s past the deadline check every
3278
- // pass, spinning on openSync(REAP)/closeSync/unlinkSync until something
3279
- // outside the lock's own 10 s budget kills it. A hang or CI timeout on
3280
- // this test, not an assertion failure, is that regression's signature.
3281
- const { file, lock, cli, residue } = lockFixture(t);
3282
- const zombie = await zombiePid(t);
3283
- writeFileSync(lock, String(zombie.pid));
3284
- const r = cli(["filed", "5", "must not land"], { LEDGER_LOCK_TIMEOUT_MS: "150" });
3285
- assert.equal(r.status, 2, r.stderr);
3286
- assert.ok(r.stderr.includes(`held by pid ${zombie.pid}`), r.stderr);
3287
- assert.ok(!r.stderr.includes("which is dead"), `a zombie holder was reported as dead: ${r.stderr}`);
3288
- assert.equal(readFileSync(lock, "utf8"), String(zombie.pid), "a zombie holder's lock was taken over before it was reaped");
3289
- assert.equal(existsSync(file), false, "a write landed under a zombie holder's lock");
3290
- assert.match(psStat(zombie.pid), /^Z/, "the holder stopped being a zombie during the wait, so the timeout proves nothing about zombies");
3291
-
3292
- await zombie.reap();
3293
- assert.throws(() => process.kill(zombie.pid, 0), { code: "ESRCH" }, `pid ${zombie.pid} was recycled before the test could use it`);
3294
- const after = cli(["filed", "5", "lands once reaped"], { LEDGER_LOCK_TIMEOUT_MS: "2000" });
3295
- assert.equal(after.status, 0, after.stderr);
3296
- assert.match(readFileSync(file, "utf8"), /^- #5 lands once reaped$/m);
3297
- assert.deepEqual(residue(), [], "the reaped holder's lock, the reap lock or a temp file was left behind");
3298
- });
3299
-
3300
- test("lock: a dead holder whose pid comes back to life before the unlink is not taken over — liveness is re-checked under the reap lock (#2088)", (t) => {
3301
- // Real pid reuse inside the microseconds between a waiter's isDead() and its
3302
- // unlink cannot be forced, and ledger.mjs carries no seam for it. So this
3303
- // stubs the OS answer itself, from outside, through Node's own --import
3304
- // preload: kill(pid, 0) reports ESRCH for the first probe of the planted
3305
- // pid and success for every probe after — exactly what a recycled pid looks
3306
- // like to the waiter. Each probe also records whether the reap lock existed
3307
- // at that moment, which is what separates a re-check UNDER the reap lock
3308
- // from a second probe taken before it (the same window, only narrower).
3309
- const { dir, file, lock, cli } = lockFixture(t);
3310
- const dead = deadPid();
3311
- const probes = join(dir, "probes.log");
3312
- const preload = join(dir, "reuse-preload.mjs");
3313
- writeFileSync(
3314
- preload,
3315
- `import { appendFileSync, existsSync } from "node:fs";
3316
- const realKill = process.kill.bind(process);
3317
- let calls = 0;
3318
- process.kill = (pid, sig) => {
3319
- if (pid !== ${dead} || sig !== 0) return realKill(pid, sig);
3320
- appendFileSync(${JSON.stringify(probes)}, (existsSync(${JSON.stringify(`${lock}.reap`)}) ? "reap" : "free") + "\\n");
3321
- if (calls++ === 0) throw Object.assign(new Error("kill ESRCH"), { code: "ESRCH" });
3322
- return true;
3323
- };
3324
- `,
3325
- );
3326
- writeFileSync(lock, String(dead));
3327
- const r = cli(["filed", "11", "x"], { LEDGER_LOCK_TIMEOUT_MS: "150", NODE_OPTIONS: `--import=${pathToFileURL(preload).href}` });
3328
- const seen = readFileSync(probes, "utf8").trim().split("\n");
3329
- assert.equal(seen[0], "free", "the first probe is the waiter's own, outside any reap lock");
3330
- assert.equal(seen[1], "reap", `the takeover must re-probe the pid while holding the reap lock: ${JSON.stringify(seen)}`);
3331
- assert.equal(r.status, 2, r.stderr);
3332
- assert.ok(r.stderr.includes(`held by pid ${dead}`), r.stderr);
3333
- assert.equal(readFileSync(lock, "utf8"), String(dead), "a holder live again at the re-check had its lock taken over");
3334
- assert.equal(existsSync(file), false, "a write landed over a live holder's lock");
3335
- assert.equal(existsSync(`${lock}.reap`), false, "the reap lock outlived a takeover that found its holder live");
3336
- });
3337
-
3338
- test("lock: a live writer that takes the lock between the re-check and the re-read is not deleted — liveness is checked before the read, not after (#2088)", (t) => {
3339
- // The prior test proves the re-check exists; this one proves the ORDER it
3340
- // runs in matters. Both `isDead(deadPid) && readLock() === String(deadPid)`
3341
- // and its operands reversed pass a re-check that never races anything, so a
3342
- // test that only ever changes the pid's liveness — never the lock's content
3343
- // — cannot tell the two orders apart. This one changes the lock's content
3344
- // from inside the liveness probe itself, timed to land exactly between the
3345
- // two calls: read-then-check would already have the stale pid in hand by
3346
- // then and delete a live writer's fresh lock; check-then-read sees the new
3347
- // content and backs off instead.
3348
- const { dir, file, lock, cli } = lockFixture(t);
3349
- const dead = deadPid();
3350
- const preload = join(dir, "swap-preload.mjs");
3351
- writeFileSync(
3352
- preload,
3353
- `import { writeFileSync } from "node:fs";
3354
- const realKill = process.kill.bind(process);
3355
- let calls = 0;
3356
- process.kill = (pid, sig) => {
3357
- if (pid !== ${dead} || sig !== 0) return realKill(pid, sig);
3358
- // The second liveness probe of the recycled pid is the re-check under the
3359
- // reap lock (the first is the caller's own, before it took the reap
3360
- // lock). A fresh writer — this very process — takes the lock in that same
3361
- // instant, landing on whichever side of the re-check the re-read runs.
3362
- if (++calls === 2) writeFileSync(${JSON.stringify(lock)}, String(process.pid));
3363
- throw Object.assign(new Error("kill ESRCH"), { code: "ESRCH" });
3364
- };
3365
- `,
3366
- );
3367
- writeFileSync(lock, String(dead));
3368
- const r = cli(["filed", "12", "x"], { LEDGER_LOCK_TIMEOUT_MS: "150", NODE_OPTIONS: `--import=${pathToFileURL(preload).href}` });
3369
- assert.equal(r.status, 2, r.stderr);
3370
- assert.ok(r.stderr.includes(`held by pid ${r.pid}`), r.stderr);
3371
- assert.equal(readFileSync(lock, "utf8"), String(r.pid), "a live writer's lock, taken between the re-check and the re-read, was deleted");
3372
- assert.equal(existsSync(file), false, "a write landed over a live holder's lock");
3373
- });
3374
-
3375
- test("lock: a dangling symlink at the lock path fails closed within the timeout, not a CPU spin (#531)", (t) => {
3376
- // `openSync(lock, "wx")` sees the dirent and reports EEXIST even when the
3377
- // symlink's target does not exist; every `readFileSync(lock)` after that
3378
- // reports ENOENT for a reason readLock()'s own "released between our
3379
- // failed create and this read" comment does not cover — the lock was
3380
- // never released, it is simply unreadable, and the create will report
3381
- // EEXIST again next time exactly as it did this time. Before this fix that
3382
- // combination skipped the deadline check entirely and spun at 100% CPU
3383
- // past the timeout this test bounds the whole run by.
3384
- const { dir, file, lock, cli } = lockFixture(t);
3385
- symlinkSync(join(dir, "nowhere"), lock);
3386
- const r = cli(["filed", "9", "x"], { LEDGER_LOCK_TIMEOUT_MS: "200" });
3387
- assert.equal(r.status, 2, r.stderr);
3388
- assert.match(r.stderr, /cannot lock .* exists but cannot be read/, r.stderr);
3389
- assert.equal(existsSync(file), false, "a write landed without the lock");
3390
- });
3391
-
3392
- // isDigits()'s job here is #1199's for LEDGER_GIT_TIMEOUT, restated for this
3393
- // override: the accepted spelling is digits alone, so anything Number()
3394
- // would still happily parse — a decimal point, a leading `-`, exponent
3395
- // notation — must be rejected FLAT rather than taken as a genuine, tiny
3396
- // bound. A regression that swapped
3397
- // `isDigits(String(v)) ? Number(v) : 0` for a bare `Number(v) || 0` would
3398
- // still pass every #531 test above unmodified, since none of them use a
3399
- // value Number() itself rejects — this is the discriminating case.
3400
- //
3401
- // Bounded fast rather than proven against the full 10 s default: the holder
3402
- // planted here never releases, so a value wrongly accepted as a genuine
3403
- // sub-second bound exits well inside this test's own short external
3404
- // timeout, where the correct fallback to the 10 s default is still running
3405
- // when that external timeout fires. spawnSync reports that as `ETIMEDOUT`,
3406
- // not as a raw signal kill — the child's own SIGTERM handler (acquireLock(),
3407
- // above) turns the timeout's SIGTERM into its own graceful `exit 2` first.
3408
- test("a malformed LEDGER_LOCK_TIMEOUT_MS override is rejected outright, not coerced by Number() (#531)", (t) => {
3409
- const { file, lock } = lockFixture(t);
3410
- writeFileSync(lock, String(process.pid));
3411
- for (const bad of ["1.5", "-5", "5e3", "abc"]) {
3412
- const r = spawnSync(process.execPath, [SCRIPT, "--file", file, "filed", "9", "x"], {
3413
- encoding: "utf8", timeout: 300,
3414
- env: { ...process.env, LEDGER_LOCK_TIMEOUT_MS: bad },
3415
- });
3416
- assert.equal(r.error?.code, "ETIMEDOUT",
3417
- `${JSON.stringify(bad)}: resolved before this test's own bound could prove it, meaning the malformed value became the wait (status ${r.status}, stderr ${r.stderr})`);
3418
- }
3419
- });
3420
-
3421
- // The other half of "can only shorten": a well-formed override ABOVE the
3422
- // 10 s default must clamp down to it, not stand as a 100 s (or longer)
3423
- // bound — the same claim #1199 proves for LEDGER_GIT_TIMEOUT, at the same
3424
- // real-time cost, because there is no fixed-latency "real answer" for a
3425
- // held lock to arrive at partway through the way a probe's own sleep gives
3426
- // that test.
3427
- test("LEDGER_LOCK_TIMEOUT_MS cannot lengthen the bound past 10 s, only shorten it (#531)", (t) => {
3428
- const { file, lock, cli } = lockFixture(t);
3429
- writeFileSync(lock, String(process.pid));
3430
- const t0 = Date.now();
3431
- const r = cli(["filed", "9", "x"], { LEDGER_LOCK_TIMEOUT_MS: "99999" });
3432
- const elapsed = Date.now() - t0;
3433
- assert.equal(r.status, 2, r.stderr);
3434
- assert.ok(elapsed < 11_000, `a 99999 ms override became the bound: waited ${elapsed} ms`);
3435
- assert.ok(elapsed >= 9_500, `exited before the untouched 10 s default could have fired: waited ${elapsed} ms`);
3436
- });