@feigi/fleet-ctl 0.0.0 → 3.16.2

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 (152) hide show
  1. package/agents/{fleet-implementer.agent.md → fleet-implementer-slow-high.agent.md} +23 -2
  2. package/agents/fleet-implementer-slow-medium.agent.md +231 -0
  3. package/agents/fleet-implementer-smol-high.agent.md +231 -0
  4. package/agents/{fleet-implementer-alt.agent.md → fleet-implementer-task-high.agent.md} +23 -2
  5. package/agents/fleet-implementer-task-max.agent.md +231 -0
  6. package/agents/fleet-review-comments.agent.md +4 -2
  7. package/agents/fleet-review-correctness.agent.md +2 -1
  8. package/agents/fleet-review-runner.agent.md +14 -10
  9. package/agents/fleet-review-silent-failure.agent.md +4 -3
  10. package/agents/fleet-review-simplify.agent.md +2 -1
  11. package/agents/fleet-review-snapshot.agent.md +2 -1
  12. package/agents/fleet-review-test-run.agent.md +29 -0
  13. package/agents/fleet-review-tests.agent.md +10 -5
  14. package/agents/fleet-review-types.agent.md +4 -2
  15. package/agents/fleet-review-verifier.agent.md +4 -3
  16. package/commands/review-and-fix.md +7 -6
  17. package/commands/run-merge-bot.md +14 -4
  18. package/package.json +4 -2
  19. package/scripts/agent-test.test.mjs +36 -32
  20. package/scripts/ambient-git-vars-mjs-prose.test.mjs +23 -13
  21. package/scripts/apply-ruleset.test.mjs +4 -3
  22. package/scripts/arg-header-probes-prose.test.mjs +1 -0
  23. package/scripts/arg.test.mjs +18 -18
  24. package/scripts/board-cli.test.mjs +18 -21
  25. package/scripts/board-identity.test.mjs +9 -9
  26. package/scripts/board-liveness-banner.test.mjs +6 -6
  27. package/scripts/board-prev-shape.test.mjs +12 -13
  28. package/scripts/board-tryparse-null.test.mjs +7 -7
  29. package/scripts/board.mjs +4 -7
  30. package/scripts/board.test.mjs +57 -61
  31. package/scripts/candidates.test.mjs +228 -17
  32. package/scripts/ci-completes-premise-prose.test.mjs +1 -1
  33. package/scripts/ci-state-prose.test.mjs +2 -2
  34. package/scripts/ci-state.mjs +389 -187
  35. package/scripts/ci-state.test.mjs +458 -165
  36. package/scripts/claim-lifecycle.test.mjs +2 -1
  37. package/scripts/claim-ticket.test.mjs +35 -34
  38. package/scripts/closing-keyword-prose.test.mjs +1 -1
  39. package/scripts/cockpit-tick-nonblocking.test.mjs +8 -8
  40. package/scripts/compute-board.mjs +13 -3
  41. package/scripts/compute-board.test.mjs +64 -1
  42. package/scripts/compute-spend.mjs +46 -8
  43. package/scripts/compute-spend.test.mjs +64 -10
  44. package/scripts/cross-repo-citation-prose.test.mjs +18 -19
  45. package/scripts/delete-merged-branch.sh +218 -0
  46. package/scripts/delete-merged-branch.test.mjs +576 -0
  47. package/scripts/derive-testcmd.sh +18 -7
  48. package/scripts/derive-testcmd.test.mjs +9 -8
  49. package/scripts/diff-stats.mjs +2 -2
  50. package/scripts/diff-stats.test.mjs +7 -11
  51. package/scripts/dispatch-block-golden-prose.test.mjs +111 -6
  52. package/scripts/dispatch-block-pins-prose.test.mjs +5 -5
  53. package/scripts/dispositions-check.mjs +507 -0
  54. package/scripts/dispositions-check.test.mjs +843 -0
  55. package/scripts/dispositions-gate-prose.test.mjs +114 -0
  56. package/scripts/drop-merged-label.test.mjs +3 -4
  57. package/scripts/exec-stub.mjs +93 -0
  58. package/scripts/exec-stub.test.mjs +69 -0
  59. package/scripts/filing-bar-seat-prose.test.mjs +1 -1
  60. package/scripts/finisher-test-verdict-prose.test.mjs +102 -0
  61. package/scripts/fix-applier-correction-rules-prose.test.mjs +11 -10
  62. package/scripts/fleet-bootstrap +5 -20
  63. package/scripts/fleet-bootstrap.test.mjs +75 -0
  64. package/scripts/fleet-heartbeat.mjs +2 -2
  65. package/scripts/fleet-provenance +15 -24
  66. package/scripts/fleet-provenance.test.mjs +86 -12
  67. package/scripts/fleet-run.test.mjs +5 -5
  68. package/scripts/fleet-state.mjs +33 -11
  69. package/scripts/fleet-state.test.mjs +90 -3
  70. package/scripts/fleet-tick.mjs +346 -70
  71. package/scripts/fleet-tick.test.mjs +566 -16
  72. package/scripts/force-with-lease-reason-prose.test.mjs +1 -1
  73. package/scripts/frontmatter-check.mjs +3 -2
  74. package/scripts/frontmatter-check.test.mjs +6 -6
  75. package/scripts/immutable-body-claim-prose.test.mjs +53 -262
  76. package/scripts/implementer-model-tier.test.mjs +98 -506
  77. package/scripts/inflight.test.mjs +18 -127
  78. package/scripts/is-cli.mjs +26 -0
  79. package/scripts/is-cli.test.mjs +99 -0
  80. package/scripts/json.test.mjs +3 -3
  81. package/scripts/ledger-dispatch.test.mjs +368 -7
  82. package/scripts/ledger-grammar.mjs +85 -1
  83. package/scripts/ledger-grammar.test.mjs +86 -1
  84. package/scripts/ledger-read-require-file.test.mjs +7 -7
  85. package/scripts/ledger-rotate.test.mjs +142 -0
  86. package/scripts/ledger.mjs +181 -17
  87. package/scripts/ledger.test.mjs +12 -130
  88. package/scripts/main-checkout.mjs +312 -0
  89. package/scripts/main-checkout.test.mjs +332 -0
  90. package/scripts/member-outcomes-header.test.mjs +3 -3
  91. package/scripts/member-outcomes.mjs +4 -5
  92. package/scripts/member-outcomes.test.mjs +92 -18
  93. package/scripts/member-prompt-prose.test.mjs +17 -13
  94. package/scripts/member-record.mjs +8 -3
  95. package/scripts/member-record.test.mjs +5 -5
  96. package/scripts/member-write-guard.mjs +5 -5
  97. package/scripts/member-write-guard.test.mjs +6 -3
  98. package/scripts/no-undo-audit.sh +24 -21
  99. package/scripts/no-undo-audit.test.mjs +9 -13
  100. package/scripts/pointer-target-prose.test.mjs +1 -1
  101. package/scripts/pr-overlap.test.mjs +6 -9
  102. package/scripts/prompt-renderer.mjs +10 -9
  103. package/scripts/prose-pin.mjs +10 -11
  104. package/scripts/prove-merge.test.mjs +3 -3
  105. package/scripts/quiet-payload-prose.test.mjs +1 -1
  106. package/scripts/reap.test.mjs +3 -4
  107. package/scripts/release-label-split-prose.test.mjs +17 -2
  108. package/scripts/release-ticket.test.mjs +35 -44
  109. package/scripts/review-core-cwd-isolation.test.mjs +7 -6
  110. package/scripts/review-core-reads.test.mjs +1 -1
  111. package/scripts/review-core-scratch-refusal.test.mjs +64 -0
  112. package/scripts/review-core-shared-test-run.test.mjs +238 -0
  113. package/scripts/review-core-snapshot-path.test.mjs +59 -12
  114. package/scripts/review-core-specialist-scratch.test.mjs +12 -10
  115. package/scripts/review-core-testcmd.test.mjs +76 -45
  116. package/scripts/review-core-unrun.test.mjs +154 -168
  117. package/scripts/review-core.mjs +250 -56
  118. package/scripts/review-eval.mjs +11 -4
  119. package/scripts/review-host-fixture.mjs +12 -3
  120. package/scripts/review-in-run-retry.test.mjs +27 -3
  121. package/scripts/review-runner-spawns.test.mjs +5 -3
  122. package/scripts/review-runner.test.mjs +14 -3
  123. package/scripts/review-tier-audit.test.mjs +1 -1
  124. package/scripts/run-merge-bot-prose.test.mjs +29 -6
  125. package/scripts/scratch-partition-invariant-prose.test.mjs +1 -1
  126. package/scripts/section-between-guard-prose.test.mjs +4 -3
  127. package/scripts/select-dimensions.test.mjs +1 -1
  128. package/scripts/shell-traps-prose.test.mjs +6 -9
  129. package/scripts/shortlist.mjs +4 -1
  130. package/scripts/shortlist.test.mjs +30 -16
  131. package/scripts/snapshot-repo.test.mjs +177 -4
  132. package/scripts/stash-prohibition-prose.test.mjs +1 -1
  133. package/scripts/temp-dir.mjs +47 -0
  134. package/scripts/tier-check.mjs +95 -28
  135. package/scripts/tier-check.test.mjs +131 -29
  136. package/scripts/tier-outcomes-header.test.mjs +11 -54
  137. package/scripts/tier-outcomes.mjs +34 -12
  138. package/scripts/tier-outcomes.test.mjs +157 -4
  139. package/scripts/tier-roles.mjs +118 -29
  140. package/scripts/tier-roles.test.mjs +226 -61
  141. package/scripts/tracker-block-copy-prose.test.mjs +3 -3
  142. package/scripts/verify-sha.test.mjs +4 -5
  143. package/scripts/watcher-degraded-block.test.mjs +5 -8
  144. package/scripts/within-run-pair-prose.test.mjs +43 -75
  145. package/scripts/worktree-audit.test.mjs +2 -1
  146. package/skills/next-ticket/SKILL.md +2 -2
  147. package/skills/run-team/SKILL.md +433 -303
  148. package/skills/run-team/references/ci-and-staleness.md +7 -6
  149. package/skills/run-team/references/correction-tickets.md +3 -3
  150. package/skills/run-team/references/isolation.md +1 -1
  151. package/skills/sizing-a-ticket/SKILL.md +8 -8
  152. package/scripts/tier-guard-gate-prose.test.mjs +0 -216
