@feigi/fleet-ctl 0.0.0 → 3.16.3

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 (153) 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/citation-sweep-prose.test.mjs +59 -1
  37. package/scripts/claim-lifecycle.test.mjs +2 -1
  38. package/scripts/claim-ticket.test.mjs +35 -34
  39. package/scripts/closing-keyword-prose.test.mjs +1 -1
  40. package/scripts/cockpit-tick-nonblocking.test.mjs +8 -8
  41. package/scripts/compute-board.mjs +13 -3
  42. package/scripts/compute-board.test.mjs +64 -1
  43. package/scripts/compute-spend.mjs +46 -8
  44. package/scripts/compute-spend.test.mjs +64 -10
  45. package/scripts/cross-repo-citation-prose.test.mjs +18 -19
  46. package/scripts/delete-merged-branch.sh +218 -0
  47. package/scripts/delete-merged-branch.test.mjs +576 -0
  48. package/scripts/derive-testcmd.sh +18 -7
  49. package/scripts/derive-testcmd.test.mjs +9 -8
  50. package/scripts/diff-stats.mjs +2 -2
  51. package/scripts/diff-stats.test.mjs +7 -11
  52. package/scripts/dispatch-block-golden-prose.test.mjs +111 -6
  53. package/scripts/dispatch-block-pins-prose.test.mjs +5 -5
  54. package/scripts/dispositions-check.mjs +507 -0
  55. package/scripts/dispositions-check.test.mjs +843 -0
  56. package/scripts/dispositions-gate-prose.test.mjs +114 -0
  57. package/scripts/drop-merged-label.test.mjs +3 -4
  58. package/scripts/exec-stub.mjs +93 -0
  59. package/scripts/exec-stub.test.mjs +69 -0
  60. package/scripts/filing-bar-seat-prose.test.mjs +1 -1
  61. package/scripts/finisher-test-verdict-prose.test.mjs +102 -0
  62. package/scripts/fix-applier-correction-rules-prose.test.mjs +11 -10
  63. package/scripts/fleet-bootstrap +5 -20
  64. package/scripts/fleet-bootstrap.test.mjs +75 -0
  65. package/scripts/fleet-heartbeat.mjs +2 -2
  66. package/scripts/fleet-provenance +15 -24
  67. package/scripts/fleet-provenance.test.mjs +86 -12
  68. package/scripts/fleet-run.test.mjs +5 -5
  69. package/scripts/fleet-state.mjs +33 -11
  70. package/scripts/fleet-state.test.mjs +90 -3
  71. package/scripts/fleet-tick.mjs +346 -70
  72. package/scripts/fleet-tick.test.mjs +566 -16
  73. package/scripts/force-with-lease-reason-prose.test.mjs +1 -1
  74. package/scripts/frontmatter-check.mjs +3 -2
  75. package/scripts/frontmatter-check.test.mjs +6 -6
  76. package/scripts/immutable-body-claim-prose.test.mjs +53 -262
  77. package/scripts/implementer-model-tier.test.mjs +98 -506
  78. package/scripts/inflight.test.mjs +18 -127
  79. package/scripts/is-cli.mjs +26 -0
  80. package/scripts/is-cli.test.mjs +99 -0
  81. package/scripts/json.test.mjs +3 -3
  82. package/scripts/ledger-dispatch.test.mjs +368 -7
  83. package/scripts/ledger-grammar.mjs +85 -1
  84. package/scripts/ledger-grammar.test.mjs +86 -1
  85. package/scripts/ledger-read-require-file.test.mjs +7 -7
  86. package/scripts/ledger-rotate.test.mjs +142 -0
  87. package/scripts/ledger.mjs +181 -17
  88. package/scripts/ledger.test.mjs +12 -130
  89. package/scripts/main-checkout.mjs +312 -0
  90. package/scripts/main-checkout.test.mjs +332 -0
  91. package/scripts/member-outcomes-header.test.mjs +3 -3
  92. package/scripts/member-outcomes.mjs +4 -5
  93. package/scripts/member-outcomes.test.mjs +92 -18
  94. package/scripts/member-prompt-prose.test.mjs +17 -13
  95. package/scripts/member-record.mjs +8 -3
  96. package/scripts/member-record.test.mjs +5 -5
  97. package/scripts/member-write-guard.mjs +5 -5
  98. package/scripts/member-write-guard.test.mjs +6 -3
  99. package/scripts/no-undo-audit.sh +24 -21
  100. package/scripts/no-undo-audit.test.mjs +9 -13
  101. package/scripts/pointer-target-prose.test.mjs +1 -1
  102. package/scripts/pr-overlap.test.mjs +6 -9
  103. package/scripts/prompt-renderer.mjs +10 -9
  104. package/scripts/prose-pin.mjs +10 -11
  105. package/scripts/prove-merge.test.mjs +3 -3
  106. package/scripts/quiet-payload-prose.test.mjs +1 -1
  107. package/scripts/reap.test.mjs +3 -4
  108. package/scripts/release-label-split-prose.test.mjs +17 -2
  109. package/scripts/release-ticket.test.mjs +35 -44
  110. package/scripts/review-core-cwd-isolation.test.mjs +7 -6
  111. package/scripts/review-core-reads.test.mjs +1 -1
  112. package/scripts/review-core-scratch-refusal.test.mjs +64 -0
  113. package/scripts/review-core-shared-test-run.test.mjs +238 -0
  114. package/scripts/review-core-snapshot-path.test.mjs +59 -12
  115. package/scripts/review-core-specialist-scratch.test.mjs +12 -10
  116. package/scripts/review-core-testcmd.test.mjs +76 -45
  117. package/scripts/review-core-unrun.test.mjs +154 -168
  118. package/scripts/review-core.mjs +250 -56
  119. package/scripts/review-eval.mjs +11 -4
  120. package/scripts/review-host-fixture.mjs +12 -3
  121. package/scripts/review-in-run-retry.test.mjs +27 -3
  122. package/scripts/review-runner-spawns.test.mjs +5 -3
  123. package/scripts/review-runner.test.mjs +14 -3
  124. package/scripts/review-tier-audit.test.mjs +1 -1
  125. package/scripts/run-merge-bot-prose.test.mjs +29 -6
  126. package/scripts/scratch-partition-invariant-prose.test.mjs +1 -1
  127. package/scripts/section-between-guard-prose.test.mjs +4 -3
  128. package/scripts/select-dimensions.test.mjs +1 -1
  129. package/scripts/shell-traps-prose.test.mjs +6 -9
  130. package/scripts/shortlist.mjs +4 -1
  131. package/scripts/shortlist.test.mjs +30 -16
  132. package/scripts/snapshot-repo.test.mjs +177 -4
  133. package/scripts/stash-prohibition-prose.test.mjs +1 -1
  134. package/scripts/temp-dir.mjs +47 -0
  135. package/scripts/tier-check.mjs +95 -28
  136. package/scripts/tier-check.test.mjs +131 -29
  137. package/scripts/tier-outcomes-header.test.mjs +11 -54
  138. package/scripts/tier-outcomes.mjs +34 -12
  139. package/scripts/tier-outcomes.test.mjs +157 -4
  140. package/scripts/tier-roles.mjs +118 -29
  141. package/scripts/tier-roles.test.mjs +226 -61
  142. package/scripts/tracker-block-copy-prose.test.mjs +3 -3
  143. package/scripts/verify-sha.test.mjs +4 -5
  144. package/scripts/watcher-degraded-block.test.mjs +5 -8
  145. package/scripts/within-run-pair-prose.test.mjs +43 -75
  146. package/scripts/worktree-audit.test.mjs +2 -1
  147. package/skills/next-ticket/SKILL.md +2 -2
  148. package/skills/run-team/SKILL.md +433 -303
  149. package/skills/run-team/references/ci-and-staleness.md +7 -6
  150. package/skills/run-team/references/correction-tickets.md +3 -3
  151. package/skills/run-team/references/isolation.md +1 -1
  152. package/skills/sizing-a-ticket/SKILL.md +8 -8
  153. package/scripts/tier-guard-gate-prose.test.mjs +0 -216
