@feigi/fleet-ctl 3.54.3 → 3.56.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.54.3",
3
+ "version": "3.56.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": {
@@ -57,9 +57,8 @@
57
57
  // only a caller passing a value like `<branch>` can cause — refuses, naming
58
58
  // it.
59
59
  //
60
- // The text every member of a role shares is meant to live in that role's
61
- // agent body; until it does, the templates carry what the controller pasted
62
- // into the dispatch prompt by hand.
60
+ // The text every member of a role shares lives in that role's agent body; a
61
+ // template carries only what varies between dispatches of the role.
63
62
 
64
63
  import { spawnSync } from "node:child_process";
65
64
  import { createHash } from "node:crypto";
@@ -55,6 +55,15 @@
55
55
  // Anything but `clean` — dirty, unknown, no baseline — prints one
56
56
  // MAIN-CHECKOUT-* line and holds every dispatching row until the
57
57
  // maintainer clears it; it never refuses the tick.
58
+ // phase0 `.fleet/phase0.json`, phase0.mjs's receipt, through
59
+ // phase0-receipt.mjs. Missing, unreadable, a `run` other than
60
+ // the controller record's `at`, one whose controller has exited
61
+ // or cannot be judged, or a step `failed`, `pending` or absent
62
+ // prints one PHASE0-INCOMPLETE line naming what is not done and
63
+ // holds every dispatching row, ahead of the main-checkout reason;
64
+ // it never refuses the tick. A step's `drift` or `unanswered`
65
+ // and a `fold-in` NEED are advice, named on the line and holding
66
+ // nothing. The receipt's `session` fills the tier hold's step.
58
67
  // guard `.fleet/cost-guard.json` beside the shortlist, pr-cost.mjs
59
68
  // --guard's verdict on the implementer cells. Printed as the
60
69
  // `router` row and never acted on here: a missing or unreadable
@@ -86,12 +95,12 @@ import { parseMember, parseToken, premisesOf, rowNums, nextRetry, REVIEW, REVIEW
86
95
  export function reconcile(s) {
87
96
  const rev = reviewers(s);
88
97
  // The conflict rows only ask the controller to write a record — never to
89
- // dispatch — so they stand outside the main-checkout hold: the fix-applier a
98
+ // dispatch — so they stand outside the dispatch hold: the fix-applier a
90
99
  // conflict hold leads to obeys the hold through its own role's row.
91
100
  return [
92
- ...mainCheckoutHold(s, [implementers(s, rev.left), ...rev.rows]),
101
+ ...dispatchHold(s, [implementers(s, rev.left), ...rev.rows]),
93
102
  ...rev.conflictRows,
94
- ...mainCheckoutHold(s, [mergeBot(s)]),
103
+ ...dispatchHold(s, [mergeBot(s)]),
95
104
  ...shortlistRows(s),
96
105
  ...routerRows(s),
97
106
  ];
@@ -114,9 +123,20 @@ function mainCheckoutHoldReason(mainCheckout) {
114
123
  if (state === "clean") return null;
115
124
  return MAIN_CHECKOUT_HOLD[state] ?? "main checkout unknown";
116
125
  }
117
- function mainCheckoutHold(s, rows) {
118
- const why = mainCheckoutHoldReason(s.mainCheckout);
119
- if (why === null) return rows;
126
+ // A phase 0 this run has not finished holds the same rows the same way, and
127
+ // outranks the main-checkout reason on them: the baseline is one of its
128
+ // steps. Only a gate that answered `held: false` lets dispatch through — no
129
+ // answer is not a finished phase 0. Not actionable, so the fold carries it
130
+ // across an unattended night; a missing baseline under it still asks the
131
+ // controller to act, as it does alone.
132
+ const PHASE0_HOLD = "phase 0 incomplete";
133
+ // Every reason dispatch is held on this tick, outermost first.
134
+ function holdReasons(s) {
135
+ return [s.phase0?.held === false ? null : PHASE0_HOLD, mainCheckoutHoldReason(s.mainCheckout)].filter((w) => w !== null);
136
+ }
137
+ function dispatchHold(s, rows) {
138
+ const [why] = holdReasons(s);
139
+ if (why === undefined) return rows;
120
140
  const acts = s.mainCheckout?.state === "absent";
121
141
  const held = [];
122
142
  for (const r of rows) {
@@ -134,11 +154,13 @@ const mkRow = (role, actual, target, detail) => (action, { acts = false, extra =
134
154
  });
135
155
 
136
156
  // The clearing step a tier hold names in its detail. The tick reads no
137
- // transcript and so does not know the session directory: `<session>` stays a
138
- // placeholder the controller fills in, as `<file>` does — one batch file, one
139
- // entry per held member (SKILL.md's phase-2 tier check).
140
- const tierCheckStep = (members) => "run ~/.fleet/bin/fleet-run tier-check.mjs --batch <file> with "
141
- + JSON.stringify(members.map((member) => ({ member, session: "<session>" })));
157
+ // transcript; the session directory is the phase-0 receipt's, which
158
+ // tier-check.mjs reads itself when an entry omits it. Without a receipt of
159
+ // this run, `<session>` stays a placeholder the controller fills in, as
160
+ // `<file>` does — one batch file, one entry per held member (SKILL.md's
161
+ // phase-2 tier check).
162
+ const tierCheckStep = (members, session) => "run ~/.fleet/bin/fleet-run tier-check.mjs --batch <file> with "
163
+ + JSON.stringify(members.map((member) => (session ? { member } : { member, session: "<session>" })));
142
164
 
143
165
  // A mismatch clears when the next attempt on the ticket is dispatched at its
144
166
  // row's tier: ledger-grammar.mjs's nextRetry(), one letter past the highest
@@ -189,7 +211,7 @@ function implementers(s, left) {
189
211
  // controller's own step, so it is asked to act, with the command in the
190
212
  // detail.
191
213
  if (s.tierUnchecked.length) {
192
- return row(`HOLD (tier unchecked ${s.tierUnchecked.join(" ")})`, { acts: true, extra: tierCheckStep(s.tierUnchecked) });
214
+ return row(`HOLD (tier unchecked ${s.tierUnchecked.join(" ")})`, { acts: true, extra: tierCheckStep(s.tierUnchecked, s.phase0?.session) });
193
215
  }
194
216
 
195
217
  const deficit = s.implCap - s.implLive;
@@ -615,10 +637,9 @@ export function foldLedger({ rows, dispatched }, open, { lenient = false } = {})
615
637
  // fix-applier is still working the conflict.
616
638
  // `reviewFixed`: a REVIEW fix-applier landed after the latest
617
639
  // `reviewed=` — one read while no hold stood unresolved. The one read
618
- // while a hold did is the conflict fix-applier `ledger.mjs dispatch` named
619
- // a `fleet-implementer-<cell>`: it rebases and never sees the review file,
620
- // so it clears the hold and answers no finding. Each fix-applier
621
- // does one of those jobs once, so its landing folds once per PR
640
+ // while a hold did is the conflict fix-applier: it rebases and never sees
641
+ // the review file, so it clears the hold and answers no finding. Each
642
+ // fix-applier does one of those jobs once, so its landing folds once per PR
622
643
  // (`fixLanded`), however many copies of its token the rows carry.
623
644
  // `fixMembers`: every fix-applier on this PR, wherever its token sits —
624
645
  // one still unsettled anywhere holds the PR off fixDue, since `dispatch`
@@ -905,8 +926,8 @@ export function deriveRun({ rows, dispatched, drain }, prs, closed = new Set(),
905
926
  unlabelled: unlabelledFinishers({ rows, dispatched },
906
927
  new Set(prs.filter((p) => !isQueued(p)).map((p) => p.number))),
907
928
  // Every PR, open or not, on a conflict hold no fix-applier has cleared —
908
- // the one reading of a hold: `ledger.mjs dispatch` names a
909
- // fix-applier's definition and refuses a finisher off this list, so it
929
+ // the one reading of a hold: `ledger.mjs dispatch` refuses a finisher off
930
+ // this list, so it
910
931
  // answers the same per-PR fold this tick holds the merge on, split rows
911
932
  // and a settle made anywhere included, rather than re-deriving it from
912
933
  // one row's text.
@@ -1068,6 +1089,8 @@ import { gitEnv } from "./git-env.mjs";
1068
1089
  import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
1069
1090
  import { statePath, readState, writeState, assessBeat, isStalled, isReported, stallReport, stallOwner } from "./fleet-state.mjs";
1070
1091
  import { checkMainCheckout, describe } from "./main-checkout.mjs";
1092
+ import { readRunReceipt, phase0Gate } from "./phase0-receipt.mjs";
1093
+ import { judgeRecord, ProcUnreadable } from "./proc.mjs";
1071
1094
 
1072
1095
  const NAME = "fleet-tick";
1073
1096
  const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
@@ -1412,6 +1435,21 @@ function claimed() {
1412
1435
  return n === CLAIMED_LIMIT ? `${n}+` : n;
1413
1436
  }
1414
1437
 
1438
+ // What the controller record's process is now, for the phase-0 gate: `none`
1439
+ // with no record, else judgeRecord()'s answer. A process table that cannot
1440
+ // be read is `unreadable`, said on stderr: a controller nobody could judge
1441
+ // is not one whose receipt this tick may take as this run's.
1442
+ function controllerState(controller) {
1443
+ if (controller === null) return "none";
1444
+ try {
1445
+ return judgeRecord(controller);
1446
+ } catch (e) {
1447
+ if (!(e instanceof ProcUnreadable)) throw e;
1448
+ console.error(`${NAME}: WARNING ${e.message} — the recorded controller pid ${controller.pid} cannot be judged, so the phase-0 receipt is held`);
1449
+ return "unreadable";
1450
+ }
1451
+ }
1452
+
1415
1453
  function main() {
1416
1454
  const { fold, state: path, liveness, ...caps } = options();
1417
1455
  const listPath = shortlistPath();
@@ -1495,9 +1533,18 @@ function main() {
1495
1533
  // every answer but `clean` is a hold on the dispatching rows plus one line
1496
1534
  // saying why, so the rest of the run keeps reporting.
1497
1535
  const mainCheckout = checkMainCheckout();
1536
+ // This run's phase 0, off its receipt: unfinished holds the same rows the
1537
+ // main checkout does, and never refuses the tick either. Judged against
1538
+ // the controller record this tick started from, and against whether that
1539
+ // record's process is still there: a finished receipt of the run before
1540
+ // carries the same `at` until this run's rotation writes the next.
1541
+ const receipt = readRunReceipt();
1542
+ const phase0 = phase0Gate(receipt.read, {
1543
+ path: receipt.path, controllerAt: controller?.at, controller: controllerState(controller),
1544
+ });
1498
1545
 
1499
1546
  const rows = reconcile({
1500
- ...caps, ...run, heads, supply, dropped, shortlistStatus: current.status, refresh: fresh, mainCheckout, router,
1547
+ ...caps, ...run, heads, supply, dropped, shortlistStatus: current.status, refresh: fresh, mainCheckout, phase0, router,
1501
1548
  });
1502
1549
  const said = describe(mainCheckout, run.live);
1503
1550
  // Re-read rather than reusing priorState: this must be the freshest
@@ -1512,7 +1559,7 @@ function main() {
1512
1559
  // and frees no slot — and nothing here settles, kills or writes the ledger.
1513
1560
  const seen = stampSeen({ live: run.live, prev: prev.seen, controller: prev.controller, now });
1514
1561
  const stale = livenessLines({ live: run.live, seen, thresholds: liveness, now });
1515
- const lines = [...(said === null ? [] : [said]), ...stale.map((s) => s.line), ...formatLines(rows)];
1562
+ const lines = [...(phase0.line === null ? [] : [phase0.line]), ...(said === null ? [] : [said]), ...stale.map((s) => s.line), ...formatLines(rows)];
1516
1563
  // The run is over once it is draining and nothing is left in flight: no
1517
1564
  // open PR and no implementer still holding a claim. Printed last and read
1518
1565
  // as actionable, so it never folds away: the stop it names is the run's
@@ -1540,13 +1587,12 @@ function main() {
1540
1587
  }
1541
1588
 
1542
1589
  // Fold only when BOTH hold: nothing to act on, and nothing new to say. A
1543
- // main-checkout hold still holding dispatch stays named on the folded line
1544
- // — not actionable, so it never resets `quiet`, but the one reason
1545
- // nothing dispatches must not drop out of view. Outside the digest, which
1546
- // already covers it through the rows.
1590
+ // phase-0 or main-checkout hold still holding dispatch stays named on the
1591
+ // folded line — not actionable, so it never resets `quiet`, but the one
1592
+ // reason nothing dispatches must not drop out of view. Outside the digest,
1593
+ // which already covers it through the rows.
1547
1594
  if (fold && !acts && digest === prev.digest) {
1548
- const why = mainCheckoutHoldReason(mainCheckout);
1549
- const held = why === null ? "" : `; HOLD (${why}) persists`;
1595
+ const held = holdReasons({ phase0, mainCheckout }).map((why) => `; HOLD (${why}) persists`).join("");
1550
1596
  // A stale member persists the same way: advisory, so it never resets
1551
1597
  // `quiet`, and named on the folded line for as long as it stays live
1552
1598
  // past its threshold. The digest already moves when its bucket does.
@@ -651,22 +651,16 @@ export function expectedDefinition(rowText) {
651
651
  // The agent definition a member is dispatched as, for a parsed member
652
652
  // and the text of the row it works: `ledger.mjs dispatch` prints it so the
653
653
  // `task` call that follows names it off a script's output, not off prose a
654
- // compaction drops. A fix-applier on an unresolved conflict hold of its own PR
655
- // is a `fleet-implementer-<POLICY_CELL>` whatever the row's `tier=` —
656
- // it rebases the PR, it does not work a ticket at a tier. Any other fix-applier is a review
657
- // one and gets null: a generic `task` by design. Whether the hold is
658
- // unresolved is `conflictHeld`, the caller's to supply from fleet-tick.mjs's
659
- // deriveRun() — the reading the tick holds the merge on, which folds every
660
- // row of the PR, never one row's text alone. Throws whatever
661
- // expectedDefinition throws, and throws on a family this switch has no case
662
- // for: null is the review fix-applier's deliberate answer, so a
663
- // `default: return null` would print a new family as a generic `task`
664
- // without anyone having decided it is one.
665
- /** @returns {string|null} the definition name; null only for a review fix-applier. */
666
- export function agentDefinition(member, rowText, conflictHeld = false) {
654
+ // compaction drops. A fix-applier is `fleet-fix-applier` for every kind of
655
+ // work — a review's findings, a conflict hold, a dispositions retry — whatever
656
+ // the row says. Throws whatever expectedDefinition throws, and throws on a
657
+ // family this switch has no case for: a `default` answer would print a new
658
+ // family as a definition without anyone having decided it is one.
659
+ /** @returns {string} the definition name. */
660
+ export function agentDefinition(member, rowText) {
667
661
  switch (member.family) {
668
662
  case "impl": return expectedDefinition(rowText);
669
- case "fix-pr": return conflictHeld ? `fleet-implementer-${POLICY_CELL}` : null;
663
+ case "fix-pr": return "fleet-fix-applier";
670
664
  case "finisher-pr": return "fleet-finisher";
671
665
  case "merge-bot": return "fleet-merge-bot";
672
666
  default: throw new Error(`agentDefinition has no case for member family '${member.family}' (${member.name}) — add one to ledger-grammar.mjs`);
@@ -1877,15 +1877,17 @@ function runDispatch() {
1877
1877
  // refused here, before the member is live, not discovered by the check
1878
1878
  // after the call.
1879
1879
  //
1880
- // A fix-applier's turns on whether its PR sits on an unresolved conflict
1881
- // hold, and that is the tick's own verdict, not a second reading
1882
- // of row `i`: a PR's tokens can be split across its ticket row and its own
1883
- // `#<pr>` row, and a settle can live in `## Dispatched` alone, so
1880
+ // A fix-applier is `fleet-fix-applier` for every kind of work — review,
1881
+ // conflict hold, dispositions retry — so its definition reads nothing off
1882
+ // the ledger.
1883
+ //
1884
+ // The finisher's gates below turn on the tick's own verdict, not a second
1885
+ // reading of row `i`: a PR's tokens can be split across its ticket row and
1886
+ // its own `#<pr>` row, and a settle can live in `## Dispatched` alone, so
1884
1887
  // one row's text can read held where the tick reads cleared, and the
1885
1888
  // reverse. A ledger the tick refuses is refused here too, before the member
1886
- // is live, rather than named a definition off a reading the tick rejects.
1887
- // `tickFold` reads that fold for whichever of the two families needs it,
1888
- // `what` naming what could not be read off a refused ledger.
1889
+ // is live. `tickFold` reads that fold, `what` naming what could not be read
1890
+ // off a refused ledger.
1889
1891
  const tickFold = (what) => {
1890
1892
  try {
1891
1893
  return deriveRun({ rows: data.rows, dispatched: data.dispatched, drain: data.drain }, []);
@@ -1894,7 +1896,6 @@ function runDispatch() {
1894
1896
  die(`${e.message} — fleet-tick.mjs refuses this ledger, so ${member.name}'s ${what} cannot be read off it; fix it with \`ledger.mjs row\` before dispatching`);
1895
1897
  }
1896
1898
  };
1897
- const held = member.family === "fix-pr" && tickFold("definition").conflictHeld.includes(member.number);
1898
1899
 
1899
1900
  // A finisher labels its PR `ready-to-merge`, so it is recorded only once
1900
1901
  // the PR sits on no conflict hold a fix-applier has yet to clear — a PR
@@ -1922,7 +1923,7 @@ function runDispatch() {
1922
1923
  // refusal's tail names neither.
1923
1924
  let agent;
1924
1925
  try {
1925
- agent = agentDefinition(member, i === -1 ? "" : data.rows[i], held);
1926
+ agent = agentDefinition(member, i === -1 ? "" : data.rows[i]);
1926
1927
  if (member.family === "impl" && !existsSync(join(AGENTS_DIR, `${agent}.agent.md`))) {
1927
1928
  throw new Error(`row #${member.number}'s tier= names ${agent}, which has no agents/${agent}.agent.md — fix the row with \`ledger.mjs row\``);
1928
1929
  }
@@ -18,8 +18,8 @@
18
18
  // - any subagent whose definition name starts with `fleet-`;
19
19
  // - any subagent whose own id is a fleet member's task name (`impl-1411`,
20
20
  // `fix-pr-88`, `review-pr-2245`, `finisher-pr-7`, with an optional `-b`
21
- // recovery suffix): this is how a fix-applier is caught, since it is
22
- // dispatched under a generic `task` definition with no `fleet-` prefix;
21
+ // recovery suffix): a member named by id is caught whatever definition
22
+ // name its dispatch gave it;
23
23
  // - any subagent spawned BY a fleet member: its `parentId` is the member's
24
24
  // task name, while its own definition name is a generic one no prefix
25
25
  // check could see.
@@ -36,7 +36,8 @@
36
36
  // same set, and the checkout's HEAD besides).
37
37
  // - `bash` cwd, for every `fleet-implementer-<cell>` (ledger-grammar.mjs's
38
38
  // `CELL_DEF`), and for a fix-applier's own id (`fix-pr-<n>`) directly,
39
- // since a review fix-applier is a generic `task`: refuse when
39
+ // since its definition, `fleet-fix-applier`, is no implementer cell and
40
+ // `CELL_DEF` does not match it: refuse when
40
41
  // `input.cwd ?? ctx.cwd` lies inside the main checkout outside
41
42
  // `.worktrees/`. Command text is never parsed. Review specialists and
42
43
  // refuters are REQUIRED to start from the inherited cwd (`pwd` first,
@@ -71,7 +72,7 @@ import { fileURLToPath } from "node:url";
71
72
  import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
72
73
  import { CELL_DEF } from "./ledger-grammar.mjs";
73
74
 
74
- /** The task names the controller gives fleet members; a subagent whose parent carries one is a member's child, and a fix-applier — dispatched under a generic `task` definition with no `fleet-` prefix — is caught by its own id matching this directly. */
75
+ /** The task names the controller gives fleet members; a subagent whose parent carries one is a member's child, and a member whose own id matches this is caught directly, whatever definition name its dispatch gave it. */
75
76
  const MEMBER_TASK_NAME = /^(impl|fix-pr|review-pr|finisher-pr)-\d+(-[a-z])?$/;
76
77
  const FIX_APPLIER_ID = /^fix-pr-\d+(-[a-z])?$/;
77
78
  const PATH_WRITERS = new Set(["write", "edit", "ast_edit"]);
@@ -0,0 +1,145 @@
1
+ // The phase-0 receipt, read. `.fleet/phase0.json` is written by phase0.mjs
2
+ // after every step (its header gives the shape); this module is its readers'
3
+ // half: the tick's dispatch gate, and the session directory tier-check.mjs
4
+ // and ticket-router.mjs take when their own flag is omitted. One reading of
5
+ // the file, so the gate and the session readers cannot disagree about what a
6
+ // receipt is.
7
+ //
8
+ // Zero deps: node builtins and sibling modules only.
9
+
10
+ import { readFileSync } from "node:fs";
11
+ import { fleetFile, FleetDirUnresolvable } from "./fleet-dir.mjs";
12
+ import { RECEIPT } from "./ledger-grammar.mjs";
13
+
14
+ const isRecord = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
15
+
16
+ // The steps phase0.mjs runs, in order: its receipt always carries every one,
17
+ // a step not yet run being `pending`. A receipt missing one was not written
18
+ // by a finished phase 0.
19
+ export const STEP_NAMES = Object.freeze([
20
+ "branch", "fast-forward", "pin", "baseline", "preflight", "ruleset", "tier-roles", "metrics",
21
+ "cockpit", "rotate", "reclaim", "recipe", "fold-in", "stranded", "shortlist",
22
+ ]);
23
+
24
+ // The statuses a step can end in that let the run go on: `ok`, and the two
25
+ // a ruleset check answers with when the gate drifted or could not be asked.
26
+ // Every other status — `failed`, `pending`, or one this reader does not know
27
+ // — is a step not done.
28
+ const ADVICE = new Set(["drift", "unanswered"]);
29
+ const DONE = new Set(["ok", ...ADVICE]);
30
+
31
+ /**
32
+ * `{ state: "missing" }`, `{ state: "unreadable", why }`, or
33
+ * `{ state: "ok", receipt }`. A receipt is a JSON object carrying `run`, a
34
+ * string `session` and a `steps` object whose every entry has a string
35
+ * `status` — the shape phase0.mjs writes and resumes from.
36
+ */
37
+ export function readReceipt(path) {
38
+ let text;
39
+ try {
40
+ text = readFileSync(path, "utf8");
41
+ } catch (e) {
42
+ if (e.code === "ENOENT") return { state: "missing" };
43
+ return { state: "unreadable", why: e.code ?? e.message };
44
+ }
45
+ let r;
46
+ try {
47
+ r = JSON.parse(text);
48
+ } catch (e) {
49
+ return { state: "unreadable", why: `not JSON (${e.message})` };
50
+ }
51
+ if (!(isRecord(r) && isRecord(r.steps) && Object.hasOwn(r, "run") && typeof r.session === "string")) {
52
+ return { state: "unreadable", why: "not a receipt: it needs run, session and steps" };
53
+ }
54
+ for (const [name, step] of Object.entries(r.steps)) {
55
+ if (!isRecord(step) || typeof step.status !== "string") return { state: "unreadable", why: `step ${name} has no status` };
56
+ }
57
+ return { state: "ok", receipt: r };
58
+ }
59
+
60
+ // The receipt at its resolved place — resolved the way phase0.mjs resolves
61
+ // it, so a worktree and the main checkout name one file — or the reason it
62
+ // has none: an unresolvable workspace is a receipt nobody can read.
63
+ export function readRunReceipt(opts) {
64
+ let path;
65
+ try {
66
+ path = fleetFile(RECEIPT, opts);
67
+ } catch (e) {
68
+ if (!(e instanceof FleetDirUnresolvable)) throw e;
69
+ return { path: RECEIPT, read: { state: "unreadable", why: e.message } };
70
+ }
71
+ return { path, read: readReceipt(path) };
72
+ }
73
+
74
+ const phase0Command = (session) => `~/.fleet/bin/fleet-run phase0.mjs --session ${session ?? "<session>"}`;
75
+
76
+ /**
77
+ * The tick's gate over one read of the receipt. `controllerAt` is the `at`
78
+ * of the controller record in `.fleet/heartbeat.json` now, null when there is
79
+ * no record or it carries no `at` — the value phase0.mjs records as `run`, and
80
+ * compares the same way. `controller` is what that record's process is now,
81
+ * as proc.mjs's judgeController() answers (`none`, `dead`, `alive`,
82
+ * `ancestor`), or `unreadable` when the process table could not be read.
83
+ *
84
+ * `run` alone cannot tell this run's receipt from the previous run's: the
85
+ * record keeps the previous run's `at` until this run's rotation writes the
86
+ * next, so a finished receipt of the run before still matches it. A record
87
+ * whose process is gone, or cannot be judged, is that case, and holds.
88
+ *
89
+ * `{ held, line, session }`: `held` holds every dispatching row; `line` is the
90
+ * one line printed above the rows, or null when there is nothing to say;
91
+ * `session` is the receipt's session directory when the receipt is this
92
+ * run's, else null.
93
+ *
94
+ * A step `failed` or `pending`, in a status this reader does not know, or
95
+ * absent from the receipt, holds. `drift` and `unanswered`, and a `NEED` line
96
+ * in a `fold-in` step's output, are advice: named on the line, holding
97
+ * nothing.
98
+ */
99
+ export function phase0Gate(read, { path, controllerAt = null, controller = "none" }) {
100
+ const held = (why, session = null) => ({
101
+ held: true,
102
+ line: `PHASE0-INCOMPLETE ${why} — dispatch held: run ${phase0Command(session)} and act on what it prints`,
103
+ session,
104
+ });
105
+ if (read.state === "missing") return held(`no receipt at ${path}`);
106
+ if (read.state !== "ok") return held(`receipt ${path} unreadable: ${read.why}`);
107
+ const { receipt } = read;
108
+ if (receipt.run !== controllerAt) {
109
+ return held(`receipt ${path} is another run's: run ${receipt.run ?? "none"}, controller record ${controllerAt ?? "none"}`);
110
+ }
111
+ if (controller === "dead" || controller === "unreadable") {
112
+ const why = controller === "dead" ? "its controller has exited" : "its controller cannot be judged";
113
+ return held(`receipt ${path} is run ${receipt.run ?? "none"}'s and ${why}: not this session's finished phase 0`);
114
+ }
115
+ const steps = Object.entries(receipt.steps);
116
+ const absent = STEP_NAMES.filter((name) => !Object.hasOwn(receipt.steps, name));
117
+ const incomplete = [
118
+ ...steps.filter(([, step]) => !DONE.has(step.status)).map(([name]) => name),
119
+ ...absent,
120
+ ];
121
+ const advice = [
122
+ ...steps.filter(([, step]) => ADVICE.has(step.status)).map(([name, step]) => `${name} ${step.status}`),
123
+ ...String(receipt.steps["fold-in"]?.output ?? "").split("\n").map((l) => l.trim())
124
+ .filter((l) => l.startsWith("NEED ")).map((l) => `fold-in ${l}`),
125
+ ];
126
+ const session = receipt.session === "" ? null : receipt.session;
127
+ if (incomplete.length) {
128
+ const said = held(incomplete.join(", "), session);
129
+ return advice.length ? { ...said, line: `${said.line}; advice: ${advice.join(", ")}` } : said;
130
+ }
131
+ return { held: false, line: advice.length ? `PHASE0-ADVICE ${advice.join(", ")}` : null, session };
132
+ }
133
+
134
+ /**
135
+ * The session directory the receipt records, for a reader whose own flag was
136
+ * omitted. Throws an Error naming the receipt when it has none to give.
137
+ */
138
+ export function sessionFromReceipt(opts) {
139
+ const { path, read } = readRunReceipt(opts);
140
+ if (read.state === "ok" && read.receipt.session !== "") return read.receipt.session;
141
+ const why = read.state === "missing" ? "no receipt"
142
+ : read.state === "unreadable" ? `unreadable: ${read.why}`
143
+ : "it records no session";
144
+ throw new Error(`no session given and none in the phase-0 receipt ${path} (${why}) — give one, or run ${phase0Command(null)} first`);
145
+ }
@@ -3,7 +3,7 @@
3
3
  // for dispatch and for the offline fit, because the stratum rule is the one
4
4
  // function that must never read differently between the two.
5
5
  //
6
- // route --session <dir|id> --ticket <N> --arm A|B --impl-row <k>
6
+ // route [--session <dir|id>] --ticket <N> --arm A|B --impl-row <k>
7
7
  // --issue <issue.json> --guard <cost-guard.json>
8
8
  // [--sizing <sizing.json>] [--table <router-table.json>]
9
9
  // [--chain-head] [--pending <tsv>]
@@ -13,7 +13,9 @@
13
13
  // `ticket-features.pending.tsv` beside `--guard`, in the run's `.fleet/`). Exit 0 on
14
14
  // every data degradation — a missing or unreadable issue, sizing or guard
15
15
  // file degrades the line, never the exit. Exit 2 only on a usage error or
16
- // an unreadable/invalid table: the caller does not dispatch then.
16
+ // an unreadable/invalid table: the caller does not dispatch then. With no
17
+ // `--session`, the session is the one the phase-0 receipt
18
+ // `.fleet/phase0.json` records; a receipt that records none is exit 2.
17
19
  // fit --table <json> --features <tsv> --members <tsv> --verdicts <tsv>
18
20
  // --guard <cost-guard.json> --commit <rev> [--due]
19
21
  // Re-fits the table from the three TSVs as committed at `--commit` (read
@@ -43,6 +45,7 @@ import { isCLI } from "./is-cli.mjs";
43
45
  import { gitEnv } from "./git-env.mjs";
44
46
  import { makeDie, defineFlags } from "./arg.mjs";
45
47
  import { CELL, POLICY_CELL, drawCell, parseMember } from "./ledger-grammar.mjs";
48
+ import { sessionFromReceipt } from "./phase0-receipt.mjs";
46
49
  import { parseTsv as parseMemberTsv } from "./member-outcomes.mjs";
47
50
  import { DATE, lastPullByTicket, parseTierOutcomes, rulingFor, rulingsByTicket } from "./tier-outcomes.mjs";
48
51
 
@@ -546,8 +549,6 @@ function main() {
546
549
  if (valid instanceof Error) die(`${tablePath}: ${valid.message}`);
547
550
 
548
551
  if (mode === "route") {
549
- const sessionArg = need("session").replace(/\/+$/, "");
550
- const session = basename(sessionArg);
551
552
  const ticket = need("ticket");
552
553
  if (!/^[1-9][0-9]*$/.test(ticket)) die(`--ticket ${ticket} is not an issue number`);
553
554
  const arm = need("arm");
@@ -556,6 +557,13 @@ function main() {
556
557
  if (!/^[1-9][0-9]*$/.test(implRowArg)) die(`--impl-row ${implRowArg} is not a positive row count`);
557
558
  const issuePath = need("issue");
558
559
  const guardPath = need("guard");
560
+ // `--session` omitted is the session directory the phase-0 receipt
561
+ // records; a receipt that records none is a usage error naming it.
562
+ let sessionArg = F.arg("session");
563
+ if (sessionArg === null) {
564
+ try { sessionArg = sessionFromReceipt(); } catch (e) { die(e.message); }
565
+ }
566
+ const session = basename(sessionArg.replace(/\/+$/, ""));
559
567
  const { line, row } = route({
560
568
  session, ticket: Number(ticket), arm, implRow: Number(implRowArg), chainHead: F.has("chain-head"),
561
569
  issue: readJson(issuePath), sizing: readJson(F.arg("sizing")), guard: readGuard(readJson(guardPath)), table,
@@ -20,7 +20,13 @@
20
20
  // member's own transcript lives: the flat `<session>/<member>.jsonl`
21
21
  // file, read directly (this layer's extension to member-record.mjs's
22
22
  // readers — a member with no assistant turn yet still resolves off its
23
- // dispatch-time `session_init` record, never treated as absent).
23
+ // dispatch-time `session_init` record, never treated as absent). An
24
+ // entry that names neither a `session` nor a `transcript` takes the
25
+ // `session` the phase-0 receipt `.fleet/phase0.json` records, and is
26
+ // exit 2 naming the receipt when it records none. That session is taken
27
+ // as the receipt stands: whether the receipt is this run's is judged by
28
+ // fleet-tick.mjs's phase-0 gate, not here, and a message about it names
29
+ // the receipt's session where it would name `--session`.
24
30
  // 3. `--transcript <file>` — the member's own transcript, when the caller
25
31
  // already holds the exact path (tests, or a caller with no session
26
32
  // root handy).
@@ -70,8 +76,9 @@
70
76
  // the tier was right. Every other case with no transcript is still exit 2: a
71
77
  // LIVE member may yet write one; a member settled `PR#M`, `bailed` or
72
78
  // `tier-mismatch` ran, so its transcript exists and the `session` is the
73
- // wrong directory; a `session` that is omitted, empty, missing or not a
74
- // directory is exit 2 whether the member is live or settled; and a session
79
+ // wrong directory; a `session` that is empty, missing or not a directory,
80
+ // or omitted with none in the phase-0 receipt, is exit 2 whether the member
81
+ // is live or settled; and a session
75
82
  // directory that cannot be searched (EACCES) is exit 2 naming the errno,
76
83
  // never read as holding no transcript.
77
84
 
@@ -84,6 +91,7 @@ import { makeDie, defineFlags } from "./arg.mjs";
84
91
  import { foldOmpTranscript, parseMemberName } from "./member-record.mjs";
85
92
  import { parseFrontmatter, expectedOmpModel, modelsEqual, readOmpConfigValue } from "./tier-roles.mjs";
86
93
  import { parseMember, parseToken, memberTokens, expectedDefinition } from "./ledger-grammar.mjs";
94
+ import { sessionFromReceipt } from "./phase0-receipt.mjs";
87
95
 
88
96
  const NAME = "tier-check";
89
97
  const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
@@ -289,10 +297,10 @@ function resolvePath(repoRoot, p) {
289
297
  // (`<parent-AgentId>/<stem>.jsonl`, one directory level down) is out of
290
298
  // reach of this flat lookup — pass `--transcript` for a transcript this
291
299
  // cannot find directly.
292
- function resolveViaSession(repoRoot, sessionPath, member) {
300
+ function resolveViaSession(repoRoot, sessionPath, member, where) {
293
301
  const root = resolvePath(repoRoot, sessionPath);
294
302
  const flat = join(root, `${member}.jsonl`);
295
- if (!existsSync(flat)) throw new Error(`no ${member}.jsonl found under --session ${sessionPath}`);
303
+ if (!existsSync(flat)) throw new Error(`no ${member}.jsonl found under ${where}`);
296
304
  return readFileSync(flat, "utf8");
297
305
  }
298
306
 
@@ -385,7 +393,7 @@ function recordImplementer(ledgerFile, r) {
385
393
  // ticket's row, under the same presence rule as the other two.
386
394
  function recordUnverifiable(ledgerFile, r) {
387
395
  const token = tierUnverifiableToken(r.member);
388
- console.error(`${r.member}: settled ${r.outcome} with no ${r.member}.jsonl under --session ${r.session} — nothing to check; recorded ${token}`);
396
+ console.error(`${r.member}: settled ${r.outcome} with no ${r.member}.jsonl under ${r.where} — nothing to check; recorded ${token}`);
389
397
  const existing = rowText(readLedger(ledgerFile), r.ticket);
390
398
  const updated = withToken(existing, token);
391
399
  if (updated === existing) console.error(` ${r.member}: row #${r.ticket} already carries ${token} — not written again`);
@@ -442,6 +450,7 @@ function main() {
442
450
  // expected definition comes off its row, and nothing this loop does
443
451
  // writes a `tier=` token.
444
452
  let ledgerData = null;
453
+ let receiptSession;
445
454
  const results = entries.map((raw) => {
446
455
  const parsed = parseMember(String(raw.member ?? ""));
447
456
  const impl = parsed?.family === "impl";
@@ -466,7 +475,14 @@ function main() {
466
475
  // An implementer's transcript is read even beside a full job record:
467
476
  // the agent type it was dispatched as lives only there.
468
477
  if (impl || !hasJobRecord) {
469
- if (raw.session) {
478
+ // An entry naming neither a session nor a transcript takes the
479
+ // session directory the phase-0 receipt records — read once per
480
+ // batch — and refuses naming the receipt when it records none. A
481
+ // given one always wins.
482
+ const session = raw.session ?? (raw.transcript ? undefined : (receiptSession ??= sessionFromReceipt()));
483
+ // Said as the caller's flag only when the caller gave it.
484
+ const where = raw.session ? `--session ${session}` : `the phase-0 receipt's session ${session}`;
485
+ if (session) {
470
486
  // A member settled `killed` or `released` with no transcript under
471
487
  // a session directory that does exist: its dispatch failed before
472
488
  // one was written, so there is nothing to judge. Recorded, not
@@ -474,12 +490,12 @@ function main() {
474
490
  // ledger nowhere, or a session path that is not a directory still
475
491
  // refuses below; one settled any other way ran, so its missing
476
492
  // transcript names the wrong session and refuses here.
477
- if (impl && sessionLacksTranscript(repoRoot, raw.session, raw.member)) {
493
+ if (impl && sessionLacksTranscript(repoRoot, session, raw.member)) {
478
494
  const outcome = memberOutcome(ledgerData, raw.member);
479
- if (NO_TRANSCRIPT_OUTCOMES.has(outcome)) return { impl: true, unverifiable: true, member: raw.member, ticket, outcome, session: raw.session };
480
- if (outcome) throw new Error(`settled ${outcome} with no ${raw.member}.jsonl under --session ${raw.session} — a member settled ${outcome} ran, so its transcript exists: name the session directory that dispatched it`);
495
+ if (NO_TRANSCRIPT_OUTCOMES.has(outcome)) return { impl: true, unverifiable: true, member: raw.member, ticket, outcome, where };
496
+ if (outcome) throw new Error(`settled ${outcome} with no ${raw.member}.jsonl under ${where} — a member settled ${outcome} ran, so its transcript exists: name the session directory that dispatched it`);
481
497
  }
482
- transcriptText = resolveViaSession(repoRoot, raw.session, raw.member);
498
+ transcriptText = resolveViaSession(repoRoot, session, raw.member, where);
483
499
  } else if (raw.transcript) {
484
500
  transcriptText = readFileSync(resolvePath(repoRoot, raw.transcript), "utf8");
485
501
  } else if (impl) {