@feigi/fleet-ctl 0.0.0

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