@@ -12,18 +12,13 @@
12
12
  import { test } from "node:test";
13
13
  import assert from "node:assert/strict";
14
14
  import { spawn, spawnSync } from "node:child_process";
15
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync, chmodSync, existsSync, readFileSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
15
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
16
16
  import { tmpdir } from "node:os";
17
17
  import { join } from "node:path";
18
18
  import { fileURLToPath, pathToFileURL } from "node:url";
19
- import { stripComments } from "./strip-comments.mjs";
19
+ import { writeExecStub } from "./exec-stub.mjs";
20
20
 
21
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
22
  // #155's fix resolves the ledger's own repository with a real `git`
28
23
  // subprocess (both here in test setup and inside ledger.mjs itself), so PATH
29
24
  // cannot simply be reduced to the stub's directory the way `gh` alone used
@@ -43,16 +38,7 @@ if (!REAL_GIT) throw new Error("ledger.test.mjs setup: could not locate a `git`
43
38
  // silently assert the offline path instead. The `|| [ -n "$line" ]` guard emits
44
39
  // the last line of a fixture written without a trailing newline, which is what
45
40
  // 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
41
  const GH_STUB = `#!/bin/sh
55
- case " $* " in *" --fleet-warm "*) exit 0 ;; esac
56
42
  printf '%s\\n' "$@" > "$GH_ARGS_FILE"
57
43
  pwd -P > "$GH_CWD_FILE"
58
44
  printf 'GIT_DIR=%s\\nGH_REPO=%s\\n' "\${GIT_DIR-}" "\${GH_REPO-}" > "$GH_ENV_FILE"
@@ -173,40 +159,10 @@ function run(subject, { filed = [], hits = [], ghFails = false, ghGarbage = fals
173
159
  symlinkSync(REAL_GIT, join(bin, "git"));
174
160
  if (gh) {
175
161
  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 });
162
+ // No warm-up exec: `writeExecStub` links the trampoline exec-stub.mjs
163
+ // already exec'd at import, so this stub's first exec pays no OS scan
164
+ // inside the 20 s budget ledger.mjs puts on its gh child.
165
+ writeExecStub(ghPath, GH_STUB);
210
166
  }
211
167
  // No `stdio` override on purpose: the default pipe is what makes `r.stderr`
212
168
  // readable at all. spawnSync drains stdout and stderr concurrently, so the
@@ -265,59 +221,6 @@ function queryOf(r) {
265
221
  return r.ghArgv[r.ghArgv.indexOf("--search") + 1];
266
222
  }
267
223
 
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
224
  const FILED_114 =
322
225
  "#114 fleet-plugin-design Non-zero column written from intent — audit 11 rows (review-pr-108)";
323
226
  const FILED_131 = "#131 run-merge-bot.md exit-2 documentation gap in the merge loop";
@@ -2928,7 +2831,7 @@ for (const [cmd, args] of [["row", ["7", "impl-7 · class=routine"]], ["filed",
2928
2831
  // ---------------------------------------------------------------------------
2929
2832
 
2930
2833
  // `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
2834
+ // other invocation instant. `/bin/sleep` absolute: PATH is this
2932
2835
  // fixture's own bin, which holds `git` and `gh` and nothing else.
2933
2836
  //
2934
2837
  // The stall RELEASES the captured pipes before it begins, and that detail is
@@ -2964,35 +2867,14 @@ function gitFixture(t, gitBody) {
2964
2867
  writeFileSync(file, ledgerText([]));
2965
2868
 
2966
2869
  const gitPath = join(bin, "git");
2967
- writeFileSync(gitPath, gitBody.replace("__DIR__", dir));
2968
- chmodSync(gitPath, 0o755);
2870
+ writeExecStub(gitPath, gitBody.replace("__DIR__", dir));
2969
2871
  // 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.
2872
+ // one by something better than an exit code both of them share. Neither stub
2873
+ // is warmed: `writeExecStub` links an already-scanned inode, so no first-exec
2874
+ // scan lands inside the bounded region these cases measure.
2977
2875
  const ghSentinel = join(dir, "gh-ran");
2978
2876
  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 });
2877
+ writeExecStub(ghPath, `#!/bin/sh\n: > '${ghSentinel}'\nprintf '[]\\n'\n`);
2996
2878
 
2997
2879
  const env = { ...process.env, PATH: bin };
2998
2880
  delete env.GIT_DIR;
@@ -0,0 +1,312 @@
1
+ #!/usr/bin/env node
2
+ // Main-checkout dirty detection (#2210) — the backstop behind #1411's
3
+ // member-write-guard. The guard refuses a member's `write`/`edit` into the
4
+ // main checkout before it runs; it cannot see an `eval` cell (the shared
5
+ // kernel's cwd IS the main checkout, and `eval` takes no cwd), `bash` command
6
+ // text that `cd`s or `git -C`s there, or bash from a member the cwd rule does
7
+ // not cover. This file catches what lands anyway: fleet-tick.mjs runs
8
+ // `checkMainCheckout()` on every invocation and, on anything but `clean`,
9
+ // holds every dispatching row until the maintainer clears it.
10
+ //
11
+ // THE BASELINE. Recorded once per run, in Phase 0 beside `instruments.sh
12
+ // --pin` (after the fast-forward, before anything reads), at
13
+ // `<workspace>/.fleet/main-checkout.sha` — instruments.sh's own
14
+ // `.fleet/instruments.sha` precedent. It holds the main checkout's
15
+ // `git status --porcelain -uall` entries AND a content hash of every path
16
+ // they name, so the maintainer's own uncommitted work at run start is allowed
17
+ // (it is in the baseline) while a further edit to one of those files is still
18
+ // caught (its hash moves). Any entry that appears, any that disappears, any
19
+ // hash that changes: `dirty`.
20
+ //
21
+ // THE PROTECTED SET is exactly the non-ignored paths of the main checkout —
22
+ // what #1411's guard protects. `.fleet/`, `.worktrees/` and `.agent-brain/`
23
+ // are gitignored in a fleet repo, so run state, members' worktrees and
24
+ // agent-brain's cache never appear in porcelain and never trip this.
25
+ // Explicit `-uall`, never bare `--porcelain`: `status.showUntrackedFiles=no`
26
+ // silences untracked files otherwise (#730).
27
+ //
28
+ // THE RUN'S OWN BOOKKEEPING IS NOT A STRAY WRITE. Two tracked files in the
29
+ // main checkout are written by the controller itself mid-run:
30
+ // `docs/metrics/tier-outcomes.tsv`, appended each time it rules a PR's review
31
+ // (run-team/SKILL.md, `tier-outcomes.mjs append`), and
32
+ // `docs/metrics/member-outcomes.tsv`, rewritten by the member-facts scrape.
33
+ // Compared like any other path, the first append would hold every
34
+ // dispatching row for the rest of the run, and clearing it with `--record`
35
+ // after every ruling would certify whatever stray write landed beside it.
36
+ // So `snapshot()` leaves exactly those two paths out, for the reason
37
+ // instruments.sh leaves `docs/metrics/` out of its pin. Two named files, not
38
+ // the directory: anything else under `docs/metrics/` is still a stray write.
39
+ // The price: a member's leaked write to one of those two files goes unseen.
40
+ //
41
+ // FOUR ANSWERS, worktree-audit.sh's three plus the baseline's own refusal:
42
+ // clean — the porcelain entries and hashes equal the baseline's.
43
+ // dirty — they do not; `changed` names every path that differs.
44
+ // unknown — some read failed: git, a hash, or a baseline that EXISTS but
45
+ // cannot be read (unreadable file, unsearchable `.fleet/`,
46
+ // dangling symlink, not written by --record). "A failure is an
47
+ // unknown answer, never a 'no'" — never `clean`.
48
+ // absent — no baseline at all: the run never recorded one. A refusal
49
+ // ("record at run start"), never `clean`.
50
+ //
51
+ // RE-BASELINING OVERWRITES, IT DOES NOT COMPARE (#1058). `--record` writes
52
+ // whatever the tree looks like now, so it is the maintainer's clear only
53
+ // AFTER the stray paths are resolved. Over `unknown` it would walk the run
54
+ // from "could not look" to "certified clean" in one step, so it refuses on
55
+ // every unknown cause it can see: a baseline that exists but cannot be read,
56
+ // and any failed git or hash read (no snapshot, nothing to write).
57
+ //
58
+ // ROOT. The main checkout is the parent of `git rev-parse --git-common-dir`
59
+ // (git-env.mjs's `workspaceDirFromGitCommonDir`, as fleet-tick.mjs resolves
60
+ // the shortlist) — never `--show-toplevel`, which answers a WORKTREE's root
61
+ // from inside one — and every git child gets `gitEnv()`, so an ambient
62
+ // GIT_DIR/GIT_WORK_TREE cannot answer for another repository (#1599).
63
+ //
64
+ // CLI:
65
+ // main-checkout.mjs --record write the baseline (Phase 0; or the
66
+ // maintainer's clear once stray paths are
67
+ // resolved). Exit 0 written, 2 refused.
68
+ // main-checkout.mjs --check print the state. Exit 0 clean, 1 dirty,
69
+ // 2 unknown or no baseline.
70
+ //
71
+ // Zero deps: `node --test plugin/scripts/main-checkout.test.mjs`.
72
+
73
+ import { spawnSync } from "node:child_process";
74
+ import { createHash } from "node:crypto";
75
+ import { lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, writeFileSync } from "node:fs";
76
+ import { join } from "node:path";
77
+ import { isCLI } from "./is-cli.mjs";
78
+ import { makeDie, defineFlags } from "./arg.mjs";
79
+ import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
80
+
81
+ export const BASELINE_FILE = "main-checkout.sha";
82
+ export const RECORD_COMMAND = "~/.fleet/bin/fleet-run main-checkout.mjs --record";
83
+ const RUN_BOOKKEEPING = new Set(["docs/metrics/tier-outcomes.tsv", "docs/metrics/member-outcomes.tsv"]);
84
+ const HEADER = "fleet main-checkout baseline v1";
85
+ const GIT_TIMEOUT_MS = 30_000;
86
+ const MAX_BUFFER = 64 * 1024 * 1024;
87
+ const NAME = "main-checkout";
88
+ const die = makeDie(NAME);
89
+
90
+ // The one git primitive. `gitEnv()` drops an ambient GIT_DIR/GIT_WORK_TREE
91
+ // (#1599); LC_ALL=C keeps a failure's last line readable as git wrote it.
92
+ // `what` names the call in a failure, since `why` is printed to the operator.
93
+ function git(what, args, cwd, env) {
94
+ const r = spawnSync("git", args, {
95
+ cwd, encoding: "utf8", maxBuffer: MAX_BUFFER, timeout: GIT_TIMEOUT_MS,
96
+ env: gitEnv({ LC_ALL: "C" }, env),
97
+ });
98
+ if (!r.error && r.status === 0) return { ok: true, stdout: r.stdout };
99
+ if (r.error) return { ok: false, why: `${what} did not run: ${r.error.code ?? r.error.message}` };
100
+ const last = String(r.stderr ?? "").trim().split("\n").at(-1);
101
+ return { ok: false, why: `${what} ${r.signal ? `killed by ${r.signal}` : `exited ${r.status}`}${last ? `: ${last}` : ""}` };
102
+ }
103
+
104
+ /** The main checkout `cwd` belongs to: `{ok, root}` or `{ok: false, why}`. */
105
+ export function resolveMainCheckout(cwd = process.cwd(), env = process.env) {
106
+ const r = git("git rev-parse --git-common-dir", ["rev-parse", "--git-common-dir"], cwd, env);
107
+ if (!r.ok) return r;
108
+ const root = workspaceDirFromGitCommonDir(r.stdout, cwd);
109
+ return root === null ? { ok: false, why: "git rev-parse --git-common-dir answered nothing" } : { ok: true, root };
110
+ }
111
+
112
+ export const baselinePath = (root) => join(root, ".fleet", BASELINE_FILE);
113
+
114
+ // A content hash of one path porcelain named, relative to the main checkout.
115
+ // Gone is an answer (a deleted tracked file is a ` D` entry), and so is a
116
+ // directory (an untracked nested repository is listed as `dir/`); anything
117
+ // else that fails to read throws, and the caller's answer is `unknown`.
118
+ function hashPath(root, rel) {
119
+ const abs = join(root, rel);
120
+ let st;
121
+ try {
122
+ st = lstatSync(abs);
123
+ } catch (e) {
124
+ if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return "absent";
125
+ throw e;
126
+ }
127
+ const sha = (buf) => createHash("sha256").update(buf).digest("hex");
128
+ if (st.isSymbolicLink()) return `link:${sha(readlinkSync(abs))}`;
129
+ if (st.isDirectory()) return "dir";
130
+ if (st.isFile()) return `sha256:${sha(readFileSync(abs))}`;
131
+ return "other";
132
+ }
133
+
134
+ /**
135
+ * The main checkout as it stands: `{ok, entries}` — a Map from each porcelain
136
+ * entry (`XY path`) to its path's hash, the run's own bookkeeping left out
137
+ * (header) — or `{ok: false, why}`.
138
+ * `--no-optional-locks` so a read never takes the main index's lock out from
139
+ * under the controller's own git; `-z` so no path is quoted or split;
140
+ * `--no-renames` so every entry names exactly one path.
141
+ */
142
+ export function snapshot(root, env = process.env) {
143
+ const r = git("git status --porcelain -uall", ["--no-optional-locks", "status", "--porcelain", "-uall", "-z", "--no-renames"], root, env);
144
+ if (!r.ok) return r;
145
+ const entries = new Map();
146
+ for (const line of r.stdout.split("\0")) {
147
+ if (!line) continue;
148
+ if (line.length < 4 || line[2] !== " ") return { ok: false, why: `git status printed an entry it does not document: ${JSON.stringify(line)}` };
149
+ const rel = line.slice(3);
150
+ if (RUN_BOOKKEEPING.has(rel)) continue;
151
+ try {
152
+ entries.set(line, hashPath(root, rel));
153
+ } catch (e) {
154
+ return { ok: false, why: `cannot hash ${rel}: ${e?.code ?? e?.message ?? e}` };
155
+ }
156
+ }
157
+ return { ok: true, entries };
158
+ }
159
+
160
+ export function formatBaseline(entries) {
161
+ const body = [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
162
+ .map(([line, hash]) => `${hash}\t${JSON.stringify(line)}\n`).join("");
163
+ return `${HEADER}\n${body}`;
164
+ }
165
+
166
+ /**
167
+ * The run's baseline: `{status: "ok", entries}`, `{status: "absent"}`, or
168
+ * `{status: "unreadable", why}`. ABSENT is only "nothing at that name": a
169
+ * dangling symlink is present-but-broken, and an unsearchable `.fleet/`
170
+ * answers EACCES rather than ENOENT, so neither can fall through to
171
+ * "no baseline" (#1058's mislabel) — both are `unreadable`.
172
+ */
173
+ export function readBaseline(path) {
174
+ let text;
175
+ try {
176
+ text = readFileSync(path, "utf8");
177
+ } catch (e) {
178
+ if (e?.code === "ENOENT") {
179
+ try {
180
+ lstatSync(path);
181
+ return { status: "unreadable", why: `${path} is a dangling symlink` };
182
+ } catch (l) {
183
+ if (l?.code === "ENOENT") return { status: "absent" };
184
+ return { status: "unreadable", why: `${path}: ${l?.code ?? l?.message}` };
185
+ }
186
+ }
187
+ return { status: "unreadable", why: `${path} exists but cannot be read: ${e?.code ?? e?.message}` };
188
+ }
189
+ const lines = text.split("\n");
190
+ if (lines[0] !== HEADER || lines.at(-1) !== "") {
191
+ return { status: "unreadable", why: `${path} is not a baseline main-checkout.mjs --record wrote` };
192
+ }
193
+ const entries = new Map();
194
+ for (const l of lines.slice(1, -1)) {
195
+ const tab = l.indexOf("\t");
196
+ let line;
197
+ try { line = tab > 0 ? JSON.parse(l.slice(tab + 1)) : null; } catch { line = null; }
198
+ if (typeof line !== "string") return { status: "unreadable", why: `${path} carries a line --record never writes: ${JSON.stringify(l)}` };
199
+ entries.set(line, l.slice(0, tab));
200
+ }
201
+ return { status: "ok", entries };
202
+ }
203
+
204
+ /** Every path whose entry appeared, disappeared or changed hash, sorted. */
205
+ export function changedPaths(baseline, current) {
206
+ const paths = new Set();
207
+ for (const [line, hash] of current) if (baseline.get(line) !== hash) paths.add(line.slice(3));
208
+ for (const line of baseline.keys()) if (!current.has(line)) paths.add(line.slice(3));
209
+ return [...paths].sort();
210
+ }
211
+
212
+ /**
213
+ * The tick's question: `{state, root?, baseline?, changed?, why?, cause?}`.
214
+ * `cause` tells the two unknowns apart — `"baseline"` (it exists but cannot
215
+ * be read) from `"read"` (git or a hash failed) — since each has its own
216
+ * message. The baseline is read before the tree, because without one there
217
+ * is nothing to compare against and no reason to look.
218
+ */
219
+ export function checkMainCheckout({ cwd = process.cwd(), env = process.env } = {}) {
220
+ const where = resolveMainCheckout(cwd, env);
221
+ if (!where.ok) return { state: "unknown", cause: "read", why: where.why };
222
+ const { root } = where;
223
+ const path = baselinePath(root);
224
+ const base = readBaseline(path);
225
+ if (base.status === "absent") return { state: "absent", root, baseline: path };
226
+ if (base.status === "unreadable") return { state: "unknown", cause: "baseline", root, baseline: path, why: base.why };
227
+ const now = snapshot(root, env);
228
+ if (!now.ok) return { state: "unknown", cause: "read", root, baseline: path, why: now.why };
229
+ const changed = changedPaths(base.entries, now.entries);
230
+ return changed.length ? { state: "dirty", root, baseline: path, changed } : { state: "clean", root, baseline: path };
231
+ }
232
+
233
+ // A path printed on one line: anything that would split or blur it is quoted.
234
+ const shown = (p) => (/[\s"\\\x00-\x1f\x7f]/.test(p) ? JSON.stringify(p) : p);
235
+
236
+ /**
237
+ * The one line the tick prints for a check that is not `clean`, or null.
238
+ * `live` names the run's live members: concurrent members make a change
239
+ * impossible to attribute to one of them, so the line names them all and
240
+ * attributes nothing. `null` (the `--check` CLI, which reads no ledger)
241
+ * leaves them out.
242
+ */
243
+ export function describe(check, live = null) {
244
+ const members = live === null ? "" : `; live members: ${live.length ? live.join(" ") : "none"}`;
245
+ switch (check.state) {
246
+ case "clean":
247
+ return null;
248
+ case "dirty":
249
+ return `MAIN-CHECKOUT-DIRTY ${check.changed.map(shown).join(" ")} — changed since the run's baseline${members}`
250
+ + ` — dispatch held: resolve the stray paths FIRST, then re-baseline with ${RECORD_COMMAND} (it overwrites, it does not compare)`;
251
+ case "absent":
252
+ return `MAIN-CHECKOUT-NO-BASELINE no baseline at ${check.baseline} — dispatch held: record it at run start with ${RECORD_COMMAND}`;
253
+ default:
254
+ return check.cause === "baseline"
255
+ ? `MAIN-CHECKOUT-UNKNOWN baseline unreadable: ${check.why}${members}`
256
+ + " — dispatch held: fix the baseline so it can be read; NEVER re-baseline over it, --record overwrites rather than compares"
257
+ : `MAIN-CHECKOUT-UNKNOWN could not look: ${check.why}${members}`
258
+ + " — dispatch held: fix the failure and tick again; NEVER re-baseline over it, --record overwrites rather than compares";
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Write the baseline: `{ok, path, entries}` or `{ok: false, why}`. Refuses
264
+ * over a baseline that exists but cannot be read — overwriting it blind
265
+ * discards evidence nobody read (#1058) — and on any failed read of the tree.
266
+ * Written to a temporary name and renamed, so a reader never sees half of it.
267
+ */
268
+ export function recordBaseline({ cwd = process.cwd(), env = process.env } = {}) {
269
+ const where = resolveMainCheckout(cwd, env);
270
+ if (!where.ok) return { ok: false, why: `${where.why} — cannot find the main checkout` };
271
+ const path = baselinePath(where.root);
272
+ const prior = readBaseline(path);
273
+ if (prior.status === "unreadable") {
274
+ return { ok: false, why: `${prior.why} — fix it first; do NOT --record over it, --record overwrites rather than compares` };
275
+ }
276
+ const now = snapshot(where.root, env);
277
+ if (!now.ok) return { ok: false, why: `${now.why} — could not look, so there is nothing to record` };
278
+ try {
279
+ mkdirSync(join(where.root, ".fleet"), { recursive: true });
280
+ const tmp = `${path}.${process.pid}.tmp`;
281
+ writeFileSync(tmp, formatBaseline(now.entries));
282
+ renameSync(tmp, path);
283
+ } catch (e) {
284
+ return { ok: false, why: `cannot write ${path}: ${e?.code ?? e?.message}` };
285
+ }
286
+ return { ok: true, path, entries: now.entries.size };
287
+ }
288
+
289
+ function main() {
290
+ // sweep()/stray() first, so an unknown flag or a stray positional is
291
+ // refused in arg.mjs's one wording before the usage guard can answer.
292
+ const { has, sweep, stray } = defineFlags(die, { flags: { record: "bool", check: "bool" } });
293
+ sweep();
294
+ stray();
295
+ const record = has("record");
296
+ if (record === has("check")) die("usage: main-checkout.mjs --record | --check");
297
+ if (record) {
298
+ const r = recordBaseline();
299
+ if (!r.ok) die(r.why);
300
+ console.log(`main-checkout: recorded ${r.entries} porcelain entr${r.entries === 1 ? "y" : "ies"} at ${r.path}`);
301
+ return;
302
+ }
303
+ const c = checkMainCheckout();
304
+ if (c.state === "clean") {
305
+ console.log(`main-checkout: clean against ${c.baseline}`);
306
+ return;
307
+ }
308
+ console.log(describe(c));
309
+ process.exitCode = c.state === "dirty" ? 1 : 2;
310
+ }
311
+
312
+ if (isCLI(import.meta.url)) main();