pi-straw-boss 0.126.0 → 0.127.1

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.
@@ -5842,6 +5842,7 @@ function slipBlocks(text4) {
5842
5842
  }
5843
5843
  return { header: header.join("\n"), blocks: blocks.map((b) => b.join("\n")) };
5844
5844
  }
5845
+ var manifestBlocks = (text4) => slipBlocks(text4);
5845
5846
  function parseDeparts(value) {
5846
5847
  const refuse3 = (what) => ({ ok: false, refusal: `sb: departs: ${what}` });
5847
5848
  const departs = { mode: "next" };
@@ -6944,13 +6945,13 @@ function noticeStatus(record, state) {
6944
6945
  var landedWord = (ticket, head, how) => `sb: car ${ticket} (${head.slice(0, 12)}) ${how}, so it takes no train again: a car lands once. Return it with this word (train_car returned), which tells its coordinator`;
6945
6946
  var headsIn = (text4) => [...new Set([...text4.matchAll(/(?:^|[\s|])head:\s*([0-9a-f]{40})(?![0-9a-f])/gim)].map((m) => m[1]))];
6946
6947
  function slipsInText(body) {
6947
- const lines = slipLines(body);
6948
- return slipBlocks(lines).blocks.flatMap((block) => {
6949
- const parsed = parseSlip(block), f = parsed.fields;
6950
- if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return [];
6951
- const over = ticketBound(parsed.tickets).join("; "), tickets = over ? parsed.tickets.slice(0, MAX_CAR_TICKETS).map((t) => t.slice(0, MAX_TICKET_CHARS)) : parsed.tickets;
6952
- return [{ app: f.car, tickets, ...over ? { over } : {}, branch: f.branch, head: f.head, ...f.coordinator ? { coordinator: f.coordinator } : {}, ...parsed.problems.length ? { problems: parsed.problems } : {} }];
6953
- });
6948
+ return slipBlocks(slipLines(body)).blocks.flatMap((block) => slipFacts(block) ?? []);
6949
+ }
6950
+ function slipFacts(block) {
6951
+ const parsed = parseSlip(block), f = parsed.fields;
6952
+ if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return void 0;
6953
+ const over = ticketBound(parsed.tickets).join("; "), tickets = over ? parsed.tickets.slice(0, MAX_CAR_TICKETS).map((t) => t.slice(0, MAX_TICKET_CHARS)) : parsed.tickets;
6954
+ return { app: f.car, tickets, ...over ? { over } : {}, branch: f.branch, head: f.head, ...f.coordinator ? { coordinator: f.coordinator } : {}, ...parsed.problems.length ? { problems: parsed.problems } : {} };
6954
6955
  }
6955
6956
  var coordinatorWord = (ticket, coordinator, sender) => `sb: car ${ticket} names coordinator ${coordinator}, but ${sender} sent it; the slip is refused`;
6956
6957
 
@@ -8905,6 +8906,7 @@ export {
8905
8906
  parseSlip,
8906
8907
  startsSlip,
8907
8908
  slipLines,
8909
+ manifestBlocks,
8908
8910
  checkAcceptRef,
8909
8911
  checkEvidence,
8910
8912
  checkCar,
@@ -9093,6 +9095,7 @@ export {
9093
9095
  landedWord,
9094
9096
  headsIn,
9095
9097
  slipsInText,
9098
+ slipFacts,
9096
9099
  coordinatorWord,
9097
9100
  writePrivate2 as writePrivate,
9098
9101
  MAX_CAR_FILES,
@@ -120,7 +120,7 @@ import {
120
120
  writeEnd,
121
121
  writeJson,
122
122
  writerAlive
123
- } from "./chunk-CDTETJUI.mjs";
123
+ } from "./chunk-3XW75EGM.mjs";
124
124
 
125
125
  // src/server/cli.ts
126
126
  import { existsSync as existsSync3, realpathSync as realpathSync4 } from "node:fs";
@@ -172,6 +172,7 @@ import {
172
172
  localEndpoint,
173
173
  localeOf,
174
174
  makeCtx,
175
+ manifestBlocks,
175
176
  markOf,
176
177
  newSecret,
177
178
  newer,
@@ -253,6 +254,7 @@ import {
253
254
  sessionNotes,
254
255
  sessionsDir,
255
256
  shortCode,
257
+ slipFacts,
256
258
  slipLines,
257
259
  slipsInText,
258
260
  slotOf,
@@ -315,7 +317,7 @@ import {
315
317
  writeStartError,
316
318
  writerAlive,
317
319
  yardPath
318
- } from "./chunk-CDTETJUI.mjs";
320
+ } from "./chunk-3XW75EGM.mjs";
319
321
 
320
322
  // src/server/main.ts
321
323
  import { homedir as homedir21 } from "node:os";
@@ -20875,7 +20877,8 @@ var hostOf2 = (url) => {
20875
20877
  function openingFacts(request) {
20876
20878
  const head = request.split(/\r?\n(?=\s*(?:car:|app:[^|\n]*\|\s*(?:car|tickets):))/i)[0] ?? request;
20877
20879
  const base = /(?:^|\n)[ \t>*-]*["']?base["']?[ \t]*[:=][ \t]*["']?([A-Za-z0-9][A-Za-z0-9._/-]{0,199})/i.exec(head)?.[1];
20878
- return { ...base ? { base } : {}, heads: headsIn(request).slice(0, 64) };
20880
+ const heads = manifestBlocks(request).blocks.flatMap((block) => ((slip) => slip && !slip.over && !slip.problems?.length ? [slip.head] : [])(slipFacts(block)));
20881
+ return { ...base ? { base } : {}, heads: [...new Set(heads)].slice(0, 64) };
20879
20882
  }
20880
20883
  var refusal4 = (text14) => new Error(text14);
20881
20884
  var text8 = (v, max) => typeof v === "string" && v.trim() !== "" && v.length <= max;
@@ -23359,7 +23362,7 @@ function opener(env) {
23359
23362
  turn.end?.();
23360
23363
  }
23361
23364
  };
23362
- const openHeld = async ({ request, sender: asked3, label: asked_label, peer, role, project, within: within2, dry, duty, worker, topic, fork }, turn) => {
23365
+ const openHeld = async ({ request, sender: asked3, label: asked_label, peer, role, project, within: within2, dry, duty, worker, topic, fork, senderId }, turn) => {
23363
23366
  const { run: run2, sleep: sleep2 } = env;
23364
23367
  const badTopic = topic === void 0 ? void 0 : topicProblem(topic, role);
23365
23368
  if (badTopic) throw new OpenLimitError(badTopic);
@@ -23387,7 +23390,8 @@ function opener(env) {
23387
23390
  let sender;
23388
23391
  if (peer) sender = { id: asked3, name: peer.label };
23389
23392
  else {
23390
- const matches2 = (await env.sessions()).filter((s2) => s2.id === asked3 || s2.name === asked3);
23393
+ const matches2 = (await env.sessions()).filter((s2) => s2.id === asked3 || !senderId && s2.name === asked3);
23394
+ if (senderId && matches2.length !== 1) throw new Error(`No live session has the id "${asked3}", so the ${role === TRAIN ? "train" : "new main"} could not report back to it`);
23391
23395
  if (matches2.length !== 1) throw new Error(`${matches2.length ? "Several sessions are named" : "No live session is named or has the id"} "${asked3}", so the new main could not report back to it`);
23392
23396
  sender = matches2[0];
23393
23397
  if (integratorOf(sender.id)) throw new OpenLimitError(`The id of sender ${sender.name ?? sender.id} reads as an integrator's marker (${integMark("<project>")}), so no main is opened in its name`);
@@ -25929,6 +25933,7 @@ function gateRun(request, run2) {
25929
25933
  }
25930
25934
  if (LOCAL_READS.has(cmd)) return { ok: true };
25931
25935
  if (run2.kind === "head") return no21(`the head tower's token may not ask for ${cmd}: it forwards to the towers, which open and close mains`);
25936
+ if (cmd === "open-main" && request.role !== void 0 && request.role !== null && request.role !== "") return no21("a run token may not open-main with a role: a run opens a train, an integrator or a worker with boss_open_main, whose checks open-main does not make");
25932
25937
  if (LOCAL_ONLY_OWN_WORKSPACE.has(cmd)) return request.workspace === run2.workspace ? { ok: true } : no21(`a run token may ${cmd} only for its own workspace (${run2.workspace})`);
25933
25938
  if (cmd === "link") {
25934
25939
  const op = opOf(request.body);
@@ -27808,6 +27813,32 @@ ${bodyOf(event.text)}`);
27808
27813
  throw new Error(PEERS_SLIP(event.from.name ?? event.from.id, event.from.id));
27809
27814
  return { ...project !== void 0 ? { project } : {}, event };
27810
27815
  }
27816
+ async function trainOpenOf(host, args) {
27817
+ const request = str12(args, "request"), asked3 = trainFromRequest(request), sender = str12(args, "sender", 300);
27818
+ if ("refusal" in asked3) return { request, sender };
27819
+ const net = await host.reach.read(), found = liveIntegrator(net.ps, net.sessions, asked3.project);
27820
+ if (!found) throw new Error(`No integrator of project ${asked3.project} runs on this computer: a train is opened for the project's integrator, on the manifest it sent.`);
27821
+ if ("refusal" in found) throw new Error(found.refusal);
27822
+ const integ = found.session, named = `${clean(integ.name ?? integ.id, 40)} (session ${integ.id})`;
27823
+ if (sender !== integ.id) {
27824
+ if (net.sessions.some((x) => x.name === sender && x.id !== sender)) throw new Error(`sender has to be the session id of the integrator of project ${asked3.project} (${integ.id}), not a name: a train is opened for its integrator's session alone.`);
27825
+ throw new Error(`${clean(sender, 40)} is not the integrator of project ${asked3.project} (${integ.id}): a train is opened for its integrator's session alone, on the manifest it sent.`);
27826
+ }
27827
+ if (deviceToken(net, integ.id) !== void 0 || (host.openedAnywhere ?? host.openedFor)?.(integ.id) !== void 0) throw new Error(`${named} was opened for a teammate's device, so no train opens for it: a project's integrator is this computer's own.`);
27828
+ const key2 = `${host.stateDir ?? ""}
27829
+ ${host.identity}
27830
+ ${asked3.project}/${asked3.code}`, kept = openedManifests.get(key2);
27831
+ if (kept && kept.integrator === integ.id) return { request: kept.text, sender: integ.id };
27832
+ const event = [...host.slipEvents?.() ?? []].reverse().find((e) => {
27833
+ if (e.from.id !== integ.id) return false;
27834
+ const sent = trainFromRequest(bodyOf(e.text));
27835
+ return !("refusal" in sent) && sent.project === asked3.project && sent.code === asked3.code;
27836
+ });
27837
+ if (!event) throw new Error(`No call_tower (why=shared) this run took from ${named} carries the manifest of train ${asked3.code} of project ${asked3.project}, and this server opened no train of that code for it: a train opens only on the manifest its integrator sent, as it came, never on a run's text. Ask ${clean(integ.name ?? integ.id, 40)} to send the tower its train: manifest again with call_tower (why=shared), then open the train on that message.`);
27838
+ const text14 = bodyOf(event.text);
27839
+ return { request: text14, sender: integ.id, keep: () => void (openedManifests.size > 500 && openedManifests.clear(), openedManifests.set(key2, { integrator: integ.id, text: text14 })) };
27840
+ }
27841
+ var openedManifests = /* @__PURE__ */ new Map();
27811
27842
  function askOpener(host, { project, event }, ally, dry = false) {
27812
27843
  if (!host.openIntegrator) throw new Error("This tower opens no integrator");
27813
27844
  return host.openIntegrator({ request: bodyOf(event.text), sender: event.from.id, role: INTEGRATOR, ...project !== void 0 ? { project } : {}, ...ally ? { within: host.project ?? "" } : {}, ...dry ? { dry } : {} }).catch((error) => {
@@ -27977,8 +28008,12 @@ async function localTool(host, name2, args, extra, ally = false) {
27977
28008
  }
27978
28009
  if (ally && args.fork !== void 0) throw new Error("A fork opens a main for a main of this computer: an ally run does not open one");
27979
28010
  const sender = str12(args, "sender", 300), peer = ally ? peerSender(host.who, sender) : void 0;
27980
- const opened = await host.open({ request: str12(args, "request"), sender: peer?.id ?? sender, ...!ally && args.fork !== void 0 ? { fork: str12(args, "fork", 128) } : {}, ...peer ? { peer } : {}, ...opt3(args, "label") ? { label: opt3(args, "label") } : {}, ...opt3(args, "role") ? { role: opt3(args, "role") } : {}, ...opt3(args, "duty") ? { duty: opt3(args, "duty") } : {}, ...!ally && typeof args.topic === "object" && args.topic !== null ? { topic: args.topic } : {} });
27981
- if (opened.train) return { text: opened.repeated ? `A train was already opened for this request (tab ${opened.tab}); nothing new opened.` : `Opened tab ${opened.tab} with ${trainLabel(opened.train.code)} (session ${opened.main}) and handed it the manifest. It reports to you; close it with boss_close_main after its milestone report.`, details: opened, settles: turnAct(host, extra) };
28011
+ const train = !ally && args.role === TRAIN ? await trainOpenOf(host, args) : void 0, request = train?.request ?? str12(args, "request");
28012
+ const opened = await host.open({ request, sender: peer?.id ?? train?.sender ?? sender, ...train ? { senderId: true } : {}, ...!ally && args.fork !== void 0 ? { fork: str12(args, "fork", 128) } : {}, ...peer ? { peer } : {}, ...opt3(args, "label") ? { label: opt3(args, "label") } : {}, ...opt3(args, "role") ? { role: opt3(args, "role") } : {}, ...opt3(args, "duty") ? { duty: opt3(args, "duty") } : {}, ...!ally && typeof args.topic === "object" && args.topic !== null ? { topic: args.topic } : {} });
28013
+ if (opened.train) {
28014
+ train?.keep?.();
28015
+ return { text: opened.repeated ? `A train was already opened for this request (tab ${opened.tab}); nothing new opened.` : `Opened tab ${opened.tab} with ${trainLabel(opened.train.code)} (session ${opened.main}) and handed it the manifest. It reports to you; close it with boss_close_main after its milestone report.`, details: opened, settles: turnAct(host, extra) };
28016
+ }
27982
28017
  const died = !ally && !opened.repeated && host.dead ? (await host.dead().catch(() => [])).filter((r) => r.openedBy === opened.sender && r.verdict.state === "dead") : [];
27983
28018
  const hint = died.map((r) => ` Note: ${clean(sender, 40)}'s main ${clean(r.name ?? r.session.slice(0, 8), 40)} (session ${r.session.slice(0, 8)}) died ${r.ageMs === void 0 ? "earlier" : `${Math.round(r.ageMs / 6e4)} min ago`}; boss_revive_main revives it, once this main is closed (a sender gets one at a time).`).join("");
27984
28019
  const text14 = (opened.repeated ? `A main was already opened for this request (tab ${opened.tab}); nothing new opened.` : opt3(args, "duty") === "standing" ? `Opened tab ${opened.tab} with a standing main (session ${opened.main}) and handed it the request. It tells ${peer ? "the tower" : sender} once and sends no done report; do not close it, only the boss does.` : `Opened tab ${opened.tab} with a main agent (session ${opened.main}) and handed it the request. ${peer ? `It reports to the tower only; each report wakes a run for ${peer.label} that sends it to the sender.` : `It reports to ${opened.sender} and to you.`}`) + hint;
@@ -32615,7 +32650,7 @@ async function runServer(o) {
32615
32650
  }
32616
32651
  if (request.token !== void 0) {
32617
32652
  run2 = towers?.runs.runOf(request.token);
32618
- const verdict = run2 ? gateRun({ cmd: request.cmd, workspace: request.workspace, body: request.body }, run2) : { ok: false, error: "unknown_token" };
32653
+ const verdict = run2 ? gateRun({ cmd: request.cmd, workspace: request.workspace, body: request.body, role: request.role }, run2) : { ok: false, error: "unknown_token" };
32619
32654
  if (!verdict.ok) return { ok: false, error: verdict.error };
32620
32655
  }
32621
32656
  if (request.cmd === "status") return { ok: true, ...facts(), uptimeMs: now() - startedAt, ...own.lastError ? { lastError: own.lastError } : {}, towers: towers?.status() ?? [], head: towers?.head.status() ?? null, link: link?.status() ?? null, ...guiHost && o.gui !== false ? { gui: guiHost.facts() } : {} };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.126.0",
3
+ "version": "0.127.1",
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",
@@ -1,5 +1,5 @@
1
1
  import { bodyOf, fieldsOf } from "./headerfields.ts";
2
- import { parseSlip, slipBlocks, slipLines } from "./train/accept.ts";
2
+ import { manifestBlocks, parseSlip, slipBlocks, slipLines } from "./train/accept.ts";
3
3
  import type { CarRow } from "./train/board.ts";
4
4
  import { type CarView, currentLife, endOf, forwardsOf } from "./train/cars.ts";
5
5
  import { isObject, type Json } from "./train/spec.ts";
@@ -50,7 +50,7 @@ export function manifestWithSlips(message: string, rows: readonly Row[], entries
50
50
  slips.set(car.head, block);
51
51
  }
52
52
  const held = new Set<string>();
53
- for (const block of slipBlocks(message).blocks) {
53
+ for (const block of manifestBlocks(message).blocks) {
54
54
  const parsed = parseSlip(block), head = parsed.fields.head, ticket = parsed.tickets[0] ?? parsed.fields.branch ?? "unknown", theirs = head ? slips.get(head) : undefined;
55
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
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}` };
package/src/opener.ts CHANGED
@@ -82,7 +82,7 @@ export interface PeerSender { id: string; label: string; short: string }
82
82
  /**
83
83
  * `role`: "train" opens a train on an integrator's manifest (docs/specs/2026-11-07-train-workers.md §3.3); "integrator" finds the one integrator of `project` or opens it, on the car slip the request carries; anything else is refused.
84
84
  */
85
- export interface OpenRequest { request: string; sender: string; label?: string; peer?: PeerSender; role?: string; /** `role: "integrator"`: the project as the caller words it. The code reads the project from the checkout (appsconfig.ts `checkoutProject`), and another word is refused. */ project?: string; /** `role: "integrator"`, an ally run's: the folder its team binds on this computer, which the workspace's checkout must be inside. */ within?: string; /** `role: "integrator"`: only the refusals are wanted, and nothing opens. */ dry?: true; /** The new main's kind (docs/specs/2026-11-09-agent-kinds.md §6): `coordinator` or `standing`; an integrator comes only through `role: "integrator"`, and a train's kind is fixed. */ duty?: string; /** `role: "worker"`: what the server prepared (server/workeropen.ts); `request` is the brief. */ worker?: WorkerOpen; /** `role: "worker"` from an ally run: the slip the run's device sent and its ask (runtools.ts), which the server's door turns into `worker`. */ slip?: { spec: Slip; ask?: string }; /** A main's topic (docs/specs/2026-11-30-topic-mains.md): the tower records it for the main it opens, the label and the folder by default; not for a train, an integrator, or a worker. */ topic?: TopicInput; /** A fork's id (docs/specs/2026-11-30-boss-fork.md): the main opens under that reserved session id, in its source's folder, with the fork's handoff; its source is the sender. */ fork?: string }
85
+ export interface OpenRequest { request: string; sender: string; label?: string; peer?: PeerSender; role?: string; /** `role: "integrator"`: the project as the caller words it. The code reads the project from the checkout (appsconfig.ts `checkoutProject`), and another word is refused. */ project?: string; /** `role: "integrator"`, an ally run's: the folder its team binds on this computer, which the workspace's checkout must be inside. */ within?: string; /** `role: "integrator"`: only the refusals are wanted, and nothing opens. */ dry?: true; /** The new main's kind (docs/specs/2026-11-09-agent-kinds.md §6): `coordinator` or `standing`; an integrator comes only through `role: "integrator"`, and a train's kind is fixed. */ duty?: string; /** `role: "worker"`: what the server prepared (server/workeropen.ts); `request` is the brief. */ worker?: WorkerOpen; /** `role: "worker"` from an ally run: the slip the run's device sent and its ask (runtools.ts), which the server's door turns into `worker`. */ slip?: { spec: Slip; ask?: string }; /** A main's topic (docs/specs/2026-11-30-topic-mains.md): the tower records it for the main it opens, the label and the folder by default; not for a train, an integrator, or a worker. */ topic?: TopicInput; /** A fork's id (docs/specs/2026-11-30-boss-fork.md): the main opens under that reserved session id, in its source's folder, with the fork's handoff; its source is the sender. */ fork?: string; /** `sender` is a session id the caller verified (a train of a tower run: server/runtools.ts `trainOpenOf`): it is matched by id alone, and a session gone since is a refusal, never a name. */ senderId?: true }
86
86
  export interface Opened { tab: string; pane: string; main: string; sender: string; /** Nothing opened: an earlier open of the same request, or the project's integrator that already runs. */ repeated?: true; /** Set for a train: its project and code. */ train?: TrainId; /** Set for an integrator: its project. */ integrator?: string }
87
87
 
88
88
  /** The text the new main starts from: who asked, and what, with nothing summarised. A coordinator answers the sender and the tower that opened it, then waits to be closed; a standing main (`duty`) has no end, so it is told no close is coming. */
@@ -146,7 +146,7 @@ export function opener(env: OpenerEnv) {
146
146
  const turn: { end?: () => void } = {};
147
147
  try { return await openHeld(input, turn); } finally { turn.end?.(); }
148
148
  };
149
- const openHeld = async ({ request, sender: asked, label: asked_label, peer, role, project, within, dry, duty, worker, topic, fork }: OpenRequest, turn: { end?: () => void }): Promise<Opened> => {
149
+ const openHeld = async ({ request, sender: asked, label: asked_label, peer, role, project, within, dry, duty, worker, topic, fork, senderId }: OpenRequest, turn: { end?: () => void }): Promise<Opened> => {
150
150
  const { run, sleep } = env;
151
151
  const badTopic = topic === undefined ? undefined : topicProblem(topic, role); // opens nothing and is not remembered, so the request may come again fixed
152
152
  if (badTopic) throw new OpenLimitError(badTopic);
@@ -178,7 +178,9 @@ export function opener(env: OpenerEnv) {
178
178
  let sender: Pick<Session, "id" | "name">;
179
179
  if (peer) sender = { id: asked, name: peer.label };
180
180
  else {
181
- const matches = (await env.sessions()).filter((s) => s.id === asked || s.name === asked);
181
+ // A sender the caller verified by session id (a train of a tower run of the sb server: server/runtools.ts `trainOpenOf`) is that session or none: a session whose name reads as the id does not stand in for it.
182
+ const matches = (await env.sessions()).filter((s) => s.id === asked || (!senderId && s.name === asked));
183
+ if (senderId && matches.length !== 1) throw new Error(`No live session has the id "${asked}", so the ${role === TRAIN ? "train" : "new main"} could not report back to it`);
182
184
  if (matches.length !== 1) throw new Error(`${matches.length ? "Several sessions are named" : "No live session is named or has the id"} "${asked}", so the new main could not report back to it`);
183
185
  sender = matches[0]!;
184
186
  // The integrators' marker is the opener's own (below): a main opened for a session whose id reads as one would be taken for a project's integrator.
@@ -2,9 +2,10 @@ import { randomBytes } from "node:crypto";
2
2
  import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { hostname } from "node:os";
4
4
  import { isAbsolute, join, parse } from "node:path";
5
+ import { manifestBlocks } from "../train/accept.ts";
5
6
  import { carsDir, trainboardDir } from "../train/board.ts";
6
7
  import { appLinkPaths, appRepos, gitmodulesPaths, readApps } from "../train/appsconfig.ts";
7
- import { addState, type CarFile, carFileName, type CarState, type CarView, coordinatorWord, emptyCar, endOf, headsIn, landedWord, type NoticeRecord, type Setter, type SlipFacts, slipsInText, type StateEntry, stateLine, type StateNotice, validateStateFields } from "../train/cars.ts";
8
+ import { addState, type CarFile, carFileName, type CarState, type CarView, coordinatorWord, emptyCar, endOf, landedWord, type NoticeRecord, type Setter, type SlipFacts, slipFacts, slipsInText, type StateEntry, stateLine, type StateNotice, validateStateFields } from "../train/cars.ts";
8
9
  import { isCode, isName, isObject, SHA_RE } from "../train/spec.ts";
9
10
  import { writePrivate } from "../trainboard.ts";
10
11
 
@@ -59,11 +60,16 @@ export const hostOf = (url: string): string | undefined => {
59
60
  for (const re of URL_OK) { const host = re.exec(url)?.groups?.host; if (host !== undefined) return host.toLowerCase(); }
60
61
  return undefined;
61
62
  };
62
- /** What the server reads from the manifest text the tower opens a train on: the base it names and the heads of its cars. */
63
+ /**
64
+ * What the server reads from the manifest text the tower opens a train on: the base its header names and the heads of its cars. A car is a slip block of the manifest as the train and the integrator's manifest call read it
65
+ * (`manifestBlocks`: a block starts at the start of a line, `car: <app>` with tickets, branch and a 40-hex head, one field a line or in one line), whole and within the bound of a car; a `head:` anywhere else (the brief, a slip quoted inside
66
+ * a line, a slip's review text) names no car (F003). There is no other form.
67
+ */
63
68
  export function openingFacts(request: string): { base?: string; heads: string[] } {
64
69
  const head = request.split(/\r?\n(?=\s*(?:car:|app:[^|\n]*\|\s*(?:car|tickets):))/i)[0] ?? request;
65
70
  const base = /(?:^|\n)[ \t>*-]*["']?base["']?[ \t]*[:=][ \t]*["']?([A-Za-z0-9][A-Za-z0-9._/-]{0,199})/i.exec(head)?.[1];
66
- return { ...(base ? { base } : {}), heads: headsIn(request).slice(0, 64) };
71
+ const heads = manifestBlocks(request).blocks.flatMap((block) => ((slip) => (slip && !slip.over && !slip.problems?.length ? [slip.head] : []))(slipFacts(block)));
72
+ return { ...(base ? { base } : {}), heads: [...new Set(heads)].slice(0, 64) };
67
73
  }
68
74
 
69
75
  export const refusal = (text: string) => new Error(text);
@@ -399,7 +399,7 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
399
399
  }
400
400
  if (request.token !== undefined) {
401
401
  run = towers?.runs.runOf(request.token);
402
- const verdict = run ? gateRun({ cmd: request.cmd, workspace: request.workspace, body: request.body }, run) : { ok: false as const, error: "unknown_token" };
402
+ const verdict = run ? gateRun({ cmd: request.cmd, workspace: request.workspace, body: request.body, role: request.role }, run) : { ok: false as const, error: "unknown_token" };
403
403
  if (!verdict.ok) return { ok: false, error: verdict.error };
404
404
  }
405
405
  if (request.cmd === "status") return { ok: true, ...facts(), uptimeMs: now() - startedAt, ...(own.lastError ? { lastError: own.lastError } : {}), towers: towers?.status() ?? [], head: towers?.head.status() ?? null, link: link?.status() ?? null, ...(guiHost && o.gui !== false ? { gui: guiHost.facts() } : {}) };
@@ -27,7 +27,7 @@ const LOCAL_READS = new Set(["status"]);
27
27
 
28
28
  const no = (error: string): Verdict => ({ ok: false, error });
29
29
  const opOf = (body: unknown) => (typeof body === "object" && body !== null ? (body as { op?: unknown }).op : undefined);
30
- export function gateRun(request: { cmd: string; workspace?: unknown; body?: unknown }, run: RunInfo): Verdict {
30
+ export function gateRun(request: { cmd: string; workspace?: unknown; body?: unknown; role?: unknown }, run: RunInfo): Verdict {
31
31
  const { cmd } = request;
32
32
  if (OWN_TOKEN.has(cmd)) return { ok: true };
33
33
  if (run.kind === "ally") {
@@ -37,6 +37,8 @@ export function gateRun(request: { cmd: string; workspace?: unknown; body?: unkn
37
37
  if (LOCAL_READS.has(cmd)) return { ok: true };
38
38
  // The head opens no mains and sends no link request (HT-D2): its token reads the status and makes its own run's requests, nothing else.
39
39
  if (run.kind === "head") return no(`the head tower's token may not ask for ${cmd}: it forwards to the towers, which open and close mains`);
40
+ // A train, an integrator and a worker open only through `run-tool`'s boss_open_main, where the server checks the integrator and its manifest, the slip, or the device's brief (runtools.ts): `open-main` with a role would skip all of it.
41
+ if (cmd === "open-main" && request.role !== undefined && request.role !== null && request.role !== "") return no("a run token may not open-main with a role: a run opens a train, an integrator or a worker with boss_open_main, whose checks open-main does not make");
40
42
  if (LOCAL_ONLY_OWN_WORKSPACE.has(cmd)) return request.workspace === run.workspace ? { ok: true } : no(`a run token may ${cmd} only for its own workspace (${run.workspace})`);
41
43
  if (cmd === "link") {
42
44
  const op = opOf(request.body);
@@ -1,7 +1,7 @@
1
1
  import { readBoard } from "../boardread.ts";
2
2
  import { type Control, refuseStanding } from "../closemain.ts";
3
3
  import { deadList } from "../deadpane.ts";
4
- import { ForwardAsBefore, INTEGRATOR } from "../integrator.ts";
4
+ import { ForwardAsBefore, INTEGRATOR, liveIntegrator } from "../integrator.ts";
5
5
  import { type Opened, type OpenRequest, type PeerSender, type Revived, type ReviveRequest, WORKER } from "../opener.ts";
6
6
  import { type DeadRow, ReviveRefused, revivedText, rowLine } from "../revive.ts";
7
7
  import { bodyOf } from "../header.ts";
@@ -12,7 +12,7 @@ import { remoteTowers } from "../link/remotelist.ts";
12
12
  import type { AllyBoard, AllyTeam } from "../link/holder.ts";
13
13
  import { clean } from "../board.ts";
14
14
  import type { Reach } from "../reach.ts";
15
- import { trainLabel } from "../trainrole.ts";
15
+ import { TRAIN, trainFromRequest, trainLabel } from "../trainrole.ts";
16
16
  import { headIdOf } from "../reachhead.ts";
17
17
  import { isSub, parentOf } from "../herdr.ts";
18
18
  import type { Kind, RunWho } from "./rungate.ts";
@@ -441,6 +441,40 @@ async function slipOf(host: ToolHost, args: Record<string, unknown>, ally: boole
441
441
  return { ...(project !== undefined ? { project } : {}), event };
442
442
  }
443
443
 
444
+ /**
445
+ * Whose train it is and the manifest it opens on. A train is opened for the project's one integrator on this computer (integrator.ts `liveIntegrator`, the project read from the manifest), named by its session id and
446
+ * never by a name, and not for a main opened for a teammate's device (its pane token or a route table, as the slip door checks). The manifest is that integrator's own `call_tower` (why=shared) this run took, the newest whose
447
+ * `train:` manifest has the request's project and code, as it came (sb appended each car's slip to it, `head:` lines included). The server reads the cars a train may set from that text at the open (trainnote.ts), so the run's
448
+ * restating of it decides nothing: on 2026-11-30 a run passed train 1130q's cars as `1. MP-6031 branch … head 34d6f3b1…`, the server read no head, and the train could set none of its cars. Without that message no train opens: a run's
449
+ * text never authorizes one. A reopen of a code (the opener's ledger answers it) goes on the manifest this server kept from the first open (`openedManifests`), never on a run's text, whether or not the message is still there.
450
+ */
451
+ async function trainOpenOf(host: ToolHost, args: Record<string, unknown>): Promise<{ request: string; sender: string; keep?: () => void }> {
452
+ const request = str(args, "request"), asked = trainFromRequest(request), sender = str(args, "sender", 300);
453
+ // A request the opener refuses (no project or code) goes on to it, which words the refusal.
454
+ if ("refusal" in asked) return { request, sender };
455
+ const net = await host.reach.read(), found = liveIntegrator(net.ps, net.sessions, asked.project);
456
+ if (!found) throw new Error(`No integrator of project ${asked.project} runs on this computer: a train is opened for the project's integrator, on the manifest it sent.`);
457
+ if ("refusal" in found) throw new Error(found.refusal);
458
+ const integ = found.session, named = `${clean(integ.name ?? integ.id, 40)} (session ${integ.id})`;
459
+ if (sender !== integ.id) {
460
+ if (net.sessions.some((x) => x.name === sender && x.id !== sender)) throw new Error(`sender has to be the session id of the integrator of project ${asked.project} (${integ.id}), not a name: a train is opened for its integrator's session alone.`);
461
+ throw new Error(`${clean(sender, 40)} is not the integrator of project ${asked.project} (${integ.id}): a train is opened for its integrator's session alone, on the manifest it sent.`);
462
+ }
463
+ if (deviceToken(net, integ.id) !== undefined || (host.openedAnywhere ?? host.openedFor)?.(integ.id) !== undefined) throw new Error(`${named} was opened for a teammate's device, so no train opens for it: a project's integrator is this computer's own.`);
464
+ const key = `${host.stateDir ?? ""}\n${host.identity}\n${asked.project}/${asked.code}`, kept = openedManifests.get(key);
465
+ if (kept && kept.integrator === integ.id) return { request: kept.text, sender: integ.id };
466
+ const event = [...(host.slipEvents?.() ?? [])].reverse().find((e) => {
467
+ if (e.from.id !== integ.id) return false;
468
+ const sent = trainFromRequest(bodyOf(e.text));
469
+ return !("refusal" in sent) && sent.project === asked.project && sent.code === asked.code;
470
+ });
471
+ if (!event) throw new Error(`No call_tower (why=shared) this run took from ${named} carries the manifest of train ${asked.code} of project ${asked.project}, and this server opened no train of that code for it: a train opens only on the manifest its integrator sent, as it came, never on a run's text. Ask ${clean(integ.name ?? integ.id, 40)} to send the tower its train: manifest again with call_tower (why=shared), then open the train on that message.`);
472
+ const text = bodyOf(event.text);
473
+ return { request: text, sender: integ.id, keep: () => void (openedManifests.size > 500 && openedManifests.clear(), openedManifests.set(key, { integrator: integ.id, text })) };
474
+ }
475
+ /** The manifest each train a run opened went on, by the server's state folder, the tower's identity, and `<project>/<code>`: a reopen of the code goes on it (`trainOpenOf`). Kept for the server's life, in memory, as the opener's ledger is. */
476
+ const openedManifests = new Map<string, { integrator: string; text: string }>();
477
+
444
478
  /**
445
479
  * The opener asked for the slip's integrator, or with `dry` only for its refusals: an ally run below `dispatch` asks so before the gate, so a call the opener refuses spends no Allow (RR151-F005).
446
480
  * The project is the checkout's, read by the opener; the run's word, when it gives one, only has to agree. An ally run's open stays inside the project its team binds here.
@@ -655,8 +689,12 @@ async function localTool(host: ToolHost, name: string, args: Record<string, unkn
655
689
  }
656
690
  if (ally && args.fork !== undefined) throw new Error("A fork opens a main for a main of this computer: an ally run does not open one");
657
691
  const sender = str(args, "sender", 300), peer = ally ? peerSender(host.who, sender) : undefined;
658
- const opened = await host.open({ request: str(args, "request"), sender: peer?.id ?? sender, ...(!ally && args.fork !== undefined ? { fork: str(args, "fork", 128) } : {}), ...(peer ? { peer } : {}), ...(opt(args, "label") ? { label: opt(args, "label")! } : {}), ...(opt(args, "role") ? { role: opt(args, "role")! } : {}), ...(opt(args, "duty") ? { duty: opt(args, "duty")! } : {}), ...(!ally && typeof args.topic === "object" && args.topic !== null ? { topic: args.topic as TopicInput } : {}) });
659
- if (opened.train) return { text: opened.repeated ? `A train was already opened for this request (tab ${opened.tab}); nothing new opened.` : `Opened tab ${opened.tab} with ${trainLabel(opened.train.code)} (session ${opened.main}) and handed it the manifest. It reports to you; close it with boss_close_main after its milestone report.`, details: opened, settles: turnAct(host, extra) };
692
+ const train = !ally && args.role === TRAIN ? await trainOpenOf(host, args) : undefined, request = train?.request ?? str(args, "request");
693
+ const opened = await host.open({ request, sender: peer?.id ?? train?.sender ?? sender, ...(train ? { senderId: true as const } : {}), ...(!ally && args.fork !== undefined ? { fork: str(args, "fork", 128) } : {}), ...(peer ? { peer } : {}), ...(opt(args, "label") ? { label: opt(args, "label")! } : {}), ...(opt(args, "role") ? { role: opt(args, "role")! } : {}), ...(opt(args, "duty") ? { duty: opt(args, "duty")! } : {}), ...(!ally && typeof args.topic === "object" && args.topic !== null ? { topic: args.topic as TopicInput } : {}) });
694
+ if (opened.train) {
695
+ train?.keep?.();
696
+ return { text: opened.repeated ? `A train was already opened for this request (tab ${opened.tab}); nothing new opened.` : `Opened tab ${opened.tab} with ${trainLabel(opened.train.code)} (session ${opened.main}) and handed it the manifest. It reports to you; close it with boss_close_main after its milestone report.`, details: opened, settles: turnAct(host, extra) };
697
+ }
660
698
  // A sender whose own opened main died (docs/specs/2026-11-23-tower-revive.md §3): the run hears of it, since a revive of that main is refused while this one runs (one per sender).
661
699
  const died = !ally && !opened.repeated && host.dead ? (await host.dead().catch(() => [])).filter((r) => r.openedBy === opened.sender && r.verdict.state === "dead") : [];
662
700
  const hint = died.map((r) => ` Note: ${clean(sender, 40)}'s main ${clean(r.name ?? r.session.slice(0, 8), 40)} (session ${r.session.slice(0, 8)}) died ${r.ageMs === undefined ? "earlier" : `${Math.round(r.ageMs / 60_000)} min ago`}; boss_revive_main revives it, once this main is closed (a sender gets one at a time).`).join("");
@@ -100,6 +100,12 @@ export function slipBlocks(text: string): { header: string; blocks: string[] } {
100
100
  return { header: header.join("\n"), blocks: blocks.map((b) => b.join("\n")) };
101
101
  }
102
102
 
103
+ /**
104
+ * The car slips of a train manifest, as the train (trainguard.ts `parseManifest`), the integrator's manifest call (manifestslips.ts) and the sb server's open (server/carbook.ts `openingFacts`) all read them: blocks that start at the
105
+ * start of a line (`slipBlocks`), never a slip quoted inside a line of prose. `slipLines` is for a forward alone, whose slip may follow the tower's words on its line.
106
+ */
107
+ export const manifestBlocks = (text: string): { header: string; blocks: string[] } => slipBlocks(text);
108
+
103
109
  export interface Departs { mode: "next" | "alone" | "with"; with?: string; after?: string; by?: string }
104
110
  export type DepartsResult = { ok: true; departs: Departs } | { ok: false; refusal: string };
105
111
 
package/src/train/cars.ts CHANGED
@@ -294,13 +294,15 @@ export interface SlipFacts { app: string; tickets: string[]; branch: string; hea
294
294
 
295
295
  /** The slips a forwarded text carries: a `car: <app> | tickets: …` that follows the tower's own words starts a block of its own line (`slipLines`). Only a slip that names app, tickets, branch and a 40-hex head is returned, with what its parse refused. */
296
296
  export function slipsInText(body: string): SlipFacts[] {
297
- const lines = slipLines(body);
298
- return slipBlocks(lines).blocks.flatMap((block) => {
299
- const parsed = parseSlip(block), f = parsed.fields;
300
- if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return [];
301
- const over = ticketBound(parsed.tickets).join("; "), tickets = over ? parsed.tickets.slice(0, MAX_CAR_TICKETS).map((t) => t.slice(0, MAX_TICKET_CHARS)) : parsed.tickets;
302
- return [{ app: f.car, tickets, ...(over ? { over } : {}), branch: f.branch, head: f.head!, ...(f.coordinator ? { coordinator: f.coordinator } : {}), ...(parsed.problems.length ? { problems: parsed.problems } : {}) }];
303
- });
297
+ return slipBlocks(slipLines(body)).blocks.flatMap((block) => slipFacts(block) ?? []);
298
+ }
299
+
300
+ /** One slip block as the server reads it: undefined unless it names app, tickets, branch and a 40-hex head; what its parse refused, and its bound, are on it. */
301
+ export function slipFacts(block: string): SlipFacts | undefined {
302
+ const parsed = parseSlip(block), f = parsed.fields;
303
+ if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return undefined;
304
+ const over = ticketBound(parsed.tickets).join("; "), tickets = over ? parsed.tickets.slice(0, MAX_CAR_TICKETS).map((t) => t.slice(0, MAX_TICKET_CHARS)) : parsed.tickets;
305
+ return { app: f.car, tickets, ...(over ? { over } : {}), branch: f.branch, head: f.head!, ...(f.coordinator ? { coordinator: f.coordinator } : {}), ...(parsed.problems.length ? { problems: parsed.problems } : {}) };
304
306
  }
305
307
 
306
308
  /** The word for a slip whose `coordinator` is not the session that sent it (§5.5). */
@@ -0,0 +1,34 @@
1
+ import { isObject, type Json } from "./spec.ts";
2
+
3
+ // A main's `todo move` batch under the train rules (pi-todo-ledger 0.12.0; MOVE-F005, docs/specs/2026-11-30-boss-fork.md, The train guard on a move). Pure: the ledger's change comes in, the refusal lines go out.
4
+
5
+ const ids = (value: unknown): number[] => (Array.isArray(value) ? value.filter((d): d is number => Number.isInteger(d)) : []);
6
+ const live = (t: Json) => t.status !== "deleted";
7
+ const isTrain = (t: Json) => isObject(t.metadata) && t.metadata.sb !== undefined;
8
+
9
+ /**
10
+ * What the train holds in a move batch, judged on the whole batch before anything moves: a todo that carries `metadata.sb` (only an integrator imports one, and the source cannot see where the batch goes), a todo that
11
+ * waits on one, and a todo one waits on, even when `dropBlockers` would cut the edge. Each is named with its reason, and a last line says nothing moved; none when the batch holds nothing of the train.
12
+ */
13
+ export function heldInMove(change: { params: Record<string, unknown>; before: readonly unknown[]; after: readonly unknown[] }): string[] {
14
+ const tasks = change.before.filter((t): t is Json => isObject(t) && Number.isInteger(t.id));
15
+ const trains = tasks.filter((t) => live(t) && isTrain(t));
16
+ // The batch: the ids the call names, and any task the ledger would take that the call did not name (a tombstone in `after` that `before` had live).
17
+ const batch = new Set(ids(change.params.ids));
18
+ for (const t of change.after) if (isObject(t) && t.status === "deleted" && tasks.some((b) => b.id === t.id && live(b))) batch.add(t.id as number);
19
+ const lines: string[] = [], held: number[] = [];
20
+ for (const t of tasks.filter((x) => live(x) && batch.has(x.id as number)).sort((a, b) => (a.id as number) - (b.id as number))) {
21
+ const id = t.id as number;
22
+ const why = [
23
+ ...(isTrain(t) ? [`sb: todo #${id} is a train todo (metadata.sb): it stays with the integrator that holds it`] : []),
24
+ ...trains.filter((s) => ids(t.blockedBy).includes(s.id as number)).map((s) => `sb: todo #${id} waits on train todo #${String(s.id)}: it stays with the train todo it waits on`),
25
+ ...trains.filter((s) => ids(s.blockedBy).includes(id)).map((s) => `sb: todo #${id} blocks train todo #${String(s.id)}: it stays with the train todo that waits on it`),
26
+ ];
27
+ if (why.length) (lines.push(...why), held.push(id));
28
+ }
29
+ // A train todo the batch would change otherwise (an edge the ledger drops that the rules above did not name): kept whole too.
30
+ const was = new Map(tasks.map((t) => [t.id as number, JSON.stringify(t)] as const));
31
+ const changed = change.after.find((t): t is Json => isObject(t) && isTrain(t) && live(t) && was.get(t.id as number) !== JSON.stringify(t));
32
+ if (!lines.length && changed) lines.push(`sb: todo #${String(changed.id)} is a train todo (metadata.sb): this move would change its edges, and it stays as it is`);
33
+ return lines.length ? [...lines, `sb: nothing moved; move the others without ${held.length ? held.map((id) => `#${id}`).join(", ") : "changing it"}`] : [];
34
+ }
package/src/trainguard.ts CHANGED
@@ -8,13 +8,14 @@ import { serverCli } from "./server/version.ts";
8
8
  import { startOf } from "./startof.ts";
9
9
  import { snapshotOfBranch } from "./todo.ts";
10
10
  import { CHANGED_EVENT, GUARD_EVENT, type LedgerChange, READY_EVENT } from "./todoledger.ts";
11
- import { type Acceptance, acceptanceOf, checkAcceptRef, checkCar, checkEvidence, type EvidenceOptions, parseSlip, slipBlocks } from "./train/accept.ts";
11
+ import { type Acceptance, acceptanceOf, checkAcceptRef, checkCar, checkEvidence, type EvidenceOptions, manifestBlocks, parseSlip, slipBlocks } from "./train/accept.ts";
12
12
  import { checkContract, type Contract, type SkillCommand } from "./train/contract.ts";
13
13
  import { type AppIntegration, carRepos, readAppIntegration } from "./train/appsconfig.ts";
14
14
  import { type BoardRead, type BoardStep, boardPath, capBoard, type CarRow, factsOf, readBoard, readTrainboards, validateTrainTodo, type Writer, writeBoard, writeYard } from "./train/board.ts";
15
15
  import { type CarView, coordinatorWord, forwardsFor, forwardsOf, noticeSatisfied, receivedTold, type TerminalState } from "./train/cars.ts";
16
16
  import { fieldsOf } from "./headerfields.ts";
17
17
  import { type Effect, isObject, type Json, shortCode, STEP_REQUIRED, todoEffects, validateStep } from "./train/spec.ts";
18
+ import { heldInMove } from "./train/moves.ts";
18
19
  import { type FactStep, stepWaits, type TrainFacts, type Wait, waitMessage } from "./train/waits.ts";
19
20
  import { type Acceptor, buildBoard, buildYard, freezeStep, type Row } from "./trainboard.ts";
20
21
  import type { MainDuty } from "./mainduty.ts";
@@ -82,7 +83,7 @@ export interface ManifestCheck { config(app: string | undefined): AppIntegration
82
83
  const OWED = /^sb: (acceptance evidence lacks |accept: none is allowed only |accept: .* names an evidence file, but it was not read)/;
83
84
 
84
85
  export function parseManifest(text: string, read: (path: string) => string | undefined, check: ManifestCheck): Manifest {
85
- const { header, blocks } = slipBlocks(text), cars: ManifestCar[] = [], leftOut: LeftOut[] = [];
86
+ const { header, blocks } = manifestBlocks(text), cars: ManifestCar[] = [], leftOut: LeftOut[] = [];
86
87
  const app = /^\s*app:\s*([A-Za-z0-9._-]{1,64})\s*$/m.exec(header)?.[1], config = check.config(app), appAccept = config.ok ? config.accept : [];
87
88
  for (const slip of blocks) {
88
89
  const parsed = parseSlip(slip), ticket = parsed.tickets[0] ?? parsed.fields.branch ?? "unknown", accept = parsed.fields.accept;
@@ -558,16 +559,18 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
558
559
  if (input.action === "import") {
559
560
  if (me) return ["sb: a train's list is never imported"];
560
561
  if (!env.isMain() || !after) return []; // only the ledger supports import; its check, not tool_call, receives the list
561
- let project: string | undefined;
562
- // An append (a move file's tasks, docs/specs/2026-11-30-boss-fork.md) is judged on what it appends: the tasks from the list's next id on, never those already in it.
562
+ // An append (a move file's tasks, docs/specs/2026-11-30-boss-fork.md) is judged on what it appends: the tasks from the list's next id on, never those already in it. Its train todos must be of the
563
+ // project of the train todos the list holds, as a create of one must (integratorTodo): a train of another project is another integrator's.
564
+ const held = input.append === true ? state().rows.map(sbOf).find((s) => s?.kind === "train")?.project : undefined;
565
+ let project = typeof held === "string" ? held : undefined, carried = false;
563
566
  for (const t of input.append === true ? after.filter((t) => isObject(t) && (t.id as number) >= state().nextId) : after) {
564
567
  if (!isObject(t) || !isObject(t.metadata) || t.metadata.sb === undefined) continue;
565
568
  if (env.duty() !== "integrator") return [NOT_INTEGRATOR];
566
569
  const sb = t.metadata.sb, refusals = trainRefusals(sb, ctx, t.status as string, t.id as number, project);
567
570
  if (refusals.length) return refusals;
568
- if (isObject(sb) && typeof sb.project === "string") project = sb.project;
571
+ if (isObject(sb) && typeof sb.project === "string") (project = sb.project, carried = true);
569
572
  }
570
- return project === undefined ? [] : contractRefusal();
573
+ return carried ? contractRefusal() : [];
571
574
  }
572
575
  const integrators = !me && env.isMain() && (hasSb(input) || changesTrainTodo(input, state));
573
576
  const reasons = me ? await trainTodo(input, ctx, me, state) : integrators ? (env.duty() === "integrator" ? await integratorTodo(input, ctx, state) : [NOT_INTEGRATOR]) : [];
@@ -590,16 +593,13 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
590
593
  }
591
594
  }
592
595
  /**
593
- * A move batch (pi-todo-ledger 0.12.0; MOVE-F005, docs/specs/2026-11-30-boss-fork.md) under the rules a removal already has: a train's list is never imported and never moves, and a main keeps each todo that carries
594
- * `metadata.sb`, moved or changed by the move (an edge dropped), since only an integrator imports one and the source cannot see where the batch goes. Everything else passes, as the delete of a plain todo does.
596
+ * A move batch (pi-todo-ledger 0.12.0; MOVE-F005, docs/specs/2026-11-30-boss-fork.md) under the rules a removal already has: a train's list is never imported and never moves, and a main keeps what the train holds,
597
+ * judged on the whole batch (train/moves.ts). Everything else passes, as the delete of a plain todo does; a todo whose child still runs is the live-child guard's (`sb-fork`, forkmain.ts).
595
598
  */
596
599
  function moveReasons(change: LedgerChange): string[] {
597
600
  if (env.train()) return [TRAIN_STAYS];
598
601
  if (env.pending?.()) return [UNSETTLED];
599
- if (!env.isMain()) return [];
600
- const was = new Map(change.before.flatMap((t) => (isObject(t) && Number.isInteger(t.id) ? [[t.id as number, JSON.stringify(t)] as const] : [])));
601
- const held = change.after.find((t): t is Json => isObject(t) && isObject(t.metadata) && t.metadata.sb !== undefined && was.get(t.id as number) !== JSON.stringify(t));
602
- return held ? [`sb: todo #${String(held.id)} is a train todo (metadata.sb): it stays with the integrator that holds it, and this move would ${held.status === "deleted" ? "take it away" : "change its edges"}. Move the others without it`] : [];
602
+ return env.isMain() ? heldInMove(change) : [];
603
603
  }
604
604
  const contractRefusal = (): string[] => { const contract = contractNow(); return contract && !contract.ok ? [contract.refusal] : []; };
605
605
  // A guard that fails does not let the call through: the train's checks are enforcement.