@@ -3,7 +3,7 @@
3
3
  // "Provenance check"). Names the live Install root — the realpath of omp's
4
4
  // `node_modules/@feigi/fleet-ctl` package entry, the one path every install kind
5
5
  // places (ADR 0021) — its kind and recorded version, and hashes the placed
6
- // Resolver (`~/.fleet/bin/fleet-run`) against each install's own copy and
6
+ // Resolver (`~/.fleet/bin/fleet-run`) against the Install root's own copy and
7
7
  // refuses on drift. Writes nothing, mutates no config — every path below is
8
8
  // read-only.
9
9
  //
@@ -103,33 +103,24 @@ function digestScriptsDir(root) {
103
103
  return { digest: sha256(Buffer.from(lines.join("\n") + "\n", "utf8")), fileCount: listed.files.length };
104
104
  }
105
105
 
106
- // Which install kind produced this root, from where the package entry points:
107
- // a symlink resolving inside omp's plugin cache → a marketplace install; the
108
- // entry itself a real directory under node_modules (not a symlink) → an npm
109
- // install; a symlink pointing anywhere else → a linked checkout. Compare
110
- // canonicalized paths — macOS resolves /tmp through /private/tmp (measured;
111
- // the same reason fleet-bootstrap's canonical() exists), so a raw string
112
- // prefix misreports an npm install as an unknown shape on those boxes.
113
- function kindOf(res) {
114
- const { packagePath, installPath, isLink } = res;
115
- let nodeModules;
116
- try {
117
- nodeModules = fs.realpathSync(path.dirname(packagePath));
118
- } catch {
119
- nodeModules = path.dirname(packagePath);
120
- }
121
- if (isLink) {
122
- if (installPath.includes(`${path.sep}.omp${path.sep}plugins${path.sep}cache${path.sep}`)) return "marketplace-install";
123
- return "linked-checkout";
124
- }
125
- if (installPath.startsWith(nodeModules + path.sep)) return "npm-install";
126
- return "unrecognized-install-shape";
106
+ // Which install kind produced this root, read off the package entry itself:
107
+ // a real directory (not a symlink) → an npm install, which unpacks into
108
+ // node_modules; a symlink resolving inside omp's plugin cache → a
109
+ // marketplace install; a symlink pointing anywhere else → a linked checkout.
110
+ // No path-prefix test decides the npm case: a non-link entry's realpath is
111
+ // always its own parent's realpath plus its name, so every non-link shape is
112
+ // that one kind.
113
+ function kindOf({ installPath, isLink }) {
114
+ if (!isLink) return "npm-install";
115
+ return installPath.includes(`${path.sep}.omp${path.sep}plugins${path.sep}cache${path.sep}`)
116
+ ? "marketplace-install"
117
+ : "linked-checkout";
127
118
  }
128
119
 
129
120
  function main() {
130
121
  const argv = process.argv.slice(2);
131
- for (let i = 0; i < argv.length; i++) {
132
- process.stderr.write(`${NAME}: unrecognized argument ${argv[i]}\n`);
122
+ if (argv.length > 0) {
123
+ process.stderr.write(`${NAME}: unrecognized argument ${argv[0]}\n`);
133
124
  process.exit(2);
134
125
  }
135
126
 
@@ -1,6 +1,7 @@
1
- // The Provenance check's scripts/ digest (ADR 0021): it certifies the whole
2
- // file set under `<Install root>/scripts`, so a subtree it cannot list must
3
- // fail the digest rather than shrink it. Driven through the real CLI —
1
+ // The Provenance check (ADR 0021): which install kind the Install root is,
2
+ // its recorded version, the scripts/ digest over the whole file set under
3
+ // `<Install root>/scripts`, Resolver drift, and the exit contract (0 clean,
4
+ // 1 drift, 2 nothing to resolve). Driven through the real CLI —
4
5
  // fleet-provenance reads `os.homedir()` directly and `process.exit()`s.
5
6
  //
6
7
  // Every fixture's env is built from scratch (never `...process.env`), so
@@ -22,31 +23,104 @@ function runProvenance(home) {
22
23
  });
23
24
  }
24
25
 
25
- // A marketplace-shaped install whose scripts/ holds a top-level file and one
26
- // nested subdirectory, with the Resolver placed byte-identical to the
27
- // installed copy so drift never decides the exit code.
28
- function fakeInstall() {
29
- const home = mkdtempSync(join(tmpdir(), "fleet-provenance-home-"));
30
- const payload = join(home, ".omp", "plugins", "cache", "a");
26
+ // A payload whose scripts/ holds a top-level file and one nested
27
+ // subdirectory carrying a dotfile, so a walk that skipped either shrinks
28
+ // the file count.
29
+ function writePayload(payload) {
31
30
  const sub = join(payload, "scripts", "sub");
32
31
  mkdirSync(sub, { recursive: true });
33
32
  writeFileSync(join(payload, "scripts", "fleet-run"), "resolver\n");
34
- writeFileSync(join(sub, "hidden.mjs"), "nested\n");
33
+ writeFileSync(join(sub, ".hidden"), "nested\n");
34
+ return sub;
35
+ }
36
+
37
+ // An install of the given kind, with the Resolver placed byte-identical to
38
+ // the installed copy so drift never decides the exit code:
39
+ // marketplace — node_modules entry symlinked into omp's plugin cache;
40
+ // npm — node_modules entry a real directory (what npm unpacks);
41
+ // link — node_modules entry symlinked to a checkout elsewhere.
42
+ function fakeInstall(kind = "marketplace") {
43
+ const home = mkdtempSync(join(tmpdir(), "fleet-provenance-home-"));
35
44
  const nm = join(home, ".omp", "plugins", "node_modules");
45
+ const entry = join(nm, "@feigi", "fleet-ctl");
36
46
  mkdirSync(join(nm, "@feigi"), { recursive: true });
37
- symlinkSync(payload, join(nm, "@feigi", "fleet-ctl"));
47
+ let sub;
48
+ if (kind === "npm") {
49
+ sub = writePayload(entry);
50
+ } else {
51
+ const payload = kind === "marketplace"
52
+ ? join(home, ".omp", "plugins", "cache", "a")
53
+ : join(home, "checkout", "plugin");
54
+ sub = writePayload(payload);
55
+ symlinkSync(payload, entry);
56
+ }
38
57
  mkdirSync(join(home, ".fleet", "bin"), { recursive: true });
39
58
  writeFileSync(join(home, ".fleet", "bin", "fleet-run"), "resolver\n");
40
59
  return { home, sub };
41
60
  }
42
61
 
43
- test("a readable nested subdirectory is digested with the rest of scripts/", () => {
62
+ const NOTICE = /NOTICE: Install root is a linked checkout/;
63
+
64
+ for (const [kind, expected] of [["npm", "npm-install"], ["marketplace", "marketplace-install"]]) {
65
+ test(`a ${kind}-shaped install reports kind ${expected}, exit 0, no linked-checkout NOTICE`, () => {
66
+ const { home } = fakeInstall(kind);
67
+ const r = runProvenance(home);
68
+ assert.equal(r.status, 0, `expected success, got status ${r.status}: ${r.stdout}${r.stderr}`);
69
+ assert.match(r.stdout, new RegExp(`^fleet-provenance: kind: ${expected}$`, "m"));
70
+ assert.doesNotMatch(r.stdout, NOTICE);
71
+ });
72
+ }
73
+
74
+ test("a link to a checkout outside omp's cache reports kind linked-checkout and a NOTICE, still exit 0", () => {
75
+ const { home } = fakeInstall("link");
76
+ const r = runProvenance(home);
77
+ assert.equal(r.status, 0, `a link is the dev loop, not a failure: status ${r.status}: ${r.stdout}${r.stderr}`);
78
+ assert.match(r.stdout, /^fleet-provenance: kind: linked-checkout$/m);
79
+ assert.match(r.stdout, NOTICE);
80
+ });
81
+
82
+ test("the version line reads the lock entry, and says none recorded without one", () => {
83
+ const { home } = fakeInstall("npm");
84
+ assert.match(runProvenance(home).stdout, /^fleet-provenance: version: \(none recorded\)$/m);
85
+ writeFileSync(
86
+ join(home, ".omp", "plugins", "omp-plugins.lock.json"),
87
+ JSON.stringify({ plugins: { "@feigi/fleet-ctl": { version: "1.2.3" } } }),
88
+ );
89
+ assert.match(runProvenance(home).stdout, /^fleet-provenance: version: 1\.2\.3$/m);
90
+ });
91
+
92
+ test("no node_modules/@feigi/fleet-ctl entry: exit 2, stderr names the missing plugin, nothing certified", () => {
93
+ const home = mkdtempSync(join(tmpdir(), "fleet-provenance-home-"));
94
+ const r = runProvenance(home);
95
+ assert.equal(r.status, 2, `expected a resolution refusal, got status ${r.status}: ${r.stdout}`);
96
+ assert.match(r.stderr, /no omp plugin "@feigi\/fleet-ctl"/);
97
+ assert.equal(r.stdout, "");
98
+ });
99
+
100
+ test("a placed Resolver that differs from the installed copy refuses as drift, exit 1", () => {
101
+ const { home } = fakeInstall("npm");
102
+ writeFileSync(join(home, ".fleet", "bin", "fleet-run"), "stale resolver\n");
103
+ const r = runProvenance(home);
104
+ assert.equal(r.status, 1, `expected drift to fail the check, got status ${r.status}: ${r.stdout}`);
105
+ assert.match(r.stdout, /Resolver drift: REFUSED/);
106
+ });
107
+
108
+ test("a readable nested subdirectory, dotfiles included, is digested with the rest of scripts/", () => {
44
109
  const { home } = fakeInstall();
45
110
  const r = runProvenance(home);
46
111
  assert.equal(r.status, 0, `expected success, got status ${r.status}: ${r.stdout}${r.stderr}`);
47
112
  assert.match(r.stdout, /scripts\/ digest: sha256 [0-9a-f]{64} \(2 files\)/);
48
113
  });
49
114
 
115
+ test("an empty scripts/ makes the digest UNAVAILABLE rather than certifying nothing", () => {
116
+ const home = mkdtempSync(join(tmpdir(), "fleet-provenance-home-"));
117
+ const entry = join(home, ".omp", "plugins", "node_modules", "@feigi", "fleet-ctl");
118
+ mkdirSync(join(entry, "scripts"), { recursive: true });
119
+ const r = runProvenance(home);
120
+ assert.match(r.stdout, /scripts\/ digest: UNAVAILABLE — no files under .*scripts — refusing to certify an empty set/);
121
+ assert.doesNotMatch(r.stdout, /scripts\/ digest: sha256/);
122
+ });
123
+
50
124
  test("an unlistable nested subdirectory makes the digest UNAVAILABLE, never a shorter file set", (t) => {
51
125
  if (process.platform === "win32" || process.getuid?.() === 0) {
52
126
  t.skip("chmod 000 does not deny a directory listing here");
@@ -10,8 +10,8 @@
10
10
  import { test } from "node:test";
11
11
  import assert from "node:assert/strict";
12
12
  import { spawnSync } from "node:child_process";
13
- import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, realpathSync } from "node:fs";
14
- import { tmpdir } from "node:os";
13
+ import { mkdirSync, writeFileSync, symlinkSync, realpathSync } from "node:fs";
14
+ import { tempDir } from "./temp-dir.mjs";
15
15
  import { join } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
 
@@ -30,7 +30,7 @@ function runFleetRun(home, args, extraEnv = {}) {
30
30
  // realpath (macOS resolves tmpdir through /private, and the resolver applies
31
31
  // realpathSync, so expectations must too).
32
32
  function fakeInstall() {
33
- const home = mkdtempSync(join(tmpdir(), "fleet-run-home-"));
33
+ const home = tempDir("fleet-run-home-");
34
34
  const payload = join(home, ".omp", "plugins", "cache", "a");
35
35
  mkdirSync(join(payload, "scripts"), { recursive: true });
36
36
  writeFileSync(join(payload, "scripts", "probe.mjs"), "content\n");
@@ -49,7 +49,7 @@ test("node_modules/@feigi/fleet-ctl present: --root prints its realpath, no noti
49
49
  });
50
50
 
51
51
  test("node_modules/@feigi/fleet-ctl absent: exit 2, stderr names ~/.omp/plugins/node_modules/@feigi/fleet-ctl", () => {
52
- const home = mkdtempSync(join(tmpdir(), "fleet-run-home-"));
52
+ const home = tempDir("fleet-run-home-");
53
53
  const r = runFleetRun(home, ["--root"]);
54
54
  assert.equal(r.status, 2, `expected a resolver refusal, got status ${r.status}: ${r.stdout}`);
55
55
  assert.match(r.stderr, /no omp plugin "@feigi\/fleet-ctl"/);
@@ -57,7 +57,7 @@ test("node_modules/@feigi/fleet-ctl absent: exit 2, stderr names ~/.omp/plugins/
57
57
  });
58
58
 
59
59
  test("a dangling link is named as dangling, not as a missing entry", () => {
60
- const home = mkdtempSync(join(tmpdir(), "fleet-run-home-"));
60
+ const home = tempDir("fleet-run-home-");
61
61
  const nm = join(home, ".omp", "plugins", "node_modules");
62
62
  mkdirSync(join(nm, "@feigi"), { recursive: true });
63
63
  symlinkSync(join(home, "does", "not", "exist"), join(nm, "@feigi", "fleet-ctl"));
@@ -32,7 +32,7 @@
32
32
  // One writer per key. A key both scripts wrote would need locking to be
33
33
  // correct, and neither script is in a position to hold one.
34
34
 
35
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
35
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
36
36
  import { spawnSync } from "node:child_process";
37
37
  import { dirname, join } from "node:path";
38
38
  import { workspaceDirFromGitCommonDir } from "./git-env.mjs";
@@ -205,6 +205,19 @@ export function readState(path, name) {
205
205
  // remainder — an interval that can never complete — so fleet-heartbeat treats
206
206
  // a failed write as a fire instead of counting progress that nothing is
207
207
  // keeping.
208
+ //
209
+ // The write is a sibling temp file renamed over the target, ledger.mjs save()'s
210
+ // convention, because the readers do not hold still for it (#2349). A plain
211
+ // writeFileSync truncates and then writes, and readState() maps the empty or
212
+ // half-written file a reader can land on to the fresh, no-mark state on
213
+ // purpose — so a reader racing a live beat read "no mark", and ledger.mjs
214
+ // rotate, which refuses only while a mark is beating, moved a live
215
+ // controller's ledger. rename is atomic on POSIX: a reader sees the whole old
216
+ // file or the whole new one. The temp name carries the pid for the reason
217
+ // ledger.mjs gives (#531): two scripts write this file, and a shared temp name
218
+ // lets one rename the other's out from under it. A temp that never made it
219
+ // into place is removed rather than left to accumulate, one per failed
220
+ // invocation, beside the file it failed to replace.
208
221
  export function writeState(path, name, prev, patch) {
209
222
  // Built from the VALIDATED view plus the fields outside the schema, never
210
223
  // from the raw parse: see `rest` in readState above.
@@ -224,11 +237,16 @@ export function writeState(path, name, prev, patch) {
224
237
  ...(prev.ticked ? { ticked: prev.ticked } : {}),
225
238
  ...patch,
226
239
  };
240
+ const tmp = `${path}.${process.pid}.tmp`;
227
241
  try {
228
242
  mkdirSync(dirname(path), { recursive: true });
229
- writeFileSync(path, `${JSON.stringify(next, null, 2)}\n`);
243
+ writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);
244
+ renameSync(tmp, path);
230
245
  return true;
231
246
  } catch (e) {
247
+ // Best-effort and never fatal: a cleanup that threw would turn a reported,
248
+ // survived write failure into the crash the comment above rules out.
249
+ try { rmSync(tmp, { force: true }); } catch {}
232
250
  console.error(`${name}: WARNING could not write ${path} (${e.message}) — back-off progress will not persist`);
233
251
  return false;
234
252
  }
@@ -306,15 +324,19 @@ export function assessBeat({ beat, ticked, now }) {
306
324
  const intervalMs = beat.interval * 1000;
307
325
  const seen = { at: beat.at, ageMs, intervalMs, overdueMs: Math.max(0, ageMs - intervalMs) };
308
326
  if (beat.stopped) return { ...seen, kind: "stopped", reason: beat.stopped };
309
- const beatOverdue = ageMs > intervalMs * BEAT_GRACE;
310
- // Absent `ticked` — every caller before #1597's follow-up, and any state
311
- // file fleet-tick has not yet written to — reads as infinitely old, which
312
- // is `beat` alone deciding it exactly as before. A present one only ever
313
- // shortens the window to "beating"; it can never manufacture a stale verdict
314
- // `beat` alone would not have reached.
315
- const tickedAgeMs = ticked ? Math.max(0, now - ticked.at) : Infinity;
316
- const tickedFresh = tickedAgeMs <= DEFAULT_CEILING_S * 1000 * BEAT_GRACE;
317
- return { ...seen, kind: beatOverdue && !tickedFresh ? "stale" : "beating", reason: null };
327
+ return { ...seen, kind: now > stallsAt({ beat, ticked }) ? "stale" : "beating", reason: null };
328
+ }
329
+
330
+ // The instant an unstopped mark turns `stale`: past `beat`'s own interval
331
+ // plus grace AND past a tick's ceiling window plus grace, whichever ends
332
+ // later. An absent `ticked` — a state file fleet-tick has not yet written to
333
+ // — contributes nothing, which is `beat` alone deciding it. A present one
334
+ // only ever postpones the stall; it can never manufacture a stale verdict
335
+ // `beat` alone would not have reached. Exported for the readers that must
336
+ // say WHEN a beating mark would stop counting, not only whether it has.
337
+ export function stallsAt({ beat, ticked }) {
338
+ const beatEnds = beat.at + beat.interval * 1000 * BEAT_GRACE;
339
+ return ticked ? Math.max(beatEnds, ticked.at + DEFAULT_CEILING_S * 1000 * BEAT_GRACE) : beatEnds;
318
340
  }
319
341
 
320
342
  // Whether this verdict is something to report. Exported because both readers
@@ -13,13 +13,13 @@
13
13
 
14
14
  import test from "node:test";
15
15
  import assert from "node:assert/strict";
16
- import { spawnSync } from "node:child_process";
17
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, symlinkSync } from "node:fs";
16
+ import { spawn, spawnSync } from "node:child_process";
17
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, symlinkSync, linkSync } from "node:fs";
18
18
  import { tmpdir } from "node:os";
19
19
  import { join } from "node:path";
20
20
  import { fileURLToPath } from "node:url";
21
21
 
22
- import { readState, writeState, assessBeat, isStalled, stallReport, BEAT_GRACE, DEFAULT_CEILING_S } from "./fleet-state.mjs";
22
+ import { readState, writeState, assessBeat, isStalled, stallReport, stallsAt, BEAT_GRACE, DEFAULT_CEILING_S } from "./fleet-state.mjs";
23
23
 
24
24
  const SCRIPT = fileURLToPath(new URL("./fleet-state.mjs", import.meta.url));
25
25
 
@@ -178,6 +178,74 @@ test("writeState: `ticked` survives a heartbeat write the same way `beat` surviv
178
178
  rmSync(dir, { recursive: true, force: true });
179
179
  });
180
180
 
181
+ test("writeState: the file a reader already opened is replaced whole, never rewritten in place", () => {
182
+ // #2349. readState maps an empty or half-written file to the no-mark state
183
+ // on purpose, so a write that truncated heartbeat.json and then filled it
184
+ // let a reader landing in between see "no mark" on a live run — and
185
+ // ledger.mjs rotate, which refuses only while a mark is beating, moved the
186
+ // live controller's ledger. A hard link stands in for that reader: it holds
187
+ // the inode the reader opened. An in-place write changes what it sees; a
188
+ // rename leaves it the complete old version while the path gets the new.
189
+ const dir = mkdtempSync(join(tmpdir(), "fleet-state-atomic-"));
190
+ const path = join(dir, "heartbeat.json");
191
+ const held = join(dir, "held-by-reader");
192
+ const old = { at: 1_700_000_000_000, interval: 300, stopped: "" };
193
+ writeFileSync(path, JSON.stringify({ quiet: 0, elapsed: 0, digest: "", beat: old }));
194
+ linkSync(path, held);
195
+ const beat = { at: 1_700_000_300_000, interval: 300, stopped: "" };
196
+ assert.equal(writeState(path, "fleet-state-test", readState(path, "fleet-state-test"), { beat }), true);
197
+ assert.deepEqual(readState(held, "fleet-state-test").beat, old, "the write rewrote the file a reader holds in place");
198
+ assert.deepEqual(readState(path, "fleet-state-test").beat, beat);
199
+ rmSync(dir, { recursive: true, force: true });
200
+ });
201
+
202
+ test("writeState: a write that cannot land leaves no temp file behind", () => {
203
+ // The temp is written first and renamed second, so a rename that fails —
204
+ // here the target is a directory — would otherwise strand one
205
+ // `heartbeat.json.<pid>.tmp` per failed invocation beside the file, each
206
+ // heartbeat run a new pid.
207
+ const dir = mkdtempSync(join(tmpdir(), "fleet-state-unlandable-"));
208
+ const path = join(dir, "heartbeat.json");
209
+ mkdirSync(path);
210
+ writeFileSync(join(path, "occupant"), "x");
211
+ assert.equal(writeState(path, "fleet-state-test", readState(path, "fleet-state-test"), { quiet: 1 }), false);
212
+ assert.deepEqual(readdirSync(dir), ["heartbeat.json"]);
213
+ rmSync(dir, { recursive: true, force: true });
214
+ });
215
+
216
+ test("writeState: two scripts writing the file at once both land — neither takes the other's temp", async () => {
217
+ // fleet-tick and fleet-heartbeat both write heartbeat.json, each its own
218
+ // process. A temp name the two share lets one rename the other's temp out
219
+ // from under it, and the loser's rename fails on ENOENT — a reported write
220
+ // failure that fleet-heartbeat treats as a fire (#531's race, ledger.mjs's
221
+ // own temp). Timing decides only whether the two loops overlap, never
222
+ // whether correct code passes: two pid-named temps cannot collide. Measured
223
+ // with the shared name `${path}.tmp` instead, it failed on each of six runs.
224
+ const dir = mkdtempSync(join(tmpdir(), "fleet-state-concurrent-"));
225
+ const path = join(dir, "heartbeat.json");
226
+ const writer = `
227
+ const { readState, writeState } = await import(${JSON.stringify(new URL("./fleet-state.mjs", import.meta.url).href)});
228
+ let fails = 0;
229
+ for (let i = 0; i < 300; i++) {
230
+ if (!writeState(${JSON.stringify(path)}, "writer", readState(${JSON.stringify(path)}, "writer"), { digest: String(i).repeat(500) })) fails++;
231
+ }
232
+ console.log(fails);
233
+ `;
234
+ const run = () => new Promise((resolve) => {
235
+ const child = spawn(process.execPath, ["--input-type=module", "-e", writer]);
236
+ let out = "", err = "";
237
+ child.stdout.on("data", (d) => { out += d; });
238
+ child.stderr.on("data", (d) => { err += d; });
239
+ child.on("close", (status) => resolve({ status, out: out.trim(), err }));
240
+ });
241
+ const results = await Promise.all([run(), run()]);
242
+ rmSync(dir, { recursive: true, force: true });
243
+ for (const r of results) {
244
+ assert.equal(r.status, 0, r.err);
245
+ assert.equal(r.out, "0", `writes failed under a concurrent writer:\n${r.err}`);
246
+ }
247
+ });
248
+
181
249
  test("assessBeat: staleness is judged against the RECORDED interval, not a constant", () => {
182
250
  // The whole reason the mark carries an interval. A quiet night backs off to
183
251
  // the ceiling, so the same twenty-minute silence is a healthy beat at
@@ -235,6 +303,25 @@ test("assessBeat: a busy run's own `ticked` covers for a `beat` the busy stretch
235
303
  assert.equal(assessBeat({ beat: stopped, ticked: { at: now - 1000 }, now }).kind, "stopped");
236
304
  });
237
305
 
306
+ test("stallsAt: a tick's window ends at the ceiling times grace, and only ever postpones `beat`'s own end", () => {
307
+ const now = 2_000_000_000_000;
308
+ // A beat already past its own window, so the tick alone decides — pinned on
309
+ // both sides of the edge, the same pair the beat boundary above uses.
310
+ const beat = { at: now - 11 * 60 * 1000, interval: 300, stopped: "" };
311
+ const tickEdge = DEFAULT_CEILING_S * 1000 * BEAT_GRACE;
312
+ assert.equal(stallsAt({ beat, ticked: { at: now - tickEdge } }), now);
313
+ assert.equal(assessBeat({ beat, ticked: { at: now - tickEdge }, now }).kind, "beating");
314
+ assert.equal(assessBeat({ beat, ticked: { at: now - tickEdge - 1 }, now }).kind, "stale");
315
+
316
+ // The later of the two windows wins: a long recorded interval outlives an
317
+ // old tick, so the tick must not cut that beat short.
318
+ const long = { at: now - 30 * 60 * 1000, interval: 1200, stopped: "" };
319
+ const oldTick = { at: now - 2 * tickEdge };
320
+ assert.equal(stallsAt({ beat: long, ticked: oldTick }), long.at + 1200 * 1000 * BEAT_GRACE);
321
+ assert.equal(assessBeat({ beat: long, ticked: oldTick, now }).kind, "beating");
322
+ assert.equal(stallsAt({ beat: long }), long.at + 1200 * 1000 * BEAT_GRACE, "no tick is `beat` alone");
323
+ });
324
+
238
325
  test("assessBeat: a recorded stop is reported whatever its age, and outranks staleness", () => {
239
326
  // A stop that had to wait two intervals to be believed is a stop reported
240
327
  // after the only window in which anyone could act on it — and it is the one