pi-straw-boss 0.80.10 → 0.80.12

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.
@@ -7311,15 +7311,15 @@ var raiserView = ({ id, ...rest }, keys) => ({ ...rest, ...id && keys.get(id) ?
7311
7311
  function buildNet({ sessions, panes: ps, workspaces: all, children: children2, services, head, sessionDir = join19(process.env.PI_CODING_AGENT_DIR ?? join19(homedir6(), ".pi", "agent"), "sessions") }, refs = /* @__PURE__ */ new Map()) {
7312
7312
  const root = canonical2(sessionDir), readable2 = (file2, id, real3 = file2?.endsWith(".jsonl") ? canonical2(file2) : void 0) => real3 && real3.startsWith(root + sep4) && (!id || basename6(real3).endsWith(`_${id}.jsonl`)) ? real3 : void 0;
7313
7313
  const piFile = (pane, id) => readable2(pane?.agent === "pi" ? pane.agent_session?.value : void 0, id);
7314
- const paneOf = (s2) => ps.find((p) => p.pane_id === s2.herdrLocation?.paneId);
7314
+ const paneOf2 = (s2) => ps.find((p) => p.pane_id === s2.herdrLocation?.paneId);
7315
7315
  const note = (mark2, status) => ({ working: status, waiting: "waiting on a question" })[mark2];
7316
7316
  const joined = sessions.flatMap((s2) => {
7317
- const pane = paneOf(s2), role = joinedRole(pane?.tokens?.sb_role);
7317
+ const pane = paneOf2(s2), role = joinedRole(pane?.tokens?.sb_role);
7318
7318
  return role ? [{ s: s2, pane, role, base: s2.herdrLocation?.workspace?.id, tab: s2.herdrLocation?.tab }] : [];
7319
7319
  });
7320
7320
  const towerOf = (w) => sessions.find((s2) => s2.id === w.tokens?.tower);
7321
7321
  const towers = all.filter((w) => !isSub(w) && !isHead(w)).flatMap((w) => /* @__PURE__ */ ((t) => t ? [t] : [])(towerOf(w)));
7322
- const rowsOf2 = new Map([...joined, ...towers.map((s2) => ({ s: s2, pane: paneOf(s2) }))].map(({ s: s2, pane }) => [s2.id, children2(pane)]));
7322
+ const rowsOf2 = new Map([...joined, ...towers.map((s2) => ({ s: s2, pane: paneOf2(s2) }))].map(({ s: s2, pane }) => [s2.id, children2(pane)]));
7323
7323
  const claimed2 = new Set([...rowsOf2.values()].flat().map((r) => r.workspace));
7324
7324
  const held2 = /* @__PURE__ */ new Set([...joined.map((j) => j.pane?.pane_id), ...[...rowsOf2.values()].flat().map((r) => r.pane)]);
7325
7325
  const keep2 = (r) => (refs.set(r.key, r), r.key);
@@ -7340,7 +7340,7 @@ function buildNet({ sessions, panes: ps, workspaces: all, children: children2, s
7340
7340
  })
7341
7341
  }));
7342
7342
  const outposts = all.filter((x) => isSub(x) && parentOf(all, x) === w && !claimed2.has(x.workspace_id)).map((x) => ({ id: x.workspace_id, label: x.label, mark: markOf(x.agent_status) }));
7343
- const tower = towerOf(w), towerPane = tower && paneOf(tower), towerSubs = tower ? subsOf(tower.id, w.workspace_id) : [];
7343
+ const tower = towerOf(w), towerPane = tower && paneOf2(tower), towerSubs = tower ? subsOf(tower.id, w.workspace_id) : [];
7344
7344
  const outside = ps.filter((p) => p.workspace_id === w.workspace_id && p.agent === "pi" && p.pane_id !== towerPane?.pane_id && !held2.has(p.pane_id) && !p.tokens?.sb_closing).flatMap((p) => {
7345
7345
  const s2 = sessions.find((x) => x.herdrLocation?.paneId === p.pane_id), file2 = p.agent_session?.value;
7346
7346
  const key2 = s2?.id ?? (file2 && basename6(file2, ".jsonl").split("_").pop());
@@ -17728,11 +17728,11 @@ var CarBook = class {
17728
17728
  const project = setter.role === "train" ? train.project : car.project;
17729
17729
  if (!isName(project)) throw refusal3("sb: car needs a project (a path-safe name)");
17730
17730
  if (setter.role === "train" && car.project !== void 0 && car.project !== project) throw refusal3(`sb: this train works for project ${project}, not ${String(car.project)}`);
17731
- if (setter.role === "main" && (state === "dropped" || state === "landed")) throw refusal3(`sb: only a train sets ${state}; the integrator sets received and returned`);
17732
17731
  if (setter.role === "train" && state === "received") throw refusal3("sb: only the integrator sets received");
17733
17732
  let file2, name2, held2, label, before, unchecked;
17734
17733
  if (setter.role === "main") {
17735
17734
  const sent = this.forwardOf(head, setter.session);
17735
+ if (!sent && state !== "received") this.expiredForward(project, head, setter.session, state);
17736
17736
  if (!sent) throw refusal3(`sb: no forward by a tower carries head ${head.slice(0, 12)} to this session: a car slip reaches the integrator only as the tower's tower_send or tower_reply with forward: (the code stamps fwd-from).${this.restartWord()}`);
17737
17737
  const slip = sent.slip;
17738
17738
  if (slip.over) throw refusal3(slip.over);
@@ -17744,16 +17744,19 @@ var CarBook = class {
17744
17744
  const off = claims.find(([, ok]) => !ok);
17745
17745
  if (off) throw refusal3(`sb: car ${label} does not match the forwarded slip: ${off[0]} differs from what the slip the tower forwarded says`);
17746
17746
  const ended = file2 ? endOf(file2) : void 0;
17747
- if (ended && sent.at > Date.parse(ended.at)) {
17747
+ if (ended && sent.at > Date.parse(ended.at) && (state === "received" || state === "returned")) {
17748
17748
  if (ended.state === "landed" && state === "received") throw refusal3(landedWord(label, head, `landed in ${String(ended.version).slice(0, 60)}`));
17749
17749
  const rode = [...this.cars.get(project)?.entries() ?? []].some(([key2, h]) => (key2 === name2 || key2.startsWith(`${name2}${PAST}`)) && h.file.states.some((s2) => s2.state === "received" && s2.train === fields.train));
17750
17750
  if (state === "received" && rode) throw refusal3(`sb: car ${label} rode train ${String(fields.train)} in an earlier life and left it; received names the train it rides now`);
17751
17751
  before = held2;
17752
17752
  held2 = file2 = void 0;
17753
17753
  }
17754
- if (file2?.states.some((s2) => s2.state === "received")) throw refusal3(`sb: car ${label} is already received${state === "returned" ? "; the integrator returns a car at receipt only" : ""}`);
17754
+ const receipt = file2?.states.find((s2) => s2.state === "received");
17755
+ if (receipt && state === "received") throw refusal3(`sb: car ${label} is already received`);
17756
+ if (!receipt && (state === "dropped" || state === "landed")) throw refusal3(`sb: car ${label} was never received, so it is on no train`);
17755
17757
  if (!slip.coordinator) throw refusal3("sb: the slip names no coordinator");
17756
- if (slip.coordinator !== sent.from) {
17758
+ if (receipt) await this.endsReceived(project, file2, receipt, setter, state, fields, head, label);
17759
+ else if (slip.coordinator !== sent.from) {
17757
17760
  const word2 = coordinatorWord(label, slip.coordinator, sent.from);
17758
17761
  if (state === "received") throw refusal3(word2);
17759
17762
  fields.reason = word2;
@@ -17802,6 +17805,56 @@ var CarBook = class {
17802
17805
  }
17803
17806
  return { state, at: entry.at, file: name2, coordinator: next2.coordinator, ...notice ? { notice } : {}, ...unchecked ? { unchecked } : {} };
17804
17807
  }
17808
+ /**
17809
+ * The integrator ends a car it received (boss W45): only once the train it was received for is gone, since a live train sets its cars' fates itself (`trainLive`); with no
17810
+ * record of the open (never opened here, or this server started again since) `dropped` and `returned` are let through, and `landed` is refused, since the base and remote its commit is checked against were read at that open. `landed` is the
17811
+ * same git check a train's is. A car already ended is not ended again.
17812
+ */
17813
+ async endsReceived(project, file2, receipt, setter, state, fields, head, label) {
17814
+ const ended = endOf(file2);
17815
+ if (ended) throw refusal3(`sb: car ${label} is already ${ended.state}`);
17816
+ if (receipt.by.session !== setter.session) throw refusal3(`sb: car ${label} was received by ${receipt.by.name}, not this session: the integrator that received a car ends it`);
17817
+ const code = String(receipt.train), record2 = this.trainOf(project, code);
17818
+ const live = record2 ? await this.trainLive(record2) : void 0;
17819
+ if (live) throw refusal3(live);
17820
+ if (state === "dropped" && (!isAbsolute7(String(fields.evidence)) || !this.d.exists(String(fields.evidence)))) throw refusal3(`sb: dropped.evidence ${String(fields.evidence).slice(0, 200)} is not a file that exists (give its absolute path)`);
17821
+ if (state !== "landed") return;
17822
+ if (!record2) throw refusal3(`sb: this server holds no open of train ${code.slice(0, 40)} (it was never opened here, or the server started again since), so the base and remote car ${label}'s commit would be checked on are unknown and it cannot be set landed`);
17823
+ await this.landed(project, record2, head, String(fields.commit), label, file2.app);
17824
+ }
17825
+ /**
17826
+ * The refusal of an integrator's state for a car it received whose forward the server no longer holds (TCR-F002): a forward counts `KEEP_MS` and the newest `MAX_FORWARDS`, in memory only, and a train that runs long or stalls outlives it. The car's identity
17827
+ * still comes from a forward alone, so nothing is set; the word says why and the way back, a forward of the slip again. A car this session did not receive, or one that ended, gets the refusal it would get anyway.
17828
+ */
17829
+ expiredForward(project, head, session, state) {
17830
+ const held2 = [...this.cars.get(project)?.entries() ?? []].find(([key2, h]) => !key2.includes(PAST) && h.file.car.head === head)?.[1], file2 = held2?.file;
17831
+ const receipt = file2?.states.find((s2) => s2.state === "received");
17832
+ if (!file2 || !receipt || receipt.by.session !== session || endOf(file2)) return;
17833
+ throw refusal3(`sb: car ${file2.car.tickets[0] ?? head.slice(0, 12)} was received by this session, but the tower's forward of its slip has expired${this.d.now() - this.since < KEEP_MS8 ? ` or went with the sb server's restart at ${iso(this.since)}` : ""} (the sb server keeps a forward ${KEEP_MS8 / 36e5} h, and the newest ${MAX_FORWARDS}, in memory only): ask its coordinator ${file2.coordinator} to send its slip to the tower again (call_tower why=shared); the tower forwards it again, and then set ${state}`);
17834
+ }
17835
+ /**
17836
+ * Why the integrator may not end a car of this train yet, or undefined once the train is gone (TCR-F001). The broker's session list alone is no answer: a train's pi that reloads, or a broker that restarts, is missing from it for a while, so a miss there
17837
+ * would read a live train as gone. The pane the server opened the train in is the fact that stays: Herdr lists it with `sb_role=train` and this train's `sb_train` while the train's pi runs, and over its /reload too (presence.ts keeps those tokens), and
17838
+ * its pi clears them when it ends. The train is gone only when that pane is gone or carries something else, and its session does not look up as a train either; a list that cannot be read is no answer, and refuses.
17839
+ */
17840
+ async trainLive(record2) {
17841
+ const code = record2.code, unsure = (what, error) => `sb: cannot tell whether train ${code} is live (${what} could not be read: ${String(error?.message ?? error).slice(0, 200)}): try again; while the train runs, it sets its cars' fates`;
17842
+ const live = `sb: train ${code} is live (session ${record2.session}, pane ${record2.pane}): the train sets its cars' fates; the integrator ends a car it received only once that train is gone (a train whose pi crashed keeps its pane's train tokens until they lapse: close its pane to free its cars)`;
17843
+ let pane;
17844
+ try {
17845
+ pane = await this.d.paneOf(record2.pane);
17846
+ } catch (error) {
17847
+ return unsure("Herdr's pane list", error);
17848
+ }
17849
+ if (pane?.role === "train" && (!pane.train || pane.train.project === record2.project && pane.train.code === code)) return live;
17850
+ let seen;
17851
+ try {
17852
+ seen = await this.d.look(record2.session);
17853
+ } catch (error) {
17854
+ return unsure(`session ${record2.session}`, error);
17855
+ }
17856
+ return seen?.role === "train" ? live : void 0;
17857
+ }
17805
17858
  /**
17806
17859
  * A commit is landed when git, run here, finds it on the real remote's branch of the base. The remote is the one the server read from the tower's checkout at the open, and for a car of an app that is a repository of its own (a submodule of the project) the one it read
17807
17860
  * from that app's checkout there (`appRemotesOf`, 0.80.2): the app's commits are on no branch of the project's remote. The base is the one the manifest named. The tip of that branch is read by `git ls-remote` run
@@ -18189,6 +18242,12 @@ async function look2(o, session) {
18189
18242
  const train = trainFromToken(pane.tokens?.sb_train);
18190
18243
  return { id: session, name: found.name ?? session, ...token ? { role: token } : {}, ...train ? { train } : {}, pane: paneId, ...pane.workspace_id ? { workspace: pane.workspace_id } : {}, ...pane.cwd ? { cwd: pane.cwd } : {}, foreground: foreground2 };
18191
18244
  }
18245
+ async function paneOf(o, paneId) {
18246
+ const pane = (await panes(o.run)).find((p) => p.pane_id === paneId);
18247
+ if (!pane) return void 0;
18248
+ const role = pane.tokens?.sb_role, train = trainFromToken(pane.tokens?.sb_train);
18249
+ return { ...role ? { role } : {}, ...train ? { train } : {} };
18250
+ }
18192
18251
  function knownHostsOfUser() {
18193
18252
  try {
18194
18253
  return readFileSync27(join39(homedir10(), ".ssh", "known_hosts"), "utf8").slice(0, 4e6);
@@ -18204,6 +18263,7 @@ function startCars(o) {
18204
18263
  now: o.now,
18205
18264
  ...o.startedAt !== void 0 ? { startedAt: o.startedAt } : {},
18206
18265
  look: (session) => look2(o, session),
18266
+ paneOf: (pane) => paneOf(o, pane),
18207
18267
  git: runGit,
18208
18268
  knownHosts: knownHostsOfUser(),
18209
18269
  exists: existsSync6,
@@ -19856,9 +19916,9 @@ async function gatherMains(d) {
19856
19916
  const ws = d.workspace.workspace_id, project = d.within?.project;
19857
19917
  const scoped = (m) => !d.within || project !== void 0 && ps.some((p) => p.pane_id === m.s.herdrLocation?.paneId && p.cwd && inside(p.cwd, project));
19858
19918
  const here = netMembers(sessions, ps).filter((m) => m.workspace.id === ws && m.role !== "tower" && scoped(m));
19859
- const paneOf = (s2) => ps.find((p) => p.pane_id === s2.herdrLocation?.paneId);
19919
+ const paneOf2 = (s2) => ps.find((p) => p.pane_id === s2.herdrLocation?.paneId);
19860
19920
  const label = (t) => d.within ? allyLabel(t) : clean(t, 40);
19861
- const live = here.filter((m) => m.role === "main" || m.role === "train").map((m) => ({ session: m.s.id, ...m.role === "train" ? { role: "train" } : {}, name: label(nameOf4(m.s)), workspaceId: ws, workspace: label(d.workspace.label), tab: label(m.tab.label), state: sessionMark(m.s, paneOf(m.s)), commanding: commanding(sessionMark(m.s, paneOf(m.s)), subagents(paneOf(m.s), ps, d.now()).map((r) => r.mark)) === "commanding", ...m.duty ? { duty: m.duty } : {} }));
19921
+ const live = here.filter((m) => m.role === "main" || m.role === "train").map((m) => ({ session: m.s.id, ...m.role === "train" ? { role: "train" } : {}, name: label(nameOf4(m.s)), workspaceId: ws, workspace: label(d.workspace.label), tab: label(m.tab.label), state: sessionMark(m.s, paneOf2(m.s)), commanding: commanding(sessionMark(m.s, paneOf2(m.s)), subagents(paneOf2(m.s), ps, d.now()).map((r) => r.mark)) === "commanding", ...m.duty ? { duty: m.duty } : {} }));
19862
19922
  const board = joinLocal(readEntries(d.boardDir), live, d.now());
19863
19923
  const tabs2 = Object.values(Object.groupBy(here, (m) => m.tab.id));
19864
19924
  const rows = tabs2.map((group2 = []) => {
@@ -19866,7 +19926,7 @@ async function gatherMains(d) {
19866
19926
  const lead = main ?? train;
19867
19927
  const row2 = lead && board.find((r) => r.session === lead.s.id);
19868
19928
  const entry = row2 && d.within && row2.now !== void 0 ? { ...row2, ...forAllies({ now: row2.now, items: row2.items, src: row2.src ?? "set", count: row2.count, who: row2.who }) } : row2;
19869
- const pane = lead && paneOf(lead.s);
19929
+ const pane = lead && paneOf2(lead.s);
19870
19930
  const shown3 = lead && { name: label(nameOf4(lead.s)), id: lead.s.id, state: sessionMark(lead.s, pane), ...pane?.tokens?.sb_opened_by ? { openedBy: label(pane.tokens.sb_opened_by) } : {}, ...entry?.now ? { now: entry.now } : {}, ...entry ? { open: entry.items.filter((x) => !x.done).length } : {}, ...entry?.stale ? { stale: true } : {} };
19871
19931
  return {
19872
19932
  tab: label(group2[0].tab.label),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.80.10",
3
+ "version": "0.80.12",
4
4
  "description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -5,9 +5,9 @@ You are the integrator of one project: the main that places the cars mains send
5
5
  - The project's skill is `integration.skill` (the headings of `integrating`'s Project skill contract). sb reads apps.json and refuses a `train` todo for an app whose `stages` list a uat stage or whose cars show less than `integration.accept`: depart nothing, `why=blocked`, naming the field.
6
6
  - A car slip arrives forwarded by the tower; its `coordinator` is a session id and must equal the forward's `fwd-from`. At receipt run `train check` as your main prompt gives it, with `--accept <evidence>` (`none` for a slip that says `accept: none`) `--app-accept <integration.accept> --slip <slip>` (absolute paths) and check that `auth` covers every `strict` target in `deploy`. An `origin=remote:` forward's `auth` covers only `strict` targets its device's boss granted; else `why=blocked`, naming car and target.
7
7
  - The train runs no acceptance. A car that asks it for UAT, e2e, or any acceptance is returned with: `sb: the train runs no acceptance: car <ticket> asks for <what> (<where>); rewrite its acceptance criteria and run them before loading, then send the evidence in accept:`.
8
- - Set each car's fate with `train_car` (`car`: the slip's first ticket; its `car:` is the app): `received` (`train`, `departs`) or `returned` (the reason). A slip with no tower forward cannot be received: `why=blocked` naming the car, for the tower to have it sent again. The sb server sends the notice; never send a slip's sender a notice yourself. One `train` todo per forming train (`metadata.sb`, `v`: 1, `project`, `app`, `train` (the code, `YYYY-MM-DD-<letters>`), `kind: "train"`, `spec.cars` rows as the slips give them): `in_progress` first (sb holds it until each `received` notice is told) and only then the manifest's call, `completed` on the tower's answer with `result`: `outcome: passed`, the train's `session`, `at`; or `failed`, the `refusal`, `at`.
8
+ - Set each car's fate with `train_car` (`car`: the slip's first ticket; its `car:` is the app; add `app` or `head` when one ticket is on two cars): `received` (`train`, `departs`) or `returned` (the reason). A live train sets its cars' fates; once it is gone, end a car you received for it with `returned`, `dropped` (`round`, `reason`, `evidence`) or `landed` (`version`, `commit`). A slip with no tower forward cannot be received: `why=blocked` naming the car, for the tower to have it sent again. The sb server sends the notice; never send a slip's sender a notice yourself. One `train` todo per forming train (`metadata.sb`, `v`: 1, `project`, `app`, `train` (the code, `YYYY-MM-DD-<letters>`), `kind: "train"`, `spec.cars` rows as the slips give them): `in_progress` first (sb holds it until each `received` notice is told) and only then the manifest's call, `completed` on the tower's answer with `result`: `outcome: passed`, the train's `session`, `at`; or `failed`, the `refusal`, `at`.
9
9
  - Place cars by `departs` and by the `strict` targets their `auth` covers. Depart under `integration.maxTrains`.
10
10
  - Name: `boss_rename` yourself `integ <project>` and never rename again. Keep the ledger at `<project>/<app>.json` in the `trains` folder your role prompt names.
11
- - To depart, `call_tower` with `why: shared` and one `train:` block: `project:`, `code:`, then `app`, `base`, `stages`, `targets`, `skill`, your session id, each car's slip and evidence verbatim.
11
+ - To depart, `call_tower` with `why: shared` and one `train:` block: `project:`, `code:`, then `app`, `base`, `stages`, `targets`, `skill`, your session id. sb appends each car's slip verbatim from the tower's forward; restate none.
12
12
  - A missing heading and a binding you cannot reach are `why=blocked`, naming the cause.
13
13
  - When the queue is empty and no train waits to be opened, `call_tower` with `why=milestone`, reply false, saying idle; the tower closes you.
package/src/briefing.ts CHANGED
@@ -10,6 +10,9 @@ const GRAPH_ADDENDUM: Partial<Record<Graph, string>> = { "fan-out/fan-in": "grap
10
10
 
11
11
  /** What a run was briefed with: the role, a main's kind, and the graph a coordinator's plan named (an integrator and a standing main carry `dispatch.md` whatever their plan says, so they have none here). */
12
12
  interface Briefed { role: Role | undefined; duty: string; graph: Graph | "" }
13
+ /** A steer's `details`: what it tells, and what it was written against (`null`: it replaces the whole role prompt, whatever the model held). */
14
+ interface Told { briefed: Briefed; base: Briefed | null }
15
+ const same = (a: Briefed, b: Briefed) => a.role === b.role && a.duty === b.duty && a.graph === b.graph;
13
16
 
14
17
  /** The role prompt: a system prompt section, set when a run starts, and a steer when the role, the kind, or a coordinator's plan changes during one. */
15
18
  export function createBriefing({ pi, cfg, s, role, guiDir, tell }: Kit, mainDuty: MainDuty) {
@@ -27,43 +30,84 @@ export function createBriefing({ pi, cfg, s, role, guiDir, tell }: Kit, mainDuty
27
30
  const duty = role() === "main" ? mainDuty.now() : "";
28
31
  return { role: role(), duty, graph: duty === "coordinator" ? (mainDuty.graph() ?? "") : "" };
29
32
  };
30
- // The role's prompt is a system prompt section, set when a run starts. A role that changes during a run (a member promoted as it
31
- // dispatches a subagent, mains demoted as their tower quits), a kind that switches, or a plan that names a graph reaches the agent at its next step as a steer; an idle session gets it with its next run.
32
- let briefed: Briefed | undefined, running = false;
33
+ // The role's prompt is a system prompt section, set when a run starts. A role that changes during a run (a member promoted as it dispatches a subagent, mains demoted as their tower quits),
34
+ // a kind that switches, or a plan that names a graph reaches the agent at its next step as a steer; an idle session gets it with its next run.
35
+ // A section that changes is read with the whole context uncached, so a run start keeps it while only the graph moved, and steers the change instead (docs/how-it-works.md, The role section stays put);
36
+ // it is rendered anew (`stale`) where the cache or the steers are gone anyway. `sectioned` is what the section was rendered with, which pi keeps for the whole run, through its compactions.
37
+ // `told` is what the agent holds: the section, then each steer pi delivered (its `message_end`), never one only sent, since pi's queue can drop it first (Esc, the dequeue key, the sb GUI's Edit).
38
+ // One steer waits in the queue at a time (`flight`), and a change meanwhile is written once it arrived, against what it told. A steer an abort left queued arrives at the next run's start, after that run's
39
+ // own was written against the older state: `told` is unknown (`undefined`) then, and the next steer is the whole prompt.
40
+ let idle = () => false, told: Briefed | undefined, sectioned: Briefed | undefined, flight: Told | undefined, running = false, stale = false;
33
41
  // `dir` is the folder of the files the prompt points to (the switch of trainswitch.ts may give a copy), `state` the state folder, whose `trains` folder holds an integrator's ledgers, `cli` the command that runs cli.mjs (`train check`). What a prompt may name is this session's own (its tab's label, its workspace's label, its kind) or fixed for the process, never another session's name or state: the tower's or the main's name in the section rewrote it whenever that session left, came back, or renamed itself, and a rewritten section is read with the whole context uncached; `boss_status` has the live values (docs/how-it-works.md, The role section stays put).
34
42
  const render = (text = "", duty = "") => text.replace(/\{\{(\w+)\}\}/g, (_, key: string) => ({ dir: files ? files.dir : cfg.promptDir, state: guiDir, cli: cliCommand(), tab: s.info.tab, workspace: s.info.workspace, head: s.info.head, duty } as Record<string, string | undefined>)[key] || "none yet");
35
43
  const compose = (parts: string[], duty: string) => render(parts.map((part) => prompts[part]).join("\n\n"), duty);
36
- const steer = (text: string) => pi.sendMessage({ customType: ENTRY, content: `<straw-boss>\n${text}\n</straw-boss>`, display: true }, { deliverAs: "steer" });
44
+ // A compaction that retries no turn gets the message stored, not steered: a steer queued then would make pi continue a run that had ended (runmode.ts does the same with a run's brief).
45
+ let quiet = false;
46
+ // A stored message is in the transcript at the turn's end, and pi reports it to no extension: it is told as it is sent. So is a steer sent while pi is idle (awaiting `agent_settled` handlers, or after a run
47
+ // that failed to start past `before_agent_start`): pi stores it at once (`_appendCustomMessage`), with no `message_end`.
48
+ const steer = (text: string, base: Briefed | null, briefed: Briefed) => {
49
+ const details: Told = { briefed, base };
50
+ pi.sendMessage({ customType: ENTRY, content: `<straw-boss>\n${text}\n</straw-boss>`, display: true, details }, quiet ? { triggerTurn: false } : { deliverAs: "steer" });
51
+ if (quiet || idle()) told = briefed;
52
+ else flight = details;
53
+ };
54
+ /** Steers what changed from `was` to `now`, if anything: a role or a kind gets its whole prompt, which replaces the section's, as does an unknown `was`; a coordinator's graph only what it adds, replaces, or drops (§2a). */
55
+ const steerChange = (was: Briefed | undefined, now: Briefed) => {
56
+ const name = nameOf(now.role);
57
+ if (!name || (was && same(was, now))) return;
58
+ const whole = (lead: string) => steer(`${lead} This replaces the role instructions in your system prompt:\n\n${compose(partsOf(name, now.duty, now.graph), now.duty)}`, null, now);
59
+ if (!was) return whole("Some of your Straw Boss role updates were lost or reached you out of order.");
60
+ if (now.role !== was.role) return whole("Your Straw Boss role changed during this run.");
61
+ if (now.duty !== was.duty) return whole(`Your kind is now ${now.duty}.`);
62
+ const addendum = now.graph ? GRAPH_ADDENDUM[now.graph] : undefined, graph = (text: string) => steer(text, was, now);
63
+ if (!now.graph) return graph(`Your plan has no open graph: drop your "## Dispatch" and "## Graph:" sections.`);
64
+ if (!was.graph) return graph(`Your plan's graph is now ${now.graph}. Add to your instructions:\n\n${compose(["dispatch", ...(addendum ? [addendum] : [])], now.duty)}`);
65
+ if (!addendum) return graph(`Your plan's graph is now ${now.graph}. Drop your "## Graph:" section.`);
66
+ graph(`Your plan's graph is now ${now.graph}. ${GRAPH_ADDENDUM[was.graph] ? 'Replace your "## Graph:" section with' : "Add to your instructions"}:\n\n${compose([addendum], now.duty)}`);
67
+ };
68
+ /** Tells a running agent what changed since what it holds, unless a steer still waits in pi's queue. */
69
+ const rebrief = () => void (running && !flight && steerChange(told, stateOf()));
37
70
  return {
38
- load() {
71
+ /** `isIdle` is pi's idle signal (`ctx.isIdle`) of the session that started. */
72
+ load(isIdle: () => boolean = () => false) {
73
+ idle = isIdle;
39
74
  files = promptSet({ promptDir: cfg.promptDir, stateDir: guiDir, env: cfg.env, warn: (text) => tell(text, "warning") });
40
75
  prompts = Object.fromEntries(PROMPTS.map((name) => [name, files!.read(name)]));
76
+ [told, sectioned, flight, running, stale] = [undefined, undefined, undefined, false, false]; // a session start: the next run renders the section anew
41
77
  },
42
78
  /** Whether the loaded prompts have integration off; before they are loaded, the switch is read as `promptSet` will read it. */
43
79
  off: () => files?.off,
44
80
  /** The folder of the files the prompts point to. */
45
81
  dir: () => (files ? files.dir : cfg.promptDir),
46
- rebrief() {
47
- const now = stateOf(), name = nameOf(now.role);
48
- if (!running || !briefed || !name) return;
49
- const was = briefed;
50
- if (now.role === was.role && now.duty === was.duty && now.graph === was.graph) return;
51
- briefed = now;
52
- if (now.role !== was.role) return steer(`Your Straw Boss role changed during this run. This replaces the role instructions in your system prompt:\n\n${compose(partsOf(name, now.duty, now.graph), now.duty)}`);
53
- if (now.duty !== was.duty) return steer(`Your kind is now ${now.duty}. This replaces the role instructions in your system prompt:\n\n${compose(partsOf(name, now.duty, now.graph), now.duty)}`);
54
- // Only a coordinator's graph differs (§2a): the steer carries what changed, not the prompt.
55
- const addendum = now.graph ? GRAPH_ADDENDUM[now.graph] : undefined;
56
- if (!now.graph) return steer(`Your plan has no open graph: drop your "## Dispatch" and "## Graph:" sections.`);
57
- if (!was.graph) return steer(`Your plan's graph is now ${now.graph}. Add to your instructions:\n\n${compose(["dispatch", ...(addendum ? [addendum] : [])], now.duty)}`);
58
- if (!addendum) return steer(`Your plan's graph is now ${now.graph}. Drop your "## Graph:" section.`);
59
- steer(`Your plan's graph is now ${now.graph}. ${GRAPH_ADDENDUM[was.graph] ? 'Replace your "## Graph:" section with' : "Add to your instructions"}:\n\n${compose([addendum], now.duty)}`);
82
+ rebrief,
83
+ /** pi delivered a message. A steer of this briefing moves what the agent holds to what it tells, when it was written against what the agent held, or tells what it holds already; else what it holds is unknown. */
84
+ delivered(message: { role?: string; customType?: string; details?: unknown }) {
85
+ const d = message.details as Told | undefined;
86
+ if (message.role !== "custom" || message.customType !== ENTRY || !d?.briefed) return;
87
+ const fits = d.base === null || (told !== undefined && (same(d.base, told) || same(d.briefed, told)));
88
+ [told, flight] = [fits ? d.briefed : undefined, flight === d ? undefined : flight];
89
+ rebrief();
90
+ },
91
+ /** The section is rendered anew at the next run start: a compaction or a tree move, as a session start (`load`), left no cache for it, or no steers after it.
92
+ * A run that goes on after a compaction keeps its section, and is told again, at each compaction, what changed since that section was rendered: the steers that said it may be summarized away. */
93
+ fresh(retries = true) {
94
+ stale = true;
95
+ if (!running || !sectioned) return;
96
+ [told, quiet] = [sectioned, !retries];
97
+ rebrief();
98
+ quiet = false;
60
99
  },
61
- /** A run starts: the role's prompt becomes the session's section. */
100
+ /** A run starts: the role's prompt becomes the session's section, or stays it while only the plan's graph moved since it was rendered, and the move is steered once. */
62
101
  begin(sections: Record<string, string>) {
63
102
  const now = stateOf(), name = nameOf(now.role);
64
- if (name) sections[ENTRY] = compose(partsOf(name, now.duty, now.graph), now.duty);
65
- else delete sections[ENTRY];
66
- [briefed, running] = [now, true];
103
+ const kept = (b: Briefed | undefined) => b !== undefined && b.role === now.role && b.duty === now.duty;
104
+ const keep = Boolean(name) && !stale && kept(sectioned) && kept(told);
105
+ if (!name) delete sections[ENTRY];
106
+ else sections[ENTRY] = compose(partsOf(name, now.duty, keep ? sectioned!.graph : now.graph), now.duty);
107
+ if (!keep) [sectioned, told, stale] = [name ? now : undefined, now, false];
108
+ // A steer the last run left undelivered was dropped from pi's queue or waits for this run's start: it is not told, and if it arrives, `delivered` weighs it.
109
+ [running, flight] = [true, undefined];
110
+ rebrief();
67
111
  },
68
112
  settled: () => void (running = false),
69
113
  };
package/src/carwait.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { type CarView, livesOf, noticeStatus } from "./train/cars.ts";
1
+ import { type CarView, livesOf, noticeStatus, type TerminalState } from "./train/cars.ts";
2
2
 
3
- // The integrator's wait for a `returned` notice (docs/specs/2026-11-07-train-workers.md §5.5; issue #13). A car the integrator returns at receipt has no train, so no todo of anyone waits for its notice: when the sb server stops before the notice is
3
+ // The integrator's wait for the notice of a car it ended (docs/specs/2026-11-07-train-workers.md §5.5; issue #13). A car the integrator returns at receipt has no train, and one it ends after its train is gone (boss W45) has no train left, so no todo of anyone waits for its notice: when the sb server stops before the notice is
4
4
  // delivered (after a failed first send, or between setting the state and the first send), its book is gone, the journal on disk is not read back (CR-F003), and nobody would tell the coordinator. So the session that returned the car waits itself: it asks
5
5
  // the server's book (`cars-read`) until the notice is told, and when the server no longer holds the car it calls the tower `blocked` with the notice text. The wait is this process's memory; nothing is read from disk. A session that ends while it
6
6
  // still waits (the tower closes an idle integrator) hands what it waits for to the tower first, since nobody waits after it, and so does a wait the server left undelivered for a day; a process that is killed hands over nothing.
7
7
 
8
8
  const KEEP_MS = 24 * 3600_000, CALL_RETRY_MS = 30_000, CALL_TRIES = 10;
9
9
 
10
- /** One returned car whose notice this session waits for: the car, the session that set it, the moment the server set the state (`at`, which names that state among the car's lives), who is told, and the notice line. */
11
- export interface ReturnWait { session: string; project: string; app: string; head: string; ticket: string; coordinator: string; at: string; line: string; since: number; calls?: number; called?: number }
10
+ /** One car this session ended whose notice it waits for: the state it set (`returned` when absent, as a wait made before W45 has none), the car, the session that set it, the moment the server set the state (`at`, which names that state among the car's lives), who is told, and the notice line. */
11
+ export interface ReturnWait { state?: TerminalState; session: string; project: string; app: string; head: string; ticket: string; coordinator: string; at: string; line: string; since: number; calls?: number; called?: number }
12
12
 
13
13
  /** Where the waits of this process are kept: on `globalThis`, so a `/reload` (a new module in the same process) goes on waiting; never in a file. */
14
14
  const HELD = Symbol.for("pi-straw-boss.cars.returns");
@@ -33,9 +33,9 @@ export const WHY = {
33
33
  ended: "its integrator's session ends while the notice is not delivered yet (the sb server may still deliver it, and nobody else waits for it)",
34
34
  stale: "the sb server has not delivered the notice in a day",
35
35
  } as const;
36
- /** What the tower is told of a returned car whose notice nobody can confirm. */
37
- export const handedWord = (wait: Pick<ReturnWait, "ticket" | "project" | "app" | "coordinator" | "line">, why: string) =>
38
- `car ${wait.ticket} is returned (${wait.project}/${wait.app}) and sb cannot confirm that its coordinator ${wait.coordinator} was told: ${why}. Tell that coordinator the notice, by its session id, or find its owner. The notice: ${wait.line}`;
36
+ /** What the tower is told of an ended car whose notice nobody can confirm. */
37
+ export const handedWord = (wait: Pick<ReturnWait, "state" | "ticket" | "project" | "app" | "coordinator" | "line">, why: string) =>
38
+ `car ${wait.ticket} is ${wait.state ?? "returned"} (${wait.project}/${wait.app}) and sb cannot confirm that its coordinator ${wait.coordinator} was told: ${why}. Tell that coordinator the notice, by its session id, or find its owner. The notice: ${wait.line}`;
39
39
 
40
40
  export function createReturnWatch(d: ReturnWatchDeps) {
41
41
  const waits = d.waits ?? heldWaits();
@@ -69,10 +69,10 @@ export function createReturnWatch(d: ReturnWatchDeps) {
69
69
  if (!views.has(wait.project)) views.set(wait.project, await d.read(wait.project).catch(() => undefined));
70
70
  const cars = views.get(wait.project);
71
71
  if (!cars) continue; // the server does not answer (it may be starting): the wait stays, however long
72
- const lives = livesOf(cars, wait.app, wait.head), life = lives.find((v) => v.file.states.some((s) => s.state === "returned" && s.at === wait.at));
72
+ const state = wait.state ?? "returned", lives = livesOf(cars, wait.app, wait.head), life = lives.find((v) => v.file.states.some((s) => s.state === state && s.at === wait.at));
73
73
  if (life) {
74
74
  // The server holds the state: told (delivered, or the tower was told by the server) ends the wait. While it still sends, the wait goes on, for a day: the server stops sending then, so the tower is handed what it left.
75
- if (noticeStatus(life.notice, "returned").kind !== "pending") drop(wait);
75
+ if (noticeStatus(life.notice, state).kind !== "pending") drop(wait);
76
76
  else if (now - wait.since > KEEP_MS) await hand(wait, WHY.stale, now);
77
77
  continue;
78
78
  }
@@ -95,7 +95,7 @@ export function createReturnWatch(d: ReturnWatchDeps) {
95
95
 
96
96
  return {
97
97
  end,
98
- /** A car this session just returned: its notice is waited for from now on. */
98
+ /** A car this session just ended: its notice is waited for from now on. */
99
99
  add(wait: Omit<ReturnWait, "session" | "since" | "calls" | "called">): void { waits.push({ ...wait, session: d.session() ?? "", since: d.now() }); },
100
100
  tick,
101
101
  /** How many notices this session still waits for. */
package/src/closemain.ts CHANGED
@@ -47,7 +47,7 @@ export function createCloseMain({ pi, cfg, s, me }: Kit, { closeSelf, check, tur
47
47
  if (!workspace?.tokens?.tower || workspace.tokens.tower !== from) return no("the request is not from the tower of this workspace");
48
48
  const running = subagents(mine, all, cfg.now()).filter((row) => !row.ended).length;
49
49
  const subs = running && `${running} subagent${running > 1 ? "s are" : " is"} running`;
50
- // An interrupt aborts the turn in flight, and only that: a dialog, a monitor or a subagent is work the abort does not end, so they still refuse. A queue that survives the abort is another busy answer at the next ask.
50
+ // An interrupt aborts the turn in flight, and only that: a dialog, a monitor or a subagent is work the abort does not end, so they still refuse. A queue that survives the abort (pi's TUI clears it; an RPC or SDK abort does not) is another busy answer at the next ask.
51
51
  if (interrupt && turn?.running()) {
52
52
  const others = [turn.blockers(), subs].filter(Boolean).join(", ");
53
53
  if (others) return { reason: others, busy: true };
@@ -0,0 +1,61 @@
1
+ import { bodyOf, fieldsOf } from "./headerfields.ts";
2
+ import { parseSlip, slipBlocks, slipLines } from "./train/accept.ts";
3
+ import type { CarRow } from "./train/board.ts";
4
+ import { type CarView, currentLife, endOf, forwardsOf } from "./train/cars.ts";
5
+ import { isObject, type Json } from "./train/spec.ts";
6
+ import type { Row } from "./trainboard.ts";
7
+ import { trainFromRequest } from "./trainrole.ts";
8
+
9
+ // The integrator's departure (boss W45, train 2026-11-17-q): the manifest the integrator sends the tower carries every car's slip because sb appends it, never because the model restates it. The tower hands the train the manifest verbatim, and the
10
+ // train's own manifest check (trainguard.ts `parseManifest`) reads the cars only from slip blocks: a manifest that named its slips by path gave the train no car, so it could set no car's fate. The slips come from the tower's forwards on the
11
+ // integrator's branch (the source `train_car received` reads), for the car rows of the integrator's `train` todo of the manifest's code.
12
+ // A car the integrator ended before the open (returned or dropped once received, TCR-F003) is refused here rather than left out: the train todo would still list it, and a train opened with its head could set it nothing (`already returned`), so the todo
13
+ // and the manifest stay one list and the integrator takes the car off the todo.
14
+
15
+ const short = (head: string) => head.slice(0, 12);
16
+ const LEAVE_OUT = "leave the slips out of the manifest: sb appends each car's slip verbatim from the tower's forward";
17
+ /** One slip block, compared line by line without the white space at the ends of its lines. */
18
+ const same = (a: string, b: string) => {
19
+ const norm = (s: string) => s.split(/\r?\n/).map((l) => l.trimEnd()).join("\n").trim();
20
+ return norm(a) === norm(b);
21
+ };
22
+
23
+ /** The slip block of a forward on the branch that carries this head, newest forward first (the server's book takes the newest forward of a head too). */
24
+ function forwardedSlip(forwards: ReturnType<typeof forwardsOf>, head: string): string | undefined {
25
+ for (const forward of [...forwards].reverse()) {
26
+ const block = slipBlocks(slipLines(bodyOf(forward.text))).blocks.find((b) => parseSlip(b).fields.head === head);
27
+ if (block) return block;
28
+ }
29
+ return undefined;
30
+ }
31
+
32
+ /**
33
+ * The integrator's `call_tower` message with every car's forwarded slip appended, or the refusal that sends nothing; undefined when the message is no train manifest (it names no `project:` and train `code:`, as the open reads them).
34
+ * A slip block the message holds already must be the forwarded slip of a car of the train todo, word for word, and is not appended again. `views` is the sb server's book of the project (`cars-read`): a car whose life there has ended rides no train.
35
+ */
36
+ export function manifestWithSlips(message: string, rows: readonly Row[], entries: readonly unknown[], views: readonly CarView[]): { message: string } | { refusal: string } | undefined {
37
+ const id = trainFromRequest(message);
38
+ if ("refusal" in id) return undefined;
39
+ const sbOf = (r: Row) => (isObject(r.metadata?.sb) ? (r.metadata!.sb as Json) : undefined);
40
+ const todo = rows.filter((r) => { const s = sbOf(r); return s?.kind === "train" && s.project === id.project && s.train === id.code; }).at(-1);
41
+ if (!todo) return { refusal: `sb: no train todo of project ${id.project} names train ${id.code}: create it with its cars as the slips give them (and set it in_progress) before the manifest's call` };
42
+ const spec = sbOf(todo)!.spec, cars = (isObject(spec) && Array.isArray(spec.cars) ? spec.cars : []).filter((c): c is CarRow => isObject(c) && typeof c.head === "string");
43
+ const forwards = forwardsOf(entries, fieldsOf), slips = new Map<string, string>();
44
+ for (const car of cars) {
45
+ if (slips.has(car.head)) continue;
46
+ const block = forwardedSlip(forwards, car.head);
47
+ if (!block) return { refusal: `sb: car ${car.tickets?.[0] ?? "?"} (${short(car.head)}) of the train todo has no forward by the tower on this branch: sb appends each car's slip from the tower's forward, so its coordinator sends the slip to the tower again (call_tower why=shared), the tower forwards it, and then call again` };
48
+ const life = currentLife(views, parseSlip(block).fields.car ?? String(sbOf(todo)!.app), car.head), ended = life ? endOf(life.file) : undefined;
49
+ if (ended) return { refusal: `sb: car ${car.tickets?.[0] ?? "?"} (${short(car.head)}) of the train todo is ${ended.state} in the sb server's book (set ${ended.at}): an ended car rides no train, so take it off the train todo, then call again` };
50
+ slips.set(car.head, block);
51
+ }
52
+ const held = new Set<string>();
53
+ for (const block of slipBlocks(message).blocks) {
54
+ const parsed = parseSlip(block), head = parsed.fields.head, ticket = parsed.tickets[0] ?? parsed.fields.branch ?? "unknown", theirs = head ? slips.get(head) : undefined;
55
+ if (!head || !theirs) return { refusal: `sb: the manifest's slip of car ${ticket} names head ${head ? short(head) : "none"}, which is no car of the train todo of ${id.code}: ${LEAVE_OUT}` };
56
+ if (!same(block, theirs)) return { refusal: `sb: the manifest's slip of car ${ticket} (${short(head)}) differs from the slip the tower forwarded: ${LEAVE_OUT}` };
57
+ held.add(head);
58
+ }
59
+ const missing = [...slips].filter(([head]) => !held.has(head)).map(([, block]) => block);
60
+ return missing.length ? { message: `${message.replace(/\s+$/, "")}\n\n${missing.join("\n\n")}\n` } : { message };
61
+ }
@@ -16,9 +16,10 @@ import { writePrivate } from "../trainboard.ts";
16
16
  // A car lands once (#15): `received` is refused for a head the same git check finds on the base's remote branch already, which holds after a restart because it rests on nothing the book remembers.
17
17
  // - A car's lives (#14). A car ends `returned`, `dropped` or `landed`. A forward of the same head that the tower made after that end is its coordinator sending the slip again, so the integrator's next state starts a new life of the car: a new car file under
18
18
  // the same name, with notices of its own. The life before stays in the book under `<name>#<n>` (its notice is still sent, and the train that dropped it still reads it); the journal shows the current life.
19
- // - Claims, each limited to the claimer's own train and granting nothing: `dropped` and `returned` of a car on the claimer's train (it only ends that car's ride), the `version` text of `landed`, and the integrator's `train`, `departs` and `reason` text. A
20
- // process that claims a role it is not can, at worst, end the rides of the cars of the train it registered as (it must be that train's session by Herdr's pane record and the server's own open), or put those words in the notice of a car the tower
21
- // forwarded to the integrator it registered as.
19
+ // - Claims, each limited to the claimer's own train and granting nothing: `dropped` and `returned` of a car on the claimer's train (it only ends that car's ride), the same of a car the integrator received once the server holds that car's train as gone
20
+ // (`endsReceived`), the `version` text of `landed`, and the integrator's `train`, `departs` and `reason` text. A
21
+ // process that claims a role it is not can, at worst, end the rides of the cars of the train it registered as (it must be that train's session by Herdr's pane record and the server's own open), end a car the integrator it registered as
22
+ // received once that car's train is gone, or put those words in the notice of a car the tower forwarded to the integrator it registered as.
22
23
  // - A per-session secret that `register` hands the pi process, once. It is defense in depth, not proof: a registration is not replaced while its process lives, the start time of the process is required, and nothing above depends on it.
23
24
  // The car files and notice records on disk are a display journal for the yard (they are written here, never read here). A restart starts with an empty book: what the disk holds, a train could have written. So a forward made before a restart is gone, and the
24
25
  // integrator's refusal says so (todo #154): for as long as such a forward would have been kept, it names the server's start and the way back, which is the fact again (the coordinator sends the slip, the tower forwards it).
@@ -69,6 +70,8 @@ export const refusal = (text: string) => new Error(text);
69
70
 
70
71
  /** What the server knows of a session from the broker and Herdr: the pane token role, the train token, the pane and its folder, and the pids of the pane's foreground processes (pi is one). */
71
72
  export interface Look { id: string; name: string; role?: string; train?: { project: string; code: string }; pane: string; workspace?: string; cwd?: string; foreground: number[] }
73
+ /** What Herdr's pane list says of one pane: its `sb_role` token and the train its `sb_train` token names. */
74
+ export interface PaneFacts { role?: string; train?: { project: string; code: string } }
72
75
 
73
76
  export interface BookDeps {
74
77
  /** The state folder: the trainboard (the display journal) lives under it. */
@@ -81,6 +84,8 @@ export interface BookDeps {
81
84
  /** When this server started, as the refusal of a forward it does not hold tells it (todo #154); the moment the book was made when absent. */
82
85
  startedAt?: number;
83
86
  look(session: string): Promise<Look | undefined>;
87
+ /** The pane as Herdr lists it now; undefined when Herdr lists no such pane, and a rejection when the list cannot be read. */
88
+ paneOf(pane: string): Promise<PaneFacts | undefined>;
84
89
  /** The checkout folder of the Herdr workspace a session runs in (where the open reads a project's remote); left out, or undefined, the session's own folder is used. */
85
90
  checkoutOf?(look: Look): Promise<string | undefined>;
86
91
  /** The start time of a process, in the form `register` is given; undefined when it cannot be told. */
@@ -502,13 +507,13 @@ export class CarBook {
502
507
  const project = setter.role === "train" ? train!.project : car.project;
503
508
  if (!isName(project)) throw refusal("sb: car needs a project (a path-safe name)");
504
509
  if (setter.role === "train" && car.project !== undefined && car.project !== project) throw refusal(`sb: this train works for project ${project}, not ${String(car.project)}`);
505
- if (setter.role === "main" && (state === "dropped" || state === "landed")) throw refusal(`sb: only a train sets ${state}; the integrator sets received and returned`);
506
510
  if (setter.role === "train" && state === "received") throw refusal("sb: only the integrator sets received");
507
511
 
508
512
  let file: CarFile | undefined, name: string, held: Held | undefined, label: string, before: Held | undefined, unchecked: string | undefined;
509
513
  if (setter.role === "main") {
510
514
  // The integrator's: the slip arrived as a tower's forward to this session; the car is what that slip says, and the session that sent it to the tower is the coordinator. Nothing of the car comes from the caller.
511
515
  const sent = this.forwardOf(head, setter.session);
516
+ if (!sent && state !== "received") this.expiredForward(project, head, setter.session, state);
512
517
  if (!sent) throw refusal(`sb: no forward by a tower carries head ${head.slice(0, 12)} to this session: a car slip reaches the integrator only as the tower's tower_send or tower_reply with forward: (the code stamps fwd-from).${this.restartWord()}`);
513
518
  const slip = sent.slip;
514
519
  if (slip.over) throw refusal(slip.over);
@@ -521,7 +526,8 @@ export class CarBook {
521
526
  if (off) throw refusal(`sb: car ${label} does not match the forwarded slip: ${off[0]} differs from what the slip the tower forwarded says`);
522
527
  // A forward the tower made after the car ended is its coordinator sending the same head again (#14): the car starts a new life, and the state set here is its first. A landed car is not received again in any life (#15); returned, it tells the coordinator so.
523
528
  const ended = file ? endOf(file) : undefined;
524
- if (ended && sent.at > Date.parse(ended.at)) {
529
+ // Only a state at receipt starts a life: a car is dropped or landed in the life it was received in.
530
+ if (ended && sent.at > Date.parse(ended.at) && (state === "received" || state === "returned")) {
525
531
  if (ended.state === "landed" && state === "received") throw refusal(landedWord(label, head, `landed in ${String(ended.version).slice(0, 60)}`));
526
532
  // A train reads the life received for its own code (`lifeFor`), so a new life does not ride a train an earlier life of the car left.
527
533
  const rode = [...(this.cars.get(project)?.entries() ?? [])].some(([key, h]) => (key === name || key.startsWith(`${name}${PAST}`)) && h.file.states.some((s) => s.state === "received" && s.train === fields.train));
@@ -529,9 +535,12 @@ export class CarBook {
529
535
  before = held;
530
536
  held = file = undefined;
531
537
  }
532
- if (file?.states.some((s) => s.state === "received")) throw refusal(`sb: car ${label} is already received${state === "returned" ? "; the integrator returns a car at receipt only" : ""}`);
538
+ const receipt = file?.states.find((s) => s.state === "received");
539
+ if (receipt && state === "received") throw refusal(`sb: car ${label} is already received`);
540
+ if (!receipt && (state === "dropped" || state === "landed")) throw refusal(`sb: car ${label} was never received, so it is on no train`);
533
541
  if (!slip.coordinator) throw refusal("sb: the slip names no coordinator");
534
- if (slip.coordinator !== sent.from) {
542
+ if (receipt) await this.endsReceived(project, file!, receipt, setter, state, fields, head, label);
543
+ else if (slip.coordinator !== sent.from) {
535
544
  const word = coordinatorWord(label, slip.coordinator, sent.from);
536
545
  if (state === "received") throw refusal(word);
537
546
  // A returned car goes to the session that really sent it, with the word.
@@ -578,6 +587,51 @@ export class CarBook {
578
587
  return { state, at: entry.at, file: name, coordinator: next.coordinator, ...(notice ? { notice } : {}), ...(unchecked ? { unchecked } : {}) };
579
588
  }
580
589
 
590
+ /**
591
+ * The integrator ends a car it received (boss W45): only once the train it was received for is gone, since a live train sets its cars' fates itself (`trainLive`); with no
592
+ * record of the open (never opened here, or this server started again since) `dropped` and `returned` are let through, and `landed` is refused, since the base and remote its commit is checked against were read at that open. `landed` is the
593
+ * same git check a train's is. A car already ended is not ended again.
594
+ */
595
+ private async endsReceived(project: string, file: CarFile, receipt: StateEntry, setter: Setter, state: CarState, fields: Record<string, unknown>, head: string, label: string): Promise<void> {
596
+ const ended = endOf(file);
597
+ if (ended) throw refusal(`sb: car ${label} is already ${ended.state}`);
598
+ if (receipt.by.session !== setter.session) throw refusal(`sb: car ${label} was received by ${receipt.by.name}, not this session: the integrator that received a car ends it`);
599
+ const code = String(receipt.train), record = this.trainOf(project, code);
600
+ const live = record ? await this.trainLive(record) : undefined;
601
+ if (live) throw refusal(live);
602
+ if (state === "dropped" && (!isAbsolute(String(fields.evidence)) || !this.d.exists(String(fields.evidence)))) throw refusal(`sb: dropped.evidence ${String(fields.evidence).slice(0, 200)} is not a file that exists (give its absolute path)`);
603
+ if (state !== "landed") return;
604
+ if (!record) throw refusal(`sb: this server holds no open of train ${code.slice(0, 40)} (it was never opened here, or the server started again since), so the base and remote car ${label}'s commit would be checked on are unknown and it cannot be set landed`);
605
+ await this.landed(project, record, head, String(fields.commit), label, file.app);
606
+ }
607
+
608
+ /**
609
+ * The refusal of an integrator's state for a car it received whose forward the server no longer holds (TCR-F002): a forward counts `KEEP_MS` and the newest `MAX_FORWARDS`, in memory only, and a train that runs long or stalls outlives it. The car's identity
610
+ * still comes from a forward alone, so nothing is set; the word says why and the way back, a forward of the slip again. A car this session did not receive, or one that ended, gets the refusal it would get anyway.
611
+ */
612
+ private expiredForward(project: string, head: string, session: string, state: CarState): void {
613
+ const held = [...(this.cars.get(project)?.entries() ?? [])].find(([key, h]) => !key.includes(PAST) && h.file.car.head === head)?.[1], file = held?.file;
614
+ const receipt = file?.states.find((s) => s.state === "received");
615
+ if (!file || !receipt || receipt.by.session !== session || endOf(file)) return;
616
+ throw refusal(`sb: car ${file.car.tickets[0] ?? head.slice(0, 12)} was received by this session, but the tower's forward of its slip has expired${this.d.now() - this.since < KEEP_MS ? ` or went with the sb server's restart at ${iso(this.since)}` : ""} (the sb server keeps a forward ${KEEP_MS / 3_600_000} h, and the newest ${MAX_FORWARDS}, in memory only): ask its coordinator ${file.coordinator} to send its slip to the tower again (call_tower why=shared); the tower forwards it again, and then set ${state}`);
617
+ }
618
+
619
+ /**
620
+ * Why the integrator may not end a car of this train yet, or undefined once the train is gone (TCR-F001). The broker's session list alone is no answer: a train's pi that reloads, or a broker that restarts, is missing from it for a while, so a miss there
621
+ * would read a live train as gone. The pane the server opened the train in is the fact that stays: Herdr lists it with `sb_role=train` and this train's `sb_train` while the train's pi runs, and over its /reload too (presence.ts keeps those tokens), and
622
+ * its pi clears them when it ends. The train is gone only when that pane is gone or carries something else, and its session does not look up as a train either; a list that cannot be read is no answer, and refuses.
623
+ */
624
+ private async trainLive(record: TrainRecord): Promise<string | undefined> {
625
+ const code = record.code, unsure = (what: string, error: unknown) => `sb: cannot tell whether train ${code} is live (${what} could not be read: ${String((error as Error)?.message ?? error).slice(0, 200)}): try again; while the train runs, it sets its cars' fates`;
626
+ const live = `sb: train ${code} is live (session ${record.session}, pane ${record.pane}): the train sets its cars' fates; the integrator ends a car it received only once that train is gone (a train whose pi crashed keeps its pane's train tokens until they lapse: close its pane to free its cars)`;
627
+ let pane: PaneFacts | undefined;
628
+ try { pane = await this.d.paneOf(record.pane); } catch (error) { return unsure("Herdr's pane list", error); }
629
+ if (pane?.role === "train" && (!pane.train || (pane.train.project === record.project && pane.train.code === code))) return live;
630
+ let seen: Look | undefined;
631
+ try { seen = await this.d.look(record.session); } catch (error) { return unsure(`session ${record.session}`, error); }
632
+ return seen?.role === "train" ? live : undefined;
633
+ }
634
+
581
635
  /**
582
636
  * A commit is landed when git, run here, finds it on the real remote's branch of the base. The remote is the one the server read from the tower's checkout at the open, and for a car of an app that is a repository of its own (a submodule of the project) the one it read
583
637
  * from that app's checkout there (`appRemotesOf`, 0.80.2): the app's commits are on no branch of the project's remote. The base is the one the manifest named. The tip of that branch is read by `git ls-remote` run
@@ -6,7 +6,7 @@ import type { IntercomLike } from "./kit.ts";
6
6
  import type { HerdrRun } from "../herdr.ts";
7
7
  import { panes, workspaces } from "../herdr.ts";
8
8
  import { trainFromToken } from "../trainrole.ts";
9
- import { CarBook, type Look } from "./carbook.ts";
9
+ import { CarBook, type Look, type PaneFacts } from "./carbook.ts";
10
10
  import { CarNotices } from "./carnotices.ts";
11
11
  import { type Slot, towerId } from "./record.ts";
12
12
  import type { Reply, Request } from "./socket.ts";
@@ -85,6 +85,14 @@ async function look(o: StartCars, session: string): Promise<Look | undefined> {
85
85
  return { id: session, name: (found.name ?? session), ...(token ? { role: token } : {}), ...(train ? { train } : {}), pane: paneId, ...(pane.workspace_id ? { workspace: pane.workspace_id } : {}), ...(pane.cwd ? { cwd: pane.cwd } : {}), foreground };
86
86
  }
87
87
 
88
+ /** A pane as Herdr lists it now, by its id: undefined when no pane has it; a pane list that cannot be had rejects. */
89
+ async function paneOf(o: StartCars, paneId: string): Promise<PaneFacts | undefined> {
90
+ const pane = (await panes(o.run)).find((p) => p.pane_id === paneId);
91
+ if (!pane) return undefined;
92
+ const role = pane.tokens?.sb_role, train = trainFromToken(pane.tokens?.sb_train);
93
+ return { ...(role ? { role } : {}), ...(train ? { train } : {}) };
94
+ }
95
+
88
96
  /** The user's known_hosts as it is now, read once when the server starts: the copy ssh trusts for the `landed` check (RR2-F002). Missing or unreadable, nothing is known and an ssh remote cannot be checked. */
89
97
  function knownHostsOfUser(): string {
90
98
  try { return readFileSync(join(homedir(), ".ssh", "known_hosts"), "utf8").slice(0, 4_000_000); } catch { return ""; }
@@ -94,7 +102,7 @@ function knownHostsOfUser(): string {
94
102
  export function startCars(o: StartCars): Cars {
95
103
  let notices: CarNotices | undefined;
96
104
  const book = new CarBook({
97
- stateDir: o.slot.stateDir, dir: o.slot.dir, now: o.now, ...(o.startedAt !== undefined ? { startedAt: o.startedAt } : {}), look: (session) => look(o, session), git: runGit, knownHosts: knownHostsOfUser(), exists: existsSync, log: o.log,
105
+ stateDir: o.slot.stateDir, dir: o.slot.dir, now: o.now, ...(o.startedAt !== undefined ? { startedAt: o.startedAt } : {}), look: (session) => look(o, session), paneOf: (pane) => paneOf(o, pane), git: runGit, knownHosts: knownHostsOfUser(), exists: existsSync, log: o.log,
98
106
  // The checkout of the session's workspace, as the tower's open reads it (towers.ts): where the check at `received` finds the project's remote and the app's base.
99
107
  checkoutOf: async (seen) => (seen.workspace ? (await workspaces(o.run)).find((w) => w.workspace_id === seen.workspace)?.worktree?.checkout_path : undefined) ?? seen.cwd,
100
108
  startOf: o.startOf, onChange: () => notices?.kick(), ...o.over,
package/src/session.ts CHANGED
@@ -116,7 +116,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
116
116
  s.ui = ctx.ui;
117
117
  s.hasUI = ctx.hasUI;
118
118
  s.quit = () => ctx.shutdown();
119
- briefing.load();
119
+ briefing.load(() => { try { return ctx.isIdle(); } catch { return false; } }); // a replaced session's context throws
120
120
  s.saved = Object.assign({}, ...ctx.sessionManager.getBranch().flatMap((e) => (e.type === "custom" && e.customType === ENTRY ? [e.data] : [])));
121
121
  s.duty = isCoordinatorDuty(s.saved.duty) ? s.saved.duty : undefined; // the migration's guard is this live value (docs/specs/2026-11-09-agent-kinds.md §2)
122
122
  s.branch = () => ctx.sessionManager.getBranch();
@@ -292,6 +292,10 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
292
292
  // A rename from any source (boss_rename, /name, another extension) can make this main an integrator (§2); its todos are read again after each todo call.
293
293
  pi.on("session_info_changed", (event) => void (!runMode.active() && mainDuty.migrate((event as { name?: string }).name)));
294
294
  pi.on("agent_settled", () => void (!runMode.active() && briefing.settled()));
295
+ pi.on("message_end", (event) => void (!runMode.active() && briefing.delivered(event.message))); // a role steer counts as told once pi delivers it (briefing.ts `told`)
296
+ // A compaction drops the cache and may summarize the steers away, and a tree move may leave them on another branch: the next run renders the role section anew (briefing.ts `fresh`).
297
+ pi.on("session_compact", (event) => void (!runMode.active() && briefing.fresh(event.willRetry)));
298
+ pi.on("session_tree", () => void (!runMode.active() && briefing.fresh()));
295
299
 
296
300
  // A member that dispatches or resumes a subagent without promoting is promoted here, before the subagent starts, unless the tab already has a main.
297
301
  // A tower only coordinates: it dispatches no subagent (one would outlive it with no one to take its result), and opens a main for the work instead.
package/src/traincar.ts CHANGED
@@ -9,7 +9,7 @@ import { startOf } from "./startof.ts";
9
9
  import type { Kit } from "./state.ts";
10
10
  import { snapshotOfBranch } from "./todo.ts";
11
11
  import { parseSlip, slipLines } from "./train/accept.ts";
12
- import { CAR_STATES, type CarState, type CarView, coordinatorWord, forwardsOf, noticeText, validateStateFields } from "./train/cars.ts";
12
+ import { CAR_STATES, type CarState, type CarView, coordinatorWord, forwardsOf, noticeText, type TerminalState, validateStateFields } from "./train/cars.ts";
13
13
  import { isName, isObject, type Json } from "./train/spec.ts";
14
14
  import { type Manifest, rowsOfSnapshot, slipBlocks, type TrainGuard } from "./trainguard.ts";
15
15
  import type { TrainId } from "./trainrole.ts";
@@ -115,12 +115,13 @@ export interface CarToolDeps {
115
115
  role(): "train" | "main" | undefined;
116
116
  train(): TrainId | undefined;
117
117
  manifest(ctx: CarCtx): Manifest | undefined;
118
- client: Pick<CarClient, "set">;
118
+ /** `read` is the train's way to a car its manifest text lacks: the cars the server holds for it. */
119
+ client: Pick<CarClient, "set" | "read">;
119
120
  home: string;
120
- /** The integrator's wait for the notice of a car it returned (carwait.ts, #13): nothing else waits for that notice, so the session does. */
121
+ /** The integrator's wait for the notice of a car it returned at receipt or ended after its train was gone (carwait.ts, #13): no step of a train waits for that notice, so the session does. */
121
122
  returns?: Pick<ReturnWatch, "add">;
122
123
  }
123
- export interface CarParams { car: string; state: CarState; project?: string; train?: string; departs?: string; reason?: string; round?: number; evidence?: string; version?: string; commit?: string }
124
+ export interface CarParams { car: string; state: CarState; app?: string; head?: string; project?: string; train?: string; departs?: string; reason?: string; round?: number; evidence?: string; version?: string; commit?: string }
124
125
  const FIELD_KEYS = ["train", "departs", "reason", "round", "evidence", "version", "commit"] as const;
125
126
 
126
127
  /** The slip blocks of a forwarded message body: a `car: <app> | tickets: …` that follows the tower's own words starts a block of its own line. */
@@ -128,6 +129,14 @@ function slipsOf(body: string) {
128
129
  return slipBlocks(slipLines(body)).blocks.map(parseSlip);
129
130
  }
130
131
 
132
+ /** The cars that match the ticket, one per app and head (the last of each), and the word that refuses more than one. */
133
+ function oneCar<T>(found: readonly T[], key: (x: T) => { app: string; head: string }, ticket: string, where: string): T | undefined {
134
+ const cars = new Map<string, T>();
135
+ for (const x of found) { const k = key(x); cars.delete(`${k.app}|${k.head}`); cars.set(`${k.app}|${k.head}`, x); }
136
+ if (cars.size > 1) throw new Error(`sb: car ${ticket} is on ${cars.size} ${where} (${[...cars.values()].map((x) => `app ${key(x).app} head ${key(x).head.slice(0, 12)}`).join(", ")}): give app or head`);
137
+ return found.at(-1);
138
+ }
139
+
131
140
  const assembles = (rows: ReturnType<typeof rowsOfSnapshot>["rows"]) => rows.flatMap((r) => {
132
141
  const sb = isObject(r.metadata?.sb) ? (r.metadata!.sb as Json) : undefined;
133
142
  if (!sb || sb.kind !== "assemble" || !Number.isInteger(sb.round)) return [];
@@ -143,7 +152,9 @@ export async function trainCar(deps: CarToolDeps, params: CarParams, ctx: CarCtx
143
152
  if (typeof params.car !== "string" || !params.car.trim()) throw new Error("sb: car is the car's first ticket (the first of the slip's tickets:, not its car:, which names the app)");
144
153
  const ticket = params.car.trim();
145
154
  if (role === "train" && state === "received") throw new Error("sb: a train does not set received: the integrator does, at receipt");
146
- if (role === "main" && (state === "dropped" || state === "landed")) throw new Error(`sb: only a train sets ${state}; the integrator sets received and returned`);
155
+ if (params.head !== undefined && !/^[0-9a-f]{40}$/.test(params.head)) throw new Error("sb: head must be 40 hex, the head: of the car's slip");
156
+ if (params.app !== undefined && !isName(params.app)) throw new Error("sb: app must be the car's app, a path-safe name (the car: of its slip)");
157
+ const fits = (app: string | undefined, head: string | undefined) => (params.app === undefined || app === params.app) && (params.head === undefined || head === params.head);
147
158
  const fields: Json = {};
148
159
  for (const key of FIELD_KEYS) if (params[key] !== undefined) fields[key] = params[key];
149
160
  if (typeof fields.evidence === "string" && !isAbsolute(fields.evidence)) fields.evidence = fields.evidence === "~" || fields.evidence.startsWith("~/") ? join(deps.home, fields.evidence.slice(2)) : resolve(ctx.cwd ?? process.cwd(), fields.evidence);
@@ -154,9 +165,10 @@ export async function trainCar(deps: CarToolDeps, params: CarParams, ctx: CarCtx
154
165
  let car: Json, coordinator: string;
155
166
  if (role === "main") {
156
167
  // The slip is one a tower forwarded to this session, and the session that sent it to the tower is the coordinator (§5.5).
157
- const found = forwardsOf(entries, fieldsOf).flatMap((forward) => slipsOf(bodyOf(forward.text)).filter((s) => s.tickets.includes(ticket)).map((slip) => ({ forward, slip })));
158
- const hit = found.at(-1);
159
- if (!hit) throw new Error(`sb: car ${ticket} is on no forwarded slip of this session: a car slip reaches the integrator as the tower's forward, whose header names its sender (fwd-from)`);
168
+ // One ticket can name two cars (two apps, or a car sent again with a new head): app and head tell them apart, and more than one left is refused, never guessed.
169
+ const found = forwardsOf(entries, fieldsOf).flatMap((forward) => slipsOf(bodyOf(forward.text)).filter((s) => s.tickets.includes(ticket) && fits(s.fields.car, s.fields.head)).map((slip) => ({ forward, slip })));
170
+ const hit = oneCar(found, (h) => ({ app: h.slip.fields.car ?? "?", head: h.slip.fields.head ?? "?" }), ticket, "forwarded slips");
171
+ if (!hit) throw new Error(`sb: car ${ticket}${params.app || params.head ? " with that app and head" : ""} is on no forwarded slip of this session: a car slip reaches the integrator as the tower's forward, whose header names its sender (fwd-from)`);
160
172
  const f = hit.slip.fields, head = f.head, claimed = f.coordinator;
161
173
  if (!head || !/^[0-9a-f]{40}$/.test(head) || !f.car || !f.branch || !claimed) throw new Error(`sb: the slip of car ${ticket} needs car:, branch:, head: (40 hex) and coordinator:`);
162
174
  if (state === "received" && claimed !== hit.forward.from) throw new Error(coordinatorWord(ticket, claimed, hit.forward.from));
@@ -165,31 +177,52 @@ export async function trainCar(deps: CarToolDeps, params: CarParams, ctx: CarCtx
165
177
  coordinator = claimed;
166
178
  car = { project, app: f.car, head, tickets: hit.slip.tickets, branch: f.branch, coordinator: claimed };
167
179
  } else {
168
- const manifest = deps.manifest(ctx), mine = manifest?.cars.find((c) => c.ticket === ticket || c.row?.tickets.includes(ticket));
169
- if (!mine?.head) throw new Error(`sb: car ${ticket} is not in this train's manifest`);
170
- const slip = parseSlip(mine.slip), app = slip.fields.car ?? manifest?.app;
180
+ const manifest = deps.manifest(ctx), appOf = (slip: string) => parseSlip(slip).fields.car ?? manifest?.app;
181
+ const listed = manifest?.cars.filter((c) => c.head && (c.ticket === ticket || c.row?.tickets.includes(ticket)) && fits(appOf(c.slip), c.head)) ?? [];
182
+ const mine = oneCar(listed, (c) => ({ app: appOf(c.slip) ?? "?", head: c.head! }), ticket, "cars of this train");
183
+ const found = mine ? { app: appOf(mine.slip), head: mine.head!, slip: parseSlip(mine.slip), tickets: mine.row?.tickets } : await fromBook(deps, ticket, fits);
184
+ const app = found.app, slip = found.slip;
171
185
  if (!app) throw new Error(`sb: the slip of car ${ticket} names no app (car:)`);
172
- const plan = assembles(rows), listed = (round: number) => plan.some((a) => a.round === round && a.removed.includes(ticket));
173
- if (state === "returned" && !listed(1)) throw new Error(`sb: car ${ticket} is returned from the manifest only when round 1's assemble lists it in spec.removed: create that assemble first`);
186
+ const plan = assembles(rows), removes = (round: number) => plan.some((a) => a.round === round && a.removed.includes(ticket));
187
+ if (state === "returned" && !removes(1)) throw new Error(`sb: car ${ticket} is returned from the manifest only when round 1's assemble lists it in spec.removed: create that assemble first`);
174
188
  if (state === "dropped") {
175
189
  const round = Number(fields.round);
176
190
  if (plan.some((a) => a.round <= round && a.removed.includes(ticket))) throw new Error(`sb: car ${ticket} was out of the train before round ${round}`);
177
- if (!listed(round + 1)) throw new Error(`sb: car ${ticket} is dropped from round ${round} when round ${round + 1}'s assemble lists it in spec.removed: create that assemble first`);
191
+ if (!removes(round + 1)) throw new Error(`sb: car ${ticket} is dropped from round ${round} when round ${round + 1}'s assemble lists it in spec.removed: create that assemble first`);
178
192
  }
179
193
  if (state === "landed" && plan.some((a) => a.removed.includes(ticket))) throw new Error(`sb: car ${ticket} was removed from the train, so it cannot land`);
180
194
  coordinator = slip.fields.coordinator ?? "";
181
- car = { app, head: mine.head, tickets: mine.row?.tickets ?? slip.tickets, branch: slip.fields.branch ?? "" };
195
+ car = { app, head: found.head, tickets: found.tickets ?? slip.tickets, branch: slip.fields.branch ?? "" };
182
196
  }
183
197
  const answer = await deps.client.set({ state, car, fields });
184
198
  const told = answer.coordinator || coordinator;
185
- // A car returned at receipt is on no train, so no step of a train waits for its notice: this session does, and calls the tower when the server lost it.
186
- const waiting = role === "main" && state === "returned" && deps.returns !== undefined;
187
- if (waiting) deps.returns!.add({ project: String(car.project), app: String(car.app), head: String(car.head), ticket, coordinator: told, at: answer.at, line: answer.notice ?? noticeText("returned", { ticket, head: String(car.head), reason: String(fields.reason) }) });
199
+ // A car the integrator ends (returned at receipt, or any end once its train is gone) has no step of a train waiting for its notice: this session waits, and calls the tower when the server lost it.
200
+ const waiting = role === "main" && state !== "received" && deps.returns !== undefined;
201
+ if (waiting) deps.returns!.add({ state: state as TerminalState, project: String(car.project), app: String(car.app), head: String(car.head), ticket, coordinator: told, at: answer.at, line: answer.notice ?? lineOf(state, ticket, String(car.head), fields) });
188
202
  const waits = waiting ? "this session waits for that and calls the tower itself if the sb server loses the notice" : `${state === "received" ? "the train todo" : state === "landed" ? "the land step" : "the assemble that removes it"} waits for that${state === "received" ? " before the manifest goes to the tower" : ""}`;
189
203
  const text = `Car ${ticket} is ${state}. sb tells its coordinator (${told}) by session id and confirms the delivery; ${waits}. You send no notice yourself.${answer.unchecked ? ` Received unchecked: ${answer.unchecked}.` : ""}`;
190
204
  return { text, details: { car: ticket, ...answer } };
191
205
  }
192
206
 
207
+ /** The notice line when the server's answer carries none: what the coordinator is sent, from the fields given. */
208
+ function lineOf(state: CarState, ticket: string, head: string, fields: Json): string {
209
+ try { return noticeText(state, { ticket, head, ...(fields as object) }); } catch { return `${state}: your car ${ticket} (${head.slice(0, 12)})`; }
210
+ }
211
+
212
+ /**
213
+ * A car the train's manifest text has no slip for (a manifest that named its slips by path, train 2026-11-17-q): the cars the sb server holds for this train, those the integrator received for it, by ticket and the app and head given. The server's own
214
+ * checks at `set` stay the authority.
215
+ */
216
+ async function fromBook(deps: CarToolDeps, ticket: string, fits: (app: string | undefined, head: string | undefined) => boolean) {
217
+ const train = deps.train();
218
+ if (!train) throw new Error(`sb: car ${ticket} is not in this train's manifest`);
219
+ const views = (await deps.client.read(train.project)).filter((v) => v.file.car.tickets.includes(ticket) && v.file.states.some((s) => s.state === "received" && s.train === train.code) && fits(v.file.app, v.file.car.head));
220
+ const view = oneCar(views, (v) => ({ app: v.file.app, head: v.file.car.head }), ticket, "cars of this train");
221
+ if (!view) throw new Error(`sb: car ${ticket} is neither in this train's manifest nor among the cars the sb server holds for train ${train.code}`);
222
+ const f = view.file;
223
+ return { app: f.app, head: f.car.head, tickets: f.car.tickets, slip: { fields: { car: f.app, branch: f.car.branch, head: f.car.head, coordinator: f.coordinator } as Record<string, string>, tickets: f.car.tickets } };
224
+ }
225
+
193
226
  const FIRST_LOOK_MS = 3_000;
194
227
 
195
228
  /** The tool of a train and of the integrator. Registered when the session has joined the net, unless the merge train is off. `callTower` is this session's `blocked` call to its tower, for a returned car whose notice the server lost (carwait.ts). */
@@ -222,10 +255,12 @@ export function trainCarTool(kit: Kit, guard: () => TrainGuard | undefined, link
222
255
  };
223
256
  pi.registerTool({
224
257
  name: "train_car", label: "train_car",
225
- description: "Set what became of a car: the sb server tells the car's coordinator by session id and confirms the delivery, and the step that depends on it waits for that. For the integrator (state received with train and departs, or returned with reason, at receipt) and a train (returned with reason, dropped with round, reason and evidence, landed with version and commit). Never send a coordinator a notice yourself.",
258
+ description: "Set what became of a car: the sb server tells the car's coordinator by session id and confirms the delivery, and the step that depends on it waits for that. For a train (returned with reason, dropped with round, reason and evidence, landed with version and commit) and the integrator (at receipt: received with train and departs, or returned with reason; and of a car it received, once the train it was received for is gone: returned, dropped or landed; while that train runs, the train sets its cars' fates). A car whose ticket is on two cars is named with app or head. Never send a coordinator a notice yourself.",
226
259
  parameters: Type.Object({
227
260
  car: Type.String({ description: "The car's first ticket: the first of the slip's tickets:, not the slip's car: (which names the car's app)." }),
228
261
  state: Type.Union(CAR_STATES.map((x) => Type.Literal(x))),
262
+ app: Type.Optional(Type.String({ description: "The car's app (the slip's car:), when its ticket is on two cars." })),
263
+ head: Type.Optional(Type.String({ description: "The car's head (the slip's head:, 40 hex), when its ticket is on two cars." })),
229
264
  project: Type.Optional(Type.String({ description: "Integrator only, when no train todo names the project yet." })),
230
265
  train: Type.Optional(Type.String({ description: "received: the train's code, YYYY-MM-DD-<letters>." })),
231
266
  departs: Type.Optional(Type.String({ description: "received: the departure conditions in words." })),
package/src/trainguard.ts CHANGED
@@ -17,9 +17,10 @@ import { type Effect, isObject, type Json, shortCode, STEP_REQUIRED, todoEffects
17
17
  import { type FactStep, stepWaits, type TrainFacts, type Wait, waitMessage } from "./train/waits.ts";
18
18
  import { type Acceptor, buildBoard, buildYard, freezeStep, type Row } from "./trainboard.ts";
19
19
  import type { MainDuty } from "./mainduty.ts";
20
+ import { manifestWithSlips } from "./manifestslips.ts";
20
21
  import type { Roles } from "./roles.ts";
21
22
  import { ENTRY, type Kit } from "./state.ts";
22
- import { TRAIN, type TrainId, trainFromToken, trainToken } from "./trainrole.ts";
23
+ import { TRAIN, type TrainId, trainFromRequest, trainFromToken, trainToken } from "./trainrole.ts";
23
24
  import { integrationOff } from "./trainswitch.ts";
24
25
 
25
26
  // The guard of the train's session (docs/specs/2026-11-07-train-workers.md §7, §21; todo #125 task 4): a `tool_call` handler on the session's own tools. In a train it handles every `todo` and `MonitorCreate` call; in the integrator, the `todo`
@@ -315,8 +316,8 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
315
316
  const startedWord = (id: number, status: string) => `sb: step #${id} is ${status}; a started step is never deleted: complete it as void (why: skipped or superseded)`;
316
317
 
317
318
  /** The server's cars of a project, or the refusal in words: a guard that cannot ask the server does not let a notice-dependent step through. */
318
- async function fetchViews(project: string): Promise<CarView[] | string> {
319
- if (!env.cars) return "sb: this guard has no link to the sb server, so it cannot read the car notices a step waits for";
319
+ async function fetchViews(project: string, what = "the car notices a step waits for"): Promise<CarView[] | string> {
320
+ if (!env.cars) return `sb: this guard has no link to the sb server, so it cannot read ${what}`;
320
321
  try { return await env.cars.read(project); } catch (error) { return `sb: the sb server did not answer for the cars of project ${project} (${(error as Error).message}); try again`; }
321
322
  }
322
323
  /** Whether a step this call completes as passed rests on a notice: a `notice` check, or an assemble that removes cars. */
@@ -532,6 +533,7 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
532
533
 
533
534
  pi.on("tool_call", async (event, ctx) => {
534
535
  const input = event.input;
536
+ if (event.toolName === "call_tower") return isObject(input) ? departure(input, ctx) : undefined;
535
537
  if (!isObject(input) || (event.toolName !== "todo" && event.toolName !== "MonitorCreate")) return undefined;
536
538
  const me = env.train();
537
539
  let reasons: string[] = [];
@@ -551,6 +553,26 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
551
553
  }
552
554
  return reasons.length ? ({ block: true, reason: reasons.join("\n") } satisfies Block) : undefined;
553
555
  });
556
+ /**
557
+ * The integrator's departure (manifestslips.ts): a `call_tower` with why=shared whose message is a train manifest goes out with every car's forwarded slip appended, rewritten in place as a run step's command is (pi hands the tool this same
558
+ * object); a manifest that cannot carry them is refused and nothing is sent.
559
+ */
560
+ async function departure(input: Json, ctx: Ctx): Promise<Block> {
561
+ if (input.why !== "shared" || typeof input.message !== "string" || env.train() || !env.isMain() || env.duty() !== "integrator") return undefined;
562
+ const id = trainFromRequest(input.message);
563
+ if ("refusal" in id) return undefined;
564
+ // The book says which car ended before the open (TCR-F003); a guard that cannot read it sends nothing.
565
+ const views = await fetchViews(id.project, "which cars of the manifest ended, so the manifest is not sent");
566
+ if (typeof views === "string") return { block: true, reason: views };
567
+ try {
568
+ const entries = ctx.sessionManager.getBranch(), out = manifestWithSlips(input.message, rowsOfSnapshot(snapshotOfBranch(entries)).rows, entries, views);
569
+ if (out && "refusal" in out) return { block: true, reason: out.refusal };
570
+ if (out) input.message = out.message;
571
+ return undefined;
572
+ } catch (error) {
573
+ return { block: true, reason: `sb: the train guard could not check this manifest (${(error as Error).message}); try again` };
574
+ }
575
+ }
554
576
  /** Whether a todo call carries a `metadata.sb`, in its own metadata or in a batch's. */
555
577
  function hasSb(input: Json): boolean {
556
578
  const meta = (m: unknown) => isObject(m) && m.sb !== undefined;