@feigi/fleet-ctl 3.75.1 → 3.76.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feigi/fleet-ctl",
3
- "version": "3.75.1",
3
+ "version": "3.76.0",
4
4
  "description": "Agent fleet: run-team controller, merge bot, PR reviewer, and the ticket pipeline they share",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -19,30 +19,20 @@
19
19
  // `spend`, never change a ticket's stage.
20
20
  //
21
21
  // That transcript tree is keyed by PROJECT DIRECTORY, not by session, and one
22
- // directory can hold several sessions at once. `serve` therefore resolves ONE
23
- // session's transcript directory and keeps it for its whole life — see
24
- // spendDirPin() below — rather than re-picking the newest on every tick and
25
- // alternating between two live runs' numbers in silence.
26
- //
27
- // LIMITATION, stated rather than solved: the session it keeps is whichever
28
- // FIRST writes a transcript at or after the pin's own construction.
29
- // Before that, a session that was already active when the pin was built —
30
- // this run's own, mid-EACCES-fault, or a genuinely previous run's — is never
31
- // latched; the pin keeps re-asking findSubagentsDir() every tick instead,
32
- // which is what lets a transient fault or a stale session recover instead of
33
- // freezing the panel for the server's whole life. What is not solved: two
34
- // sessions that BOTH start writing after the pin exists, in the same project
35
- // directory, are still indistinguishable — the board is scoped to a
36
- // workspace and a workspace does not know that — so the first of them
37
- // to pass the newest-transcript check wins and keeps winning. `--spend-dir
38
- // <path>` is how an operator names the right one: it overrides the
39
- // heuristic outright.
22
+ // directory can hold several sessions at once, so nothing in the tree says
23
+ // which session is this run's. The run says it: phase 0 records the
24
+ // controller's own session directory in its receipt, `.fleet/phase0.json`,
25
+ // and receiptSpendDir() below reads it back on every tick — never latched,
26
+ // because a cockpit outlives the run that launched it and has to follow the
27
+ // next run's receipt. `--spend-dir <path>` overrides the receipt outright.
40
28
 
41
- import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
29
+ import { readFileSync, existsSync, statSync } from "node:fs";
42
30
  import { computeSpend, attributeTools, mergeTools } from "./compute-spend.mjs";
43
31
  import {
44
- encodeProjectDir, isOmpSessionDirName, ompSessionTranscripts, foldOmpTranscript, ompMemberRecord,
32
+ isOmpSessionDirName, ompSessionTranscripts, foldOmpTranscript, ompMemberRecord,
45
33
  } from "./member-record.mjs";
34
+ import { readReceipt } from "./phase0-receipt.mjs";
35
+ import { RECEIPT } from "./ledger-grammar.mjs";
46
36
  import { NAME, warnOnce, execRead } from "./board-common.mjs";
47
37
  import { mergedReadPrs } from "./compute-board.mjs";
48
38
  // The heartbeat's liveness mark and the controller record beside it, read here
@@ -398,161 +388,46 @@ export function mapCi(ciJson, pr) {
398
388
  return "unknown";
399
389
  }
400
390
 
401
- // Where this session's member transcripts live:
402
- // ~/.omp/agent/sessions/<encoded-cwd>/<ISO>_<uuid>/
403
- //
404
- // The session uuid is not knowable from here, so take the most recently
405
- // active one. Rank on the newest TRANSCRIPT mtime, not on the session
406
- // directory's own: a directory's mtime moves when an entry is created or
407
- // removed, never when a file inside it is appended to. Ranking on the
408
- // directory therefore tracked the last agent SPAWN rather than the last
409
- // agent activity — and since the cockpit launches in run-team phase 0,
410
- // before the first agent spawns, the live session has no transcript yet and
411
- // a PREVIOUS session won. The board would render a prior run's spend as
412
- // this run's, then silently switch when the first agent landed. That is the
413
- // one failure mode here that produces confidently wrong numbers rather than
414
- // no numbers.
415
- //
416
- // Returns { error } when there is no project dir for this cwd — a bug that
417
- // never fixes itself — and null when one resolves but holds no sessions
418
- // yet, which is normal at run start. Collapsing those two into one bare
419
- // null is what hid the encoding bug above. A listing that THROWS is
420
- // { error } too.
421
- export function findSubagentsDir(home = process.env.HOME, cwd = process.cwd()) {
422
- try {
423
- const tree = sessionDirs(home, cwd);
424
- if (tree.dirs === null) {
425
- return { error: `no transcript dir for cwd ${cwd} (looked in ${tree.root})` };
426
- }
427
- const cands = tree.dirs
428
- .map((d) => ({ d, m: newestTranscriptMs(d) }))
429
- .sort((a, b) => b.m - a.m);
430
- return cands.length ? cands[0].d : null;
431
- } catch (e) { return { error: `transcript lookup failed: ${e.message}` }; }
432
- }
433
-
434
- // The candidate session directories for this cwd. `dirs: null` means there
435
- // is no project dir here at all; `[]` means there is one holding no session
436
- // yet. `root` is where it looked, for the error above.
437
- //
438
- // `encodeProjectDir` realpath-resolves a cwd outside $HOME, which throws
439
- // ENOENT when that cwd does not exist. No omp session can be keyed on such a
440
- // cwd, so THAT is this tree's absence — not a lookup fault. Any OTHER error
441
- // (EACCES on an ancestor directory, say) is a real fault, not an absence,
442
- // and must not be relabelled as one: swallowing it here would crash
443
- // silently with no signal anything went wrong. It is rethrown, uncaught,
444
- // into findSubagentsDir's own catch — the same fate a listing failure below
445
- // already gets, deliberately.
446
- function sessionDirs(home, cwd) {
447
- const sessions = join(home, ".omp", "agent", "sessions");
448
- let root;
449
- try {
450
- root = join(sessions, encodeProjectDir(cwd, { home }));
451
- } catch (e) {
452
- if (e.code !== "ENOENT") throw e;
453
- return { root: sessions, dirs: null };
454
- }
455
- if (!existsSync(root)) return { root, dirs: null };
456
- const dirs = readdirSync(root, { withFileTypes: true })
457
- .filter((e) => e.isDirectory() && isOmpSessionDirName(e.name))
458
- .map((e) => join(root, e.name));
459
- return { root, dirs };
460
- }
461
-
462
- // Newest *.jsonl mtime anywhere under a session's transcript dir, 0 if it
463
- // holds none. Recursive: a nested member (a dispatcher's own further
464
- // fan-out, one directory level down — the same walk ompSessionTranscripts
465
- // does to book their spend) can be the only fresh activity in an otherwise
466
- // idle-looking session, and a scan bounded to the top level would score
467
- // that session 0 and lose it to a genuinely stale sibling.
468
- //
469
- // A dir whose transcripts are all unreadable loses to one that is readable,
470
- // which is the behaviour we want when picking "the live session".
471
- //
472
- // The scan is wrapped for the same reason the per-file stat below is. This runs
473
- // once per CANDIDATE, so an uncaught throw here does not just lose one dir — it
474
- // escapes findSubagentsDir's try and turns the whole lookup into { error },
475
- // blacking out every readable session over one bad sibling. Scoring 0 is what
476
- // the comment above already promises: a dir we cannot read simply loses.
477
- function newestTranscriptMs(dir) {
478
- let names;
479
- try { names = readdirSync(dir, { recursive: true }); } catch { return 0; }
480
- let newest = 0;
481
- for (const f of names) {
482
- if (!f.endsWith(".jsonl")) continue;
483
- try { newest = Math.max(newest, statSync(join(dir, f)).mtimeMs); } catch { /* raced away */ }
391
+ // The session directory this run's phase-0 receipt records, for a panel with
392
+ // no --spend-dir: `.fleet/phase0.json` in the cockpit's own state directory —
393
+ // the directory its ledger and heartbeat come from, so the three cannot
394
+ // disagree about which run they belong to — through phase0-receipt.mjs's
395
+ // readReceipt, the one reading of that file. The caller reads it on EVERY
396
+ // tick and keeps nothing: a cockpit survives across runs (a phase-0 relaunch
397
+ // reuses a running server), so a session held from an earlier tick would
398
+ // keep showing the previous run's spend once the next run's receipt lands.
399
+ //
400
+ // A receipt with no session to give is `{ error }`, which the panel shows:
401
+ // the board names no session rather than guessing one. So is a recorded
402
+ // session whose NAME is not an omp `<ISO>_<uuid>` session directory:
403
+ // phase0.mjs accepts any existing directory as the session, so a `--session`
404
+ // naming the encoded-cwd project dir instead of its own session child lands in
405
+ // the receipt, and readOmpSpend would book every session under it — the
406
+ // controller's own main-session transcript included — as this run's agents.
407
+ // A recorded directory that does not exist yet is not an error — that is
408
+ // gatherSpend()'s quiet `null`, below.
409
+ export function receiptSpendDir(stateDir) {
410
+ const path = join(stateDir, RECEIPT);
411
+ const read = readReceipt(path);
412
+ if (read.state === "ok" && read.receipt.session !== "") {
413
+ const session = read.receipt.session;
414
+ if (isOmpSessionDirName(basename(session))) return session;
415
+ return { error: `phase-0 receipt ${path} records ${session}, which is not an omp <ISO>_<uuid> session directory` };
484
416
  }
485
- return newest;
486
- }
487
-
488
- // The transcript directory a `serve` process is bound to, resolved
489
- // once it can be trusted and reused by every tick after it. findSubagentsDir()
490
- // above ranks sessions by newest transcript mtime and gather() reached it
491
- // through gatherSpend() on EVERY tick (~15s by default), so two sessions live
492
- // under one project directory took turns winning: the panel alternated
493
- // between two runs' numbers with nothing on the page or on stderr to say it
494
- // had switched.
495
- //
496
- // The pin holds the first answer that COULD BE THIS RUN'S, not the first
497
- // non-null answer and not the first call. findSubagentsDir() has
498
- // three returns and none of them is safe to latch on sight: a directory
499
- // resolved at pin-construction time can be a PREVIOUS run's session — newer
500
- // than nothing else that exists yet, so it wins the ranking, but not this
501
- // run's — and `{ error }` can be a transient fault (EACCES on a directory
502
- // mid-permission-change, EMFILE, EIO) recovering on the very next tick just
503
- // as easily as it can be the truly unresolvable "bug that never fixes
504
- // itself" the ticket originally reasoned about. Latching either one turns
505
- // the self-correcting degradation this file's header describes into a
506
- // permanent one: measured, a chmod'd-then-restored session tree left
507
- // the OLD `??=` pin stuck on `{ error }` forever while the unpinned lookup
508
- // recovered on its very next tick, and a prior run's session dir
509
- // present at launch left the old pin on yesterday's numbers for the whole of
510
- // today's run, even once today's first agent had written its own transcript.
511
- //
512
- // So `launchMs`, captured once at construction, is the boundary: `null` (no
513
- // session anywhere yet) and `{ error }` (unresolvable OR transiently
514
- // unreadable — indistinguishable from here, so neither is trusted) both keep
515
- // re-asking, same one scan per tick the `null` case always cost. A resolved
516
- // directory whose own newest transcript predates `launchMs` is treated the
517
- // same way — returned as this tick's best-effort answer, so the panel still
518
- // renders it, but not cached — because a transcript that stopped moving
519
- // before this pin existed cannot be evidence of THIS run's activity. Only a
520
- // directory whose newest transcript is at or after `launchMs` latches, which
521
- // is the one fact available here that says "something is writing to this
522
- // session on my watch", never a previous run's signature.
523
- //
524
- // An explicit directory skips the heuristic entirely — never resolved, never
525
- // re-picked, and findSubagentsDir() is never called at all, so a tree it could
526
- // not read cannot degrade a panel the operator has already named the source
527
- // for. `home`/`cwd` are captured HERE rather than read per call for the same
528
- // reason the resolution is: a pin that could answer for a different workspace
529
- // later is not a pin.
530
- //
531
- // The limitation this leaves is stated at the top of this file: two sessions
532
- // that both start writing after the pin exists are still indistinguishable.
533
- // --spend-dir is the way out.
534
- export function spendDirPin(explicit, home = process.env.HOME, cwd = process.cwd()) {
535
- if (explicit != null) return () => explicit;
536
- const launchMs = Date.now();
537
- let pinned = null;
538
- return () => {
539
- if (pinned !== null) return pinned;
540
- const answer = findSubagentsDir(home, cwd);
541
- if (typeof answer !== "string") return answer; // null or { error }: neither is a trustworthy answer to latch
542
- if (newestTranscriptMs(answer) < launchMs) return answer; // predates this pin — could be a previous run's
543
- return (pinned = answer);
544
- };
417
+ const none = "no session recorded — run phase 0 or pass --spend-dir";
418
+ return { error: read.state === "unreadable" ? `${none} (phase-0 receipt ${path} unreadable: ${read.why})` : none };
545
419
  }
546
420
 
547
421
  // The `no-spend-dir` gate warns at most once per process PER DISTINCT ERROR.
548
- // `dir.error` is not constant — findSubagentsDir words an unresolvable project
549
- // dir differently from a lookup that threw — so it is keyed on the message
422
+ // `dir.error` is not constant — receiptSpendDir words an unreadable receipt
423
+ // differently from a missing one — so it is keyed on the message
550
424
  // itself, not the empty string this gate used to key on: an empty key
551
425
  // collapsed both wordings onto the one `no-spend-dir\0` slot, so whichever
552
426
  // fault landed first for a process consumed the slot and a later, genuinely
553
427
  // different fault never reached stderr again for the rest of the run. Keying
554
- // on `dir.error` fixes that without losing the steady-state behaviour: `cwd`
555
- // and `HOME` are fixed for the life of `serve`, so a repeating identical fault
428
+ // on `dir.error` fixes that without losing the steady-state behaviour: a
429
+ // receipt that stays missing is worded the same way on every tick, so a
430
+ // repeating identical fault
556
431
  // still costs one line, not one per tick. Either way this gate only ever
557
432
  // controlled the repeated stderr LINE — a fault that differs still reaches the
558
433
  // browser on the tick it happens, through the `{ error }` gatherSpend returns
@@ -597,31 +472,38 @@ export function spendDirPin(explicit, home = process.env.HOME, cwd = process.cwd
597
472
  // truthiness check returning, because nothing in the data says which field is
598
473
  // the tag. This follows `ledger.mjs`'s `tracker`: a boolean checked before any
599
474
  // success-only field is read.
600
- export function gatherSpend({ dir = findSubagentsDir(), sinceMs = null, topN = 8, explicit = false } = {}) {
475
+ export function gatherSpend({ dir, sinceMs = null, topN = 8, explicit = false } = {}) {
601
476
  try {
602
- // A caller-supplied `null` is a RESOLUTION from one that owns a pin
603
- // (spendDirPin() above) — the project directory is there and holds no
604
- // session yet — and must not run the heuristic a second time; only an
605
- // omitted `dir` (every gatherSpend test driver, and `build`, which is one
606
- // gather per process and so needs no pin) defaults to it. A default
607
- // parameter fires on `undefined` alone, never `null`, which is exactly
608
- // that distinction — the hand-rolled `if (dir === undefined) dir =
609
- // findSubagentsDir();` this used to spell out is redundant with it.
477
+ // `dir` is the caller's resolution, never one made here: the operator's
478
+ // --spend-dir, or the session the phase-0 receipt records
479
+ // (receiptSpendDir() above), or that read's `{ error }`. `null` or an
480
+ // omitted `dir` is a caller with no session to read, and hides the panel.
610
481
  //
611
482
  // `explicit` is true only when `dir` came from the operator's
612
- // own --spend-dir, never from the heuristic or an unresolved pin — see
613
- // its one use below, at the empty-directory branch.
483
+ // own --spend-dir, never from the receipt — see its uses below.
614
484
  const dirError = dir?.error;
615
485
  if (dirError) {
616
486
  warnOnce("no-spend-dir", dirError, dirError);
617
487
  return { ok: false, error: dirError };
618
488
  }
619
- if (!dir) return null; // resolved, but this session has spawned no agents yet
620
- // Only for an EXPLICIT --spend-dir — the heuristic's own
621
- // findSubagentsDir() already dispatches on isOmpSessionDirName, so a
622
- // resolved-but-non-heuristic `dir` here only ever arrives from the
623
- // operator naming a directory directly. Without this check the
624
- // mis-levelled path this same function's comments already name (the
489
+ if (!dir) return null;
490
+ // A recorded session whose directory does not exist yet: omp creates it
491
+ // when the session's first subagent writes there, and the cockpit
492
+ // launches in phase 0, before that. The normal state at launch, so quiet
493
+ // — but only ENOENT is that state. Any other failure to stat it (EACCES
494
+ // or ENOTDIR on an ancestor) is a session the cockpit cannot read, and
495
+ // goes to the catch's loud path below rather than hiding the panel.
496
+ // An explicit --spend-dir that does not exist still takes the catch's
497
+ // loud path too: an operator who named a directory hears about a typo.
498
+ if (!explicit) {
499
+ try { statSync(dir); } catch (e) {
500
+ if (e.code === "ENOENT") return null;
501
+ throw e;
502
+ }
503
+ }
504
+ // Here only for an EXPLICIT --spend-dir — receiptSpendDir() already holds
505
+ // the receipt's session to this same name rule. Without this check
506
+ // the mis-levelled path this same function's comments already name (the
625
507
  // encoded-cwd project dir instead of its own <ISO>_<uuid> child) walked
626
508
  // straight into readOmpSpend below, which recurses over every nested
627
509
  // .jsonl with no name check of its own, and booked every session's
@@ -657,9 +539,9 @@ export function gatherSpend({ dir = findSubagentsDir(), sinceMs = null, topN = 8
657
539
  return { ok: false, error: `no agent turn readable: ${lost.join("; ")}` };
658
540
  }
659
541
  if (skipped) return { ok: false, error: `all ${skipped} transcripts unreadable` };
660
- // Only for an EXPLICIT override — never the heuristic's own
661
- // "resolved, no session yet" `null` case two arms up, which is the
662
- // normal state at launch and must stay silent. An operator who named
542
+ // Only for an EXPLICIT override — never the receipt's session holding
543
+ // no transcripts yet, which is the normal state at launch and must
544
+ // stay silent. An operator who named
663
545
  // this exact directory has a panel that just went quiet with nothing
664
546
  // saying whether that is the normal "not written yet" wait or a typo'd
665
547
  // / mis-levelled path (e.g. the encoded-cwd directory instead of its
@@ -772,20 +654,16 @@ function readOmpSpend(dir, sinceMs) {
772
654
  // the fields.
773
655
  //
774
656
  // `spendDir` is the caller's transcript directory and is the one
775
- // parameter here whose ABSENCE is not a default to fill in: the tick loop hands
776
- // the same pin's answer to every tick, and its three shapes — a directory, `null`
777
- // for "resolved, no session yet", `{ error }` for unresolvable — all have to
778
- // reach gatherSpend() as themselves. `build` is one gather per process, so it
779
- // needs the --spend-dir override but never a pin, and passes the override or
780
- // nothing; with neither the pin nor the flag, gatherSpend() resolves for itself.
781
- //
782
- // `spendDirExplicit` is passed separately from `spendDir` itself: the tick
783
- // loop always passes a resolved `spendDir` (the pin's answer), never leaving it
784
- // to default, so `spendDir`'s own presence cannot say whether an operator named
785
- // it. Whether --spend-dir was given is a fact about argv, unrelated to which of
786
- // gatherSpend's three shapes the pin currently holds. It, `spendSince` and
787
- // `interval` are argv's answers, resolved by the caller: nothing in here reads
788
- // argv.
657
+ // parameter here whose ABSENCE is not a default to fill in: the caller hands
658
+ // in the operator's --spend-dir or, with none, the receipt's answer for this
659
+ // tick — a directory or `{ error }` — and either has to reach gatherSpend() as
660
+ // itself. Nothing in here reads the receipt.
661
+ //
662
+ // `spendDirExplicit` is passed separately from `spendDir` itself: `spendDir`
663
+ // always arrives resolved, so its own presence cannot say whether an operator
664
+ // named it. Whether --spend-dir was given is a fact about argv. It,
665
+ // `spendSince` and `interval` are argv's answers, resolved by the caller:
666
+ // nothing in here reads argv.
789
667
  // Async, because every child read below is. The event loop this frees
790
668
  // belongs to serve()'s HTTP server, which shares this process — see execRead's
791
669
  // note in board-common.mjs for what the synchronous version cost. `build` awaits it and is
package/scripts/board.mjs CHANGED
@@ -8,13 +8,13 @@
8
8
  // The board never depends on the controller feeding it.
9
9
  //
10
10
  // What stays here is what neither half owns: argv parsing, the build/serve
11
- // dispatch, the tick loop with its overlap guard and spend pin, and the fault
12
- // path.
11
+ // dispatch, the tick loop with its overlap guard and per-tick spend source, and
12
+ // the fault path.
13
13
 
14
14
  import { writeFileSync, renameSync, writeSync } from "node:fs";
15
15
  import { defineFlags } from "./arg.mjs";
16
16
  import { NAME, die, warnOnce } from "./board-common.mjs";
17
- import { gather, spendDirPin } from "./board-gather.mjs";
17
+ import { gather, receiptSpendDir } from "./board-gather.mjs";
18
18
  import { serve, resolveCockpitInstance, cockpitWorkspace } from "./board-server.mjs";
19
19
  // The heartbeat's liveness mark path, taken from the module that owns the
20
20
  // filename rather than spelling `heartbeat.json` a second time. The PATH
@@ -126,8 +126,9 @@ function argSpendSince() {
126
126
  return sinceMs;
127
127
  }
128
128
 
129
- // The operator's override for the session heuristic (findSubagentsDir() in
130
- // board-gather.mjs). A PATH, so there is no range or magnitude to check the way
129
+ // The operator's override for the session the phase-0 receipt records
130
+ // (receiptSpendDir() in board-gather.mjs). A PATH, so there is no range or
131
+ // magnitude to check the way
131
132
  // --spend-since and --interval have one — every malformed SHAPE this flag can
132
133
  // take is already arg()'s: a trailing `--spend-dir`, an empty or whitespace
133
134
  // value, a following flag eaten as the value, and the `--spend-dir=` form.
@@ -147,12 +148,20 @@ function argSpendSince() {
147
148
  // degrades per tick through gatherSpend's catch and hides the panel; it never
148
149
  // renders zeroes and never dies.
149
150
  //
150
- // `undefined` for an absent flag, not the `null` argPort()/argInterval()/
151
- // argSpendSince() return: `null` is a transcript-directory RESOLUTION
152
- // ("resolved, no session yet" — findSubagentsDir() in board-gather.mjs), and the
153
- // absence of an override must not read as one.
151
+ // `null` for an absent flag, like argPort()/argInterval()/argSpendSince().
154
152
  function argSpendDir() {
155
- return arg("spend-dir") ?? undefined;
153
+ return arg("spend-dir");
154
+ }
155
+
156
+ // What gather() reads the spend panel from: the operator's --spend-dir, else
157
+ // the session the phase-0 receipt in `stateDir` records, read on every call
158
+ // and never held. `spendDirExplicit` is decided here, beside the choice it
159
+ // describes, so build and every serve tick cannot tell the two apart
160
+ // differently.
161
+ function spendSource(spendDir, stateDir) {
162
+ return spendDir != null
163
+ ? { spendDir, spendDirExplicit: true }
164
+ : { spendDir: receiptSpendDir(stateDir), spendDirExplicit: false };
156
165
  }
157
166
 
158
167
  async function main() {
@@ -239,7 +248,7 @@ async function main() {
239
248
  const spendSince = argSpendSince();
240
249
  // `--spend-dir` joins them for the same two reasons, from the day it
241
250
  // ships rather than one ticket later — it reaches both subcommands (gather()
242
- // on build, the tick loop's pin on serve), and a trailing
251
+ // on build, every tick on serve), and a trailing
243
252
  // `--spend-dir` ahead of a stray positional has to name itself instead of
244
253
  // the token behind it.
245
254
  const spendDir = argSpendDir();
@@ -289,7 +298,7 @@ async function main() {
289
298
  // there.
290
299
  stateFile: stateFileIn(instance.stateDir),
291
300
  workspace: instance.workspace, port: instance.port,
292
- interval, spendDir, spendDirExplicit: spendDir != null, spendSince,
301
+ interval, ...spendSource(spendDir, instance.stateDir), spendSince,
293
302
  }));
294
303
  console.log(JSON.stringify(model, null, 2));
295
304
  return;
@@ -308,13 +317,11 @@ async function main() {
308
317
  // owns the socket, the timer and the identity handshake; what a tick reads and
309
318
  // writes is owned here.
310
319
  //
311
- // The pin is built HERE, once, and read by every tick. Outside the returned
312
- // tick for the obvious reason — a pin rebuilt per tick is a pin in name only —
313
- // and ahead of serve()'s port loop because it costs nothing to carry:
314
- // spendDirPin() touches no filesystem until its first call, so the reuse and
315
- // degrade arms that exit before ticking pay nothing for it.
320
+ // The spend source is settled per TICK, never held across ticks: with no
321
+ // --spend-dir, every tick reads the session the phase-0 receipt records now.
322
+ // A cockpit outlives the run that launched it — a phase-0 relaunch reuses a
323
+ // running server — so it has to follow the next run's receipt.
316
324
  async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
317
- const spendPin = spendDirPin(spendDir);
318
325
  const { computeBoard } = await import("./compute-board.mjs");
319
326
  // One tick at a time, and the flag is load-bearing rather than defensive.
320
327
  // The timer's callback used to be synchronous, so node could not start
@@ -380,10 +387,9 @@ async function boardTick({ ledgerFile, interval, spendDir, spendSince }) {
380
387
  // the ledger default: a pure join on a directory settled at bind time.
381
388
  stateFile: stateFileIn(stateDir),
382
389
  workspace, port: served,
383
- // The pinned transcript directory, not a fresh lookup: every tick after
384
- // the first gets the SAME answer, which is what stops the panel
385
- // alternating between two sessions under one project directory.
386
- spendDir: spendPin(), spendDirExplicit: spendDir != null, spendSince,
390
+ // The operator's --spend-dir, else the receipt as it stands at this
391
+ // tick, read from the same state directory as the ledger and heartbeat.
392
+ ...spendSource(spendDir, stateDir), spendSince,
387
393
  }));
388
394
  const tmp = `${jsonPath}.tmp`;
389
395
  writeFileSync(tmp, JSON.stringify(model)); // atomic: write tmp, rename over target
@@ -1,10 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  // Phase 0 as one command: the run's start sequence, in order, with a receipt.
3
3
  //
4
- // phase0.mjs --session <dir> [--in-flight n] [--plugin-checkout <dir>]
4
+ // phase0.mjs [--session <dir>] [--in-flight n] [--plugin-checkout <dir>]
5
5
  // [--spend-dir <dir>]
6
6
  // [--workflow <name> | --declare-no-ci]
7
7
  //
8
+ // The session directory is `--session`, else `PI_ARTIFACTS_DIR`, which omp
9
+ // exports to its Python eval kernel and the processes that kernel starts (the
10
+ // bash tool's environment does not carry it); with neither, exit 2. It is
11
+ // accepted when it is an existing directory, or when `<dir>.jsonl` exists
12
+ // beside it — omp creates the directory when the session's first subagent
13
+ // writes there.
14
+ //
8
15
  // Reached through the Resolver and run from the MAIN checkout (a linked
9
16
  // worktree refuses: the checks below judge the checkout the controller reads
10
17
  // its rules from). The steps, each a named entry in the receipt, run in
@@ -70,13 +77,13 @@
70
77
  // a pending step. Every step name is always present: one not yet run is
71
78
  // `pending`. `run` is the `at` that `ledger.mjs rotate` wrote into the
72
79
  // controller record in `.fleet/heartbeat.json`, null until the rotation has
73
- // run. `session` is `--session`, the one place the controller states its
74
- // session directory. `scratch` is what `scratch-root.mjs` prints. `inFlight`
80
+ // run. `session` is the session directory, from `--session` or
81
+ // `PI_ARTIFACTS_DIR`. `scratch` is what `scratch-root.mjs` prints. `inFlight`
75
82
  // is the In-flight bound this run used — `--in-flight`, or its default.
76
83
  //
77
84
  // RESUMABLE. A re-run reads the receipt. It continues it — skipping every `ok`
78
85
  // step and re-running the rest — only when its `run` equals the `at` the
79
- // controller record holds now AND its `session` equals `--session`. That
86
+ // controller record holds now AND its `session` equals this run's session. That
80
87
  // comparison alone does not separate two runs before the new run's rotation:
81
88
  // the record still carries the previous run's `at` until `ledger.mjs rotate`
82
89
  // writes the next, so the previous run's receipt still matches it, and a
@@ -108,7 +115,8 @@
108
115
  // to it: they are checked against each other here and recorded in the
109
116
  // `preflight` step's output.
110
117
  //
111
- // One `phase0: <step>: <status> …` line per step on stdout, a step's further
118
+ // A `session <dir> (from --session|PI_ARTIFACTS_DIR)` line first on stdout,
119
+ // then one `phase0: <step>: <status> …` line per step, a step's further
112
120
  // output indented under it when there is any, and the `NEED` lines last.
113
121
  // Exit 0 every step ok, or `drift`/`unanswered` — advice the run goes on past;
114
122
  // 2 a usage error; 3 a step failed, or the run could not start or record itself
@@ -464,13 +472,26 @@ function main() {
464
472
  F.sweep();
465
473
  F.stray();
466
474
  const absent = (name) => F.arg(name) === null;
467
- if (absent("session")) die("--session is required: the controller's session directory, `~/.omp/agent/sessions/<encoded-cwd>/<ISO>_<uuid>`");
468
- const session = resolve(F.arg("session"));
475
+ // The session directory: --session, else PI_ARTIFACTS_DIR, which omp exports
476
+ // to its Python eval kernel and that kernel's children — not to the bash
477
+ // tool. Never a guess at the newest session for this cwd: a concurrent
478
+ // session in the same cwd can be newer.
479
+ const given = F.arg("session");
480
+ const fromEnv = process.env.PI_ARTIFACTS_DIR || null;
481
+ if (given === null && fromEnv === null) {
482
+ die("no session directory: pass --session <dir>, or run phase 0 from a Python eval cell (PI_ARTIFACTS_DIR); the bash tool's environment carries none");
483
+ }
484
+ const source = given === null ? "PI_ARTIFACTS_DIR" : "--session";
485
+ const session = resolve(given ?? fromEnv);
486
+ // An existing directory, or `<session>.jsonl` beside a path that does not
487
+ // exist yet: omp creates the directory when the session's first subagent
488
+ // writes there.
469
489
  try {
470
- if (!statSync(session).isDirectory()) die(`--session ${session} is not a directory`);
490
+ if (!statSync(session).isDirectory()) die(`${source} ${session} is not a directory`);
471
491
  } catch (e) {
472
492
  if (e.code === undefined) throw e;
473
- die(`--session ${session} is not readable (${e.code})`);
493
+ if (e.code !== "ENOENT") die(`${source} ${session} is not readable (${e.code})`);
494
+ if (!existsSync(`${session}.jsonl`)) die(`${source} ${session} does not exist, and no ${session}.jsonl beside it names a session`);
474
495
  }
475
496
  const positive = (name) => {
476
497
  const n = F.numArg(name);
@@ -549,6 +570,7 @@ function main() {
549
570
 
550
571
  const ctx = { cwd, fleetDir, held, receipt, receiptPath, scratch, pluginCheckout, spendDir, ci };
551
572
  const say = (line) => process.stdout.write(`${line}\n`);
573
+ say(`session ${session} (from ${source})`);
552
574
  let stop = null;
553
575
  for (const name of STEP_NAMES) {
554
576
  if (receipt.steps[name].status === "ok") {
@@ -40,22 +40,21 @@ refreshes the Shortlist itself, and every admission is a **Pull** — one ticket
40
40
  into one free implementer slot, the moment it frees (phase 1). Nothing in this
41
41
  phase, or in any later one, asks the maintainer which tickets to take.
42
42
 
43
- 0. **Once per run, before anything else.** Run `~/.fleet/bin/fleet-run
44
- phase0.mjs --session <session-dir>` from this main checkout, `<session-dir>`
45
- being this run's own session directory. Add `--in-flight <n>` when
46
- `$ARGUMENTS` gave one, `--plugin-checkout
47
- <dir>` when this workspace tracks no `plugin/…` of its own, `--spend-dir
48
- <dir>` to name the directory the cockpit's spend panel reads, and
49
- `--workflow <name>` or `--declare-no-ci` when the repository has no workflow
50
- named CI. It runs the start sequence in its fixed order — branch,
51
- fast-forward, pin, baseline, preflight, ruleset, tier-roles, metrics,
52
- cockpit, rotate, reclaim, recipe, fold-in, stranded, shortlist — prints one
53
- `phase0: <step>: <status>` line per step with the `NEED` lines last, and
54
- records each step in `.fleet/phase0.json`, which the tick reads: it prints
55
- `PHASE0-INCOMPLETE` and holds every dispatching row until the receipt is whole.
56
- Dispatch nothing before it exits 0. Exit 3 is a step that failed: its line
57
- carries the refusal, so fix the cause and run it again. Exit 4 is a step
58
- that needs you: act on each `NEED` line below, then run it again. Once
43
+ 0. **Once per run, before anything else.** Run phase 0 from a Python eval
44
+ cell in this main checkout, without `--session`:
45
+ `subprocess.run([os.path.expanduser("~/.fleet/bin/fleet-run"),
46
+ "phase0.mjs", …], stderr=subprocess.STDOUT)`. Add `--in-flight <n>` when
47
+ `$ARGUMENTS` gave one, `--plugin-checkout <dir>` when this workspace tracks
48
+ no `plugin/…` of its own, `--spend-dir <dir>` to name the directory the
49
+ cockpit's spend panel reads, and `--workflow <name>` or `--declare-no-ci`
50
+ when the repository has no workflow named CI. It runs the start sequence in
51
+ its fixed order — branch, fast-forward, pin, baseline, preflight, ruleset,
52
+ tier-roles, metrics, cockpit, rotate, reclaim, recipe, fold-in, stranded,
53
+ shortlist — prints one `phase0: <step>: <status>` line per step with the
54
+ `NEED` lines last, and records each step in `.fleet/phase0.json`, which the
55
+ tick reads: it prints `PHASE0-INCOMPLETE` and holds every dispatching row
56
+ until the receipt is whole. Dispatch nothing before it exits 0. Exit 4 is a
57
+ step that needs you: act on each `NEED` line below, then run it again. Once
59
58
  `rotate` has run, a re-run skips every `ok` step and resumes where the last
60
59
  one stopped; before it, a re-run runs every step again.
61
60
 
@@ -21,7 +21,7 @@ the same encoded-cwd directory also holds this cwd's own top-level session
21
21
  transcripts as loose FILES sibling to the per-session directories, and a
22
22
  glob without it would try to scrape one of those as if it were a session.
23
23
 
24
- **Do not narrow this to "this run's session" with `findSubagentsDir`.** That helper
24
+ **Do not narrow this to "this run's session" with the newest session for this cwd.** That
25
25
  answers a different question — the session with the NEWEST transcript for this cwd,
26
26
  which is not the same as the one you are in. Any other session sharing this cwd —
27
27
  a second terminal, a second controller run — can hold a newer transcript than
@@ -2,6 +2,16 @@
2
2
 
3
3
  `phase0.mjs` runs the start sequence and writes the receipt `.fleet/phase0.json`; SKILL.md's phase 0 step 0 says how to drive it and what to do about each `NEED` line. This file is what each step means, in the order the script runs them, for the controller to read when a step refuses or a line asks for more than SKILL.md says. One heading per step.
4
4
 
5
+ **Run it from a Python eval cell, never the bash tool.** That kernel's
6
+ environment carries `PI_ARTIFACTS_DIR`, this run's own session directory,
7
+ which phase 0 records in its receipt; the bash tool's does not, so there
8
+ phase 0 exits 2. `expanduser` is required: a literal `~/…` fails with
9
+ `FileNotFoundError`. So is the `stderr` redirect: the cell never shows a
10
+ child's stderr. `--session <dir>` overrides the variable.
11
+
12
+ Exit 3 is a step that failed: its line carries the refusal, so fix the cause
13
+ and run it again.
14
+
5
15
  ## Fast-forward the checkout
6
16
 
7
17
  **Fast-forward the checkout before you trust these rules — you are reading
@@ -146,14 +156,18 @@ free port in its range when the derived one is already held by something
146
156
  else — either way it gets its own board, just not always on the port its
147
157
  hash predicts.
148
158
 
149
- The spend panel reads this workspace's own `~/.omp/agent/sessions` tree,
150
- and is pinned to whichever session first writes a transcript on this
151
- cockpit's own watch: it will not follow a workspace that
152
- already had another session's transcripts sitting there at launch. If the
153
- panel is reading someone else's numbers, relaunch with `--spend-dir <path>`
154
- naming this run's own session directory to override the heuristic outright —
159
+ The spend panel reads the session directory this run's phase-0 receipt
160
+ records, re-read on every tick, so a cockpit that outlives a run follows the
161
+ next run's receipt. Until that directory exists and holds a member transcript
162
+ the panel stays hidden; with no receipt, or one recording no session, it says
163
+ `no session recorded — run phase 0 or pass --spend-dir`. Passing
164
+ `--spend-dir <path>` to phase 0 overrides the receipt —
155
165
  `~/.omp/agent/sessions/<encoded-cwd>/<ISO>_<uuid>` (the directory, never
156
- the `.jsonl` file of the same name beside it).
166
+ the `.jsonl` file of the same name beside it) — but only on the launch that
167
+ starts the server. A phase 0 that finds this workspace's cockpit already
168
+ running leaves it reading what it read, flag or not. To put a running
169
+ cockpit on `--spend-dir`, stop it first: SIGTERM to the pid phase 0's
170
+ `cockpit` line printed when it launched that server.
157
171
 
158
172
  ## Rotate the ledger
159
173