pi-straw-boss 0.74.0 → 0.75.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.
@@ -3816,6 +3816,8 @@ function joinLocal(entries, mains, now, o = {}) {
3816
3816
  var KINDS = ["assemble", "review", "full-check", "merge", "ci", "deploy", "deploy-verify", "rollback", "land"];
3817
3817
  var CHECK_TYPES = ["run", "git", "report", "notice"];
3818
3818
  var MAX_SB_BYTES = 8 * 1024;
3819
+ var MAX_CAR_TICKETS = 64;
3820
+ var MAX_TICKET_CHARS = 64;
3819
3821
  var SHA_RE = /^[0-9a-f]{40}$/;
3820
3822
  var NAME_RE = /^[A-Za-z0-9._-]{1,64}$/;
3821
3823
  var CODE_RE = /^(\d{4})-(\d{2})-(\d{2})-([a-z]{1,2})$/;
@@ -4196,10 +4198,18 @@ function asksTrain(value) {
4196
4198
  var NOT_SCANNED = /* @__PURE__ */ new Set(["head", "tested-on", "coordinator", "departs", "accept", "uat"]);
4197
4199
  var base = (path) => path.split(/[\\/]/).pop() ?? path;
4198
4200
  var namesCheckpoints = (path) => base(path).toLowerCase().split(/[^a-z0-9]+/).some((token) => /^(checkpoints?|conditions?)$/.test(token));
4201
+ function ticketBound(tickets) {
4202
+ const out = [];
4203
+ if (tickets.length > MAX_CAR_TICKETS) out.push(`sb: slip tickets names ${tickets.length} tickets, and a car carries at most ${MAX_CAR_TICKETS}: split the car into two or more slips`);
4204
+ const long2 = tickets.find((t) => t.length > MAX_TICKET_CHARS);
4205
+ if (long2 !== void 0) out.push(`sb: slip ticket ${shown(long2)} is longer than ${MAX_TICKET_CHARS} characters: name the ticket by its id`);
4206
+ return out;
4207
+ }
4199
4208
  function checkSlip(slip, { appAccept }) {
4200
4209
  const { fields, tickets, entries, problems } = parseSlip(slip), out = [...problems], car = tickets[0] ?? fields.branch ?? "unknown";
4201
4210
  if (!SHA_RE.test(fields.head ?? "")) out.push("sb: slip head must be 40 hex");
4202
4211
  if (tickets.length === 0) out.push("sb: slip tickets is empty");
4212
+ out.push(...ticketBound(tickets));
4203
4213
  if (present2(fields.uat)) {
4204
4214
  if (fields.uat.toLowerCase() === "none") out.push("sb: the slip's uat: line is gone; send accept: <evidence file> | none");
4205
4215
  else out.push(acceptanceWord({ car, what: `UAT (${fields.uat})`, where: "slip line uat:" }));
@@ -4273,7 +4283,7 @@ function checkEvidence(raw, o) {
4273
4283
  else {
4274
4284
  for (const key2 of Object.keys(car)) if (present2(car[key2]) && !["app", "tickets", "branch", "head"].includes(key2)) out.push(`sb: evidence.car.${key2} is not a field`);
4275
4285
  if (!isName(car.app)) out.push("sb: evidence.car.app must be a path-safe name");
4276
- if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.every((t) => text(t, 64)))) out.push("sb: evidence.car.tickets must be a non-empty list of tickets");
4286
+ if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.length <= MAX_CAR_TICKETS && car.tickets.every((t) => text(t, MAX_TICKET_CHARS)))) out.push(`sb: evidence.car.tickets must be a list of 1 to ${MAX_CAR_TICKETS} tickets`);
4277
4287
  if (!text(car.branch, 255)) out.push("sb: evidence.car.branch must be a non-empty string");
4278
4288
  if (!SHA_RE.test(String(car.head))) out.push("sb: evidence.car.head must be 40 hex");
4279
4289
  else if (o.head !== void 0 && car.head !== o.head) out.push("sb: evidence.car.head is not the slip's head");
@@ -4429,6 +4439,7 @@ function trainFromToken(token) {
4429
4439
  return isName(project) && isCode(code) ? { project, code } : void 0;
4430
4440
  }
4431
4441
  var trainLabel = (code) => `train ${shortCode(code)}`;
4442
+ var isRoleLabel = (label2) => label2 === TOWER_LABEL || label2 === HEAD_LABEL || /^train \d{4}[a-z]{1,2}$/.test(label2);
4432
4443
  function trainFromRequest(request2) {
4433
4444
  const find = (key2) => new RegExp(`(?:^|[{,])[ \\t>*-]*["']?${key2}["']?[ \\t]*[:=][ \\t]*["']?([^\\s"',}]+)`, "im").exec(request2)?.[1];
4434
4445
  const [project, code] = [find("project"), find("code")];
@@ -4491,7 +4502,7 @@ var text2 = (value, max) => typeof value === "string" && value.trim() !== "" &&
4491
4502
  var whole = (value, min, max = Number.MAX_SAFE_INTEGER) => typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
4492
4503
  var unknown = (value, allowed, path) => Object.keys(value).filter((k) => present3(value[k]) && !allowed.includes(k)).map((k) => `sb: ${path}.${k} is not a field`);
4493
4504
  var CAR_FIELDS = ["tickets", "branch", "head", "coordinator", "departs", "accept", "arrived", "accepted", "unverified"];
4494
- var CAP = { session: 128, pane: 64, ticket: 64, tickets: 16, branch: 255, coordinator: 128, departs: 300, accept: 1024, name: 64, kind: 32, reason: 600, by: 128, label: 64 };
4505
+ var CAP = { session: 128, pane: 64, ticket: MAX_TICKET_CHARS, tickets: MAX_CAR_TICKETS, branch: 255, coordinator: 128, departs: 300, accept: 1024, name: 64, kind: 32, reason: 600, by: 128, label: 64 };
4495
4506
  function writerRefusals(w, path) {
4496
4507
  if (!isObject2(w)) return [`sb: ${path} must be an object`];
4497
4508
  const out = unknown(w, ["session", "pane", "pid", "started"], path);
@@ -4832,7 +4843,7 @@ function validateCarFile(value) {
4832
4843
  const car = isObject2(value.car) ? value.car : void 0;
4833
4844
  if (!car) out.push("sb: car.car must be an object");
4834
4845
  else {
4835
- if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.every((t) => text3(t, 64)))) out.push("sb: car.car.tickets must be a non-empty list of tickets");
4846
+ if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.length <= MAX_CAR_TICKETS && car.tickets.every((t) => text3(t, MAX_TICKET_CHARS)))) out.push(`sb: car.car.tickets must be a list of 1 to ${MAX_CAR_TICKETS} tickets`);
4836
4847
  if (!text3(car.branch, 255)) out.push("sb: car.car.branch must be a non-empty string");
4837
4848
  if (!SHA_RE.test(String(car.head))) out.push("sb: car.car.head must be 40 hex");
4838
4849
  }
@@ -4935,7 +4946,8 @@ function slipsInText(body) {
4935
4946
  return slipBlocks(lines).blocks.flatMap((block) => {
4936
4947
  const parsed = parseSlip(block), f = parsed.fields;
4937
4948
  if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return [];
4938
- return [{ app: f.car, tickets: parsed.tickets.slice(0, 16), branch: f.branch, head: f.head, ...f.coordinator ? { coordinator: f.coordinator } : {} }];
4949
+ 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;
4950
+ return [{ app: f.car, tickets, ...over ? { over } : {}, branch: f.branch, head: f.head, ...f.coordinator ? { coordinator: f.coordinator } : {} }];
4939
4951
  });
4940
4952
  }
4941
4953
  var coordinatorWord = (ticket, coordinator, sender) => `sb: car ${ticket} names coordinator ${coordinator}, but ${sender} sent it; the slip is refused`;
@@ -6630,6 +6642,7 @@ export {
6630
6642
  LockBusy,
6631
6643
  takeLock,
6632
6644
  MAX_SB_BYTES,
6645
+ MAX_TICKET_CHARS,
6633
6646
  SHA_RE,
6634
6647
  isName,
6635
6648
  isObject2 as isObject,
@@ -6654,6 +6667,7 @@ export {
6654
6667
  trainToken,
6655
6668
  trainFromToken,
6656
6669
  trainLabel,
6670
+ isRoleLabel,
6657
6671
  trainFromRequest,
6658
6672
  appFromRequest,
6659
6673
  readMaxTrains,
@@ -86,7 +86,7 @@ import {
86
86
  writeBoard,
87
87
  writeJson,
88
88
  writerAlive
89
- } from "./chunk-ZHT3FG4Q.mjs";
89
+ } from "./chunk-SDNV6G3O.mjs";
90
90
 
91
91
  // src/server/cli.ts
92
92
  import { existsSync as existsSync2, realpathSync as realpathSync2 } from "node:fs";
@@ -17,6 +17,7 @@ import {
17
17
  LAN_PORT,
18
18
  MARK,
19
19
  MAX_SB_BYTES,
20
+ MAX_TICKET_CHARS,
20
21
  POWERSHELL_FLAGS,
21
22
  PROGRESS_OFF,
22
23
  PROTOCOL,
@@ -101,6 +102,7 @@ import {
101
102
  isName,
102
103
  isObject,
103
104
  isOrphan,
105
+ isRoleLabel,
104
106
  isSessionRole,
105
107
  isStandin,
106
108
  isSub,
@@ -206,7 +208,7 @@ import {
206
208
  writeStartError,
207
209
  writerAlive,
208
210
  yardPath
209
- } from "./chunk-ZHT3FG4Q.mjs";
211
+ } from "./chunk-SDNV6G3O.mjs";
210
212
 
211
213
  // src/server/main.ts
212
214
  import { homedir as homedir14 } from "node:os";
@@ -3098,7 +3100,12 @@ async function popBase(d, name2) {
3098
3100
  }
3099
3101
  }
3100
3102
  async function open2(d, name2, file2) {
3101
- const { run: run3 } = d, st = readStash(d.stateDir, name2, file2), all = st.tabs.flatMap((t) => t.panes);
3103
+ const { run: run3 } = d, st = readStash(d.stateDir, name2, file2), refused3 = [];
3104
+ for (const tab of st.tabs) {
3105
+ const alone = tab.label === TOWER_LABEL && tab.panes.filter((p) => p.kind !== "shell").length === 1;
3106
+ tab.panes = tab.panes.map((p) => p.kind !== "tower" || alone ? p : (refused3.push(p.name ?? p.session ?? "a session"), { ...p, kind: "member" }));
3107
+ }
3108
+ const all = st.tabs.flatMap((t) => t.panes);
3102
3109
  const envOf = (kind) => [...roleEnv(kind), ...d.agentDir ? [`PI_CODING_AGENT_DIR=${d.agentDir}`] : []];
3103
3110
  const gone = [.../* @__PURE__ */ new Set([...all.filter((p) => p.session && !existsSync3(p.session)).map((p) => p.session), ...all.map((p) => p.cwd).filter((c) => !statSync5(c, { throwIfNoEntry: false })?.isDirectory())])];
3104
3111
  if (gone.length) throw new Error(`Nothing was opened: ${gone.join(", ")} no longer exist${gone.length > 1 ? "" : "s"}`);
@@ -3119,7 +3126,7 @@ async function open2(d, name2, file2) {
3119
3126
  const starts = tab.panes.map((p, j) => ({ p, pane: ids[j] })).filter(({ p }) => p.kind !== "shell").sort((a, b) => RANK[a.p.kind] - RANK[b.p.kind]);
3120
3127
  for (const { p, pane } of starts) await resume(d, ws, pane, p), sessions++;
3121
3128
  }
3122
- return { workspace: ws, label: st.label, sessions };
3129
+ return { workspace: ws, label: st.label, sessions, ...refused3.length ? { warning: `Straw Boss: the stash names ${refused3.join(", ")} a tower, but not alone in a tower tab, so it came back as a member: a file alone gives no role` } : {} };
3123
3130
  } catch (error) {
3124
3131
  await run3(["workspace", "close", ws]).catch(() => {
3125
3132
  });
@@ -9747,7 +9754,7 @@ function readYards(deps, join_) {
9747
9754
  const carView = (row2, app, nods) => {
9748
9755
  const accepted = (row2.accepted ?? []).slice(0, 8).map((kind) => ((nod) => nod ? { kind: clean6(kind, 32), nod } : { kind: clean6(kind, 32) })(nods?.get(row2.head)?.get(kind)));
9749
9756
  const notice = noticeOf(app, row2.head);
9750
- return { tickets: row2.tickets.slice(0, 16).map((t) => clean6(t, 64)), branch: clean6(row2.branch, 255), head: row2.head, departs: clean6(row2.departs, 300), ...row2.arrived ? { arrived: row2.arrived } : {}, accepted, ...row2.unverified ? { unverified: true } : {}, ...notice ? { notice } : {} };
9757
+ return { tickets: row2.tickets.map((t) => clean6(t, MAX_TICKET_CHARS)), branch: clean6(row2.branch, 255), head: row2.head, departs: clean6(row2.departs, 300), ...row2.arrived ? { arrived: row2.arrived } : {}, accepted, ...row2.unverified ? { unverified: true } : {}, ...notice ? { notice } : {} };
9751
9758
  };
9752
9759
  const trainRow = (read4, fact) => {
9753
9760
  if (!read4.ok) {
@@ -17247,8 +17254,11 @@ var CarBook = class {
17247
17254
  failures = /* @__PURE__ */ new Map();
17248
17255
  chain = Promise.resolve();
17249
17256
  d;
17257
+ /** Since when this book holds forwards: none made before it is here, whatever the disk holds. */
17258
+ since;
17250
17259
  constructor(deps) {
17251
17260
  this.d = deps;
17261
+ this.since = deps.startedAt ?? deps.now();
17252
17262
  }
17253
17263
  // ---- the display journal: written here, read by the yard, never read back (CR-F003)
17254
17264
  writeCar(project, name2, held) {
@@ -17296,6 +17306,14 @@ var CarBook = class {
17296
17306
  trainOf(project, code) {
17297
17307
  return this.trains.get(`${project}/${code}`);
17298
17308
  }
17309
+ /**
17310
+ * What the refusal of a forward this book does not hold adds while a forward made before the server's start would still be kept (todo #154; live, 0.75.0: a slip forwarded 8 minutes before an install restarted the server could be neither received nor
17311
+ * returned, and the refusal named no cause). Nothing is restored: the tower's forward to this server is the fact, so the way back is that forward again. After `KEEP_MS` no earlier forward would count, and nothing is added.
17312
+ */
17313
+ restartWord() {
17314
+ if (this.d.now() - this.since >= KEEP_MS8) return "";
17315
+ return ` The sb server started at ${iso(this.since)} and keeps a tower's forwards in memory only, so a forward made before that is gone with the restart: ask the car's coordinator to send its slip to the tower again (call_tower why=shared); the tower forwards it again, and then the state is set.`;
17316
+ }
17299
17317
  // ---- the registration: defense in depth
17300
17318
  /**
17301
17319
  * Hands the pi process its secret, once. The session must be live, in a pane Herdr knows, and `pid` one of that pane's foreground processes with the start time the server reads for it. A registration whose process still runs in the pane is not replaced
@@ -17420,8 +17438,9 @@ var CarBook = class {
17420
17438
  let file2, name2, held, label;
17421
17439
  if (setter.role === "main") {
17422
17440
  const sent = this.forwardOf(head, setter.session);
17423
- 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)`);
17441
+ 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()}`);
17424
17442
  const slip = sent.slip;
17443
+ if (slip.over) throw refusal3(slip.over);
17425
17444
  name2 = carFileName(slip.app, head);
17426
17445
  held = this.cars.get(project)?.get(name2);
17427
17446
  file2 = held?.file;
@@ -17769,6 +17788,7 @@ function startCars(o) {
17769
17788
  stateDir: o.slot.stateDir,
17770
17789
  dir: o.slot.dir,
17771
17790
  now: o.now,
17791
+ ...o.startedAt !== void 0 ? { startedAt: o.startedAt } : {},
17772
17792
  look: (session) => look2(o, session),
17773
17793
  git: runGit,
17774
17794
  knownHosts: knownHostsOfUser(),
@@ -18767,6 +18787,7 @@ function opener(env) {
18767
18787
  train = found2;
18768
18788
  label = trainLabel(found2.code);
18769
18789
  }
18790
+ if (!train && label !== void 0 && isRoleLabel(label.trim())) throw new OpenLimitError("label is the label of a tower's or a train's tab, which only Straw Boss gives; choose another");
18770
18791
  if (role === INTEGRATOR) {
18771
18792
  if (peer) throw new OpenLimitError("An integrator is opened on a car slip a session of this computer sent, not for a teammate's device");
18772
18793
  if (env.integrationOff?.()) throw new OpenLimitError("No integrator is opened: integration is off on this computer");
@@ -20561,15 +20582,16 @@ var opt2 = (args, name2) => typeof args[name2] === "string" && args[name2] ? arg
20561
20582
  var json = (result2) => ({ text: JSON.stringify(result2, null, 2), details: result2 });
20562
20583
  var NO_HOLDER2 = /* @__PURE__ */ new Set(["no_holder", "no_link"]);
20563
20584
  var namedFor = /* @__PURE__ */ new Map();
20585
+ var restartWord = (host, at) => host.startedAt !== void 0 && at !== void 0 && at < host.startedAt ? ` The sb server started at ${new Date(host.startedAt).toISOString()}, after this slip came in, and keeps the door's answer in memory only: if the door named this slip's integrators before that, its answer is gone with the restart, so ask the door again the same way and forward then.` : "";
20564
20586
  var PEERS_SLIP = (name2, id) => `${clean(name2, 40)} (session ${id}) was opened for a teammate's device, so its slip is a peer's: it reaches the integrator through the ally run of its device, which marks it origin=remote and asks the boss below dispatch, and never through a local run. Forward nothing of it; it sends the slip again to the tower that opened it.`;
20565
20587
  async function forwardOf(host, args, to) {
20566
20588
  const id = opt2(args, "forward");
20567
20589
  if (id === void 0) return void 0;
20568
20590
  const event = host.forwardEvent?.(id);
20569
- if (!event) throw new Error(`forward ${id.slice(0, 40)} is no call_tower event (why=shared) that this run took: forward a car slip with the id its event header shows`);
20591
+ if (!event) throw new Error(`forward ${id.slice(0, 40)} is no call_tower event (why=shared) that this run took: forward a car slip with the id its event header shows. A slip's event is held only while the run that took it lives and for 24 h: ask its sender to send the slip to the tower again (call_tower why=shared) and forward the new event's id`);
20570
20592
  const net = await host.reach.read(), peers = (session) => deviceToken(net, session) !== void 0 || (host.openedAnywhere ?? host.openedFor)?.(session) !== void 0;
20571
20593
  if (peers(event.from)) throw new Error(PEERS_SLIP(event.from, event.from));
20572
- if (to !== void 0 && !namedFor.get(`${host.identity} ${event.id}`)?.includes(to)) throw new Error(`forward ${event.id} goes only to an integrator the door named for this slip: call boss_open_main with role "integrator", the slip as the request, and its sender, and forward to one of the sessions its answer names.`);
20594
+ if (to !== void 0 && !namedFor.get(`${host.identity} ${event.id}`)?.includes(to)) throw new Error(`forward ${event.id} goes only to an integrator the door named for this slip: call boss_open_main with role "integrator", the slip as the request, and its sender, and forward to one of the sessions its answer names.${restartWord(host, event.at)}`);
20573
20595
  if (to !== void 0 && peers(to)) throw new Error(`Session ${to} was opened for a teammate's device, so no slip is forwarded to it. The boss closes it or renames it.`);
20574
20596
  return { fwd: event.id, fwdFrom: event.from, body: bodyOf(event.text) };
20575
20597
  }
@@ -23419,7 +23441,7 @@ function createTowers(o) {
23419
23441
  const pane = ps.find((p) => p.pane_id === record2.pane && p.workspace_id === record2.workspace), workspace = all.find((w) => w.workspace_id === record2.workspace);
23420
23442
  if (!pane || !workspace || isSub(workspace) || record2.tab !== pane.tab_id) continue;
23421
23443
  const glyph = (await tabs(run3, workspace.workspace_id)).some((t) => t.tab_id === pane.tab_id && t.label === TOWER_LABEL);
23422
- if (!glyph && !(typeof record2.file === "string" && pane.agent_session?.value === record2.file)) continue;
23444
+ if (!glyph && !(pane.tokens?.sb_role === "tower" && typeof record2.file === "string" && pane.agent_session?.value === record2.file)) continue;
23423
23445
  if (!services.has(workspace.workspace_id) && !readService(slot, workspace.workspace_id)) {
23424
23446
  const made = { workspace: workspace.workspace_id, label: workspace.label, id: towerId(slot, workspace.workspace_id), name: towerName(slot, workspace.label), pane: pane.pane_id, tab: pane.tab_id, created: new Date(now()).toISOString(), seq: 0 };
23425
23447
  if (!glyph) await run3(["tab", "rename", pane.tab_id, TOWER_LABEL]).catch(() => {
@@ -23761,6 +23783,7 @@ function createTowers(o) {
23761
23783
  who: who2,
23762
23784
  identity: l.record.id,
23763
23785
  requests: l.requests,
23786
+ startedAt: o.startedAt,
23764
23787
  allow: (q) => o.allows ? o.allows.take({ pane: who2.pane, ...q, sessions: () => l.client.listSessions() }) : Promise.resolve({ ok: false, reason: "this server holds no Allows" }),
23765
23788
  allowRequest: (q) => o.allows ? o.allows.takeRequest({ pane: who2.pane, ...q, sessions: () => l.client.listSessions() }) : Promise.resolve({ ok: false, reason: "this server holds no Allows" }),
23766
23789
  asks: o.asks ?? { open: () => {
@@ -23770,7 +23793,7 @@ function createTowers(o) {
23770
23793
  forwardEvent: (id) => {
23771
23794
  const event = readQueue(slot, ws).find((e) => e.id === id && e.taken?.run === who2.id && e.kind === "intercom" && e.from);
23772
23795
  const fields = event && fieldsOf(event.text);
23773
- return event && fields?.kind === "call_tower" && fields.why === "shared" ? { id: event.id, from: event.from.id, text: event.text } : void 0;
23796
+ return event && fields?.kind === "call_tower" && fields.why === "shared" ? { id: event.id, from: event.from.id, text: event.text, at: Date.parse(event.at) } : void 0;
23774
23797
  },
23775
23798
  // A reply that settles a blocked call_tower this run took, while auto mode is on, is listed for the return list with the basis it names (autotower.ts `basisOf`) or `none`.
23776
23799
  decided: (to, gist, basis) => {
@@ -25055,7 +25078,7 @@ async function runServer(o) {
25055
25078
  if (read4.problem !== toldConfig) toldConfig = read4.problem ?? "", read4.problem && recordError("config", read4.problem);
25056
25079
  return read4;
25057
25080
  };
25058
- cars = startCars({ slot, run: cfg.run, now, client: () => client?.isConnected() ? client : void 0, startOf: startOf2, log: (event, facts2) => log.line(event, facts2), stops });
25081
+ cars = startCars({ slot, run: cfg.run, now, startedAt, client: () => client?.isConnected() ? client : void 0, startOf: startOf2, log: (event, facts2) => log.line(event, facts2), stops });
25059
25082
  towers = createTowers({
25060
25083
  ally: allyPort(() => link),
25061
25084
  allows,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.74.0",
3
+ "version": "0.75.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",
package/src/membership.ts CHANGED
@@ -99,6 +99,10 @@ export function createMembership({ pi, cfg, s, me, tell }: Kit, { presence, elec
99
99
  if (s.joined) return;
100
100
  await s.recheck?.(); // a session whose sub workspace check failed (or is still running) asks Herdr again, or shares the ask in flight, before it is refused
101
101
  if (s.barred) throw new Error(s.barred);
102
+ if (s.isTower) throw fatal("This session is the tower of its workspace, not a member of a tab's net"); // the check may have just proven a restored tower (session.ts `towerProof`), and a caller that waited for it joins nothing
103
+ // A session with a sign of a train (trainguard.ts `signsOfTrain`) whose start has not settled the role yet (Herdr did not list its pane or tab) joins nothing early: /boss or a subagent call
104
+ // would publish it as a member, and a promotion would make a train's pane its tab's main. The start's own join comes after it has settled (session.ts `proceed`).
105
+ if (s.trainSign && !s.trainSettled) throw new Error("This session's train role is not settled yet: Herdr has not answered for its pane and tab; it is asked again");
102
106
  s.at = await place(run);
103
107
  connect(true);
104
108
  await connected();
package/src/opener.ts CHANGED
@@ -9,7 +9,7 @@ import { assertSettingsSafe, SettingsRefused } from "./trust/settings.ts";
9
9
  import { inside } from "./link/routing.ts";
10
10
  import { checkoutProject, noTrainRefusal, openRefusal, repoRoot } from "./train/appsconfig.ts";
11
11
  import { slipsInText } from "./train/cars.ts";
12
- import { appFromRequest, readMaxTrains, TRAIN, type TrainId, trainFromRequest, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
12
+ import { appFromRequest, isRoleLabel, readMaxTrains, TRAIN, type TrainId, trainFromRequest, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
13
13
  import { waitPastTrust } from "./trust/wait.ts";
14
14
 
15
15
  // The one thing a tower does besides routing: when no session owns a request, it opens a main for it (docs/how-it-works.md, "Opening a main").
@@ -129,6 +129,8 @@ export function opener(env: OpenerEnv) {
129
129
  train = found;
130
130
  label = trainLabel(found.code);
131
131
  }
132
+ // The label becomes the new tab's, and a tab labelled as a tower's or a train's is what proves that role after a restore (roles.ts): a main's tab is never given one (a train's is its code's, above).
133
+ if (!train && label !== undefined && isRoleLabel(label.trim())) throw new OpenLimitError("label is the label of a tower's or a train's tab, which only Straw Boss gives; choose another");
132
134
  // An integrator is opened on a car slip a session of this computer sent, for the project of the workspace's checkout (read below); its tab and session carry the project's name, which makes the new pi an integrator from its first turn (mainduty.ts).
133
135
  if (role === INTEGRATOR) {
134
136
  if (peer) throw new OpenLimitError("An integrator is opened on a car slip a session of this computer sent, not for a teammate's device");
package/src/roles.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { TOWER_LABEL } from "./herdr.ts";
4
5
  import type { Kit } from "./state.ts";
5
- import { TRAIN, type TrainId, trainFromToken, trainToken } from "./trainrole.ts";
6
+ import { TRAIN, type TrainId, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
6
7
 
7
8
  // What a Herdr restore cannot keep. After `herdr server stop` and a new server, Herdr resumes each pi pane into its session file, but a role lives in
8
9
  // things the restore drops: STRAW_BOSS_ROLE in the pane's environment, the pane and workspace tokens, and, for a session without a conversation yet, the
@@ -16,11 +17,15 @@ import { TRAIN, type TrainId, trainFromToken, trainToken } from "./trainrole.ts"
16
17
  // main, whose record would race the new one at a restore). And a main takes the role back only in a pane whose terminal is not the one it recorded: Herdr starts
17
18
  // a new terminal for a pane it restores, while a `/resume` in the same shell after a /quit finds the old one, and that is no restore. (A tower needs no such
18
19
  // check: it closes its pane when it quits, and its record is dropped then.)
20
+ // A record is a claim, never a proof: the session's own shell can write this folder (and its session file), so a record that says `tower` or `train` gives the
21
+ // role back only in the tab Herdr labels as that role's (the tower glyph, a train's `train <MMDDx>`), which a restore keeps and no file holds. The caller reads the
22
+ // label from Herdr (`Here.tabLabel`). A main has no such tab (its label is its own free name), so its record stands on the checks above
23
+ // (docs/specs/2026-11-07-train-workers.md §29).
19
24
 
20
25
  const KEEP_MS = 90 * 24 * 3600_000;
21
26
  export interface RoleRecord { role: "tower" | "main" | "train"; pane: string; tab: string; workspace: string; terminal?: string; file?: string; openedBy?: string; /** A train's project and code (docs/specs/2026-11-07-train-workers.md §3.3). */ train?: TrainId; at: number }
22
- /** Where a session runs now: the pane, tab, and workspace of the record must all be these. */
23
- export interface Here { paneId?: string; tabId?: string; workspaceId?: string; terminalId?: string }
27
+ /** Where a session runs now: the pane, tab, and workspace of the record must all be these. `tabLabel` is the label Herdr lists for the tab now, the proof of a tower's or a train's tab; left out, neither role is given back. */
28
+ export interface Here { paneId?: string; tabId?: string; workspaceId?: string; terminalId?: string; tabLabel?: string }
24
29
 
25
30
  const keyOf = (file: string) => createHash("sha256").update(file).digest("hex").slice(0, 32);
26
31
 
@@ -65,15 +70,20 @@ export function createRoles({ cfg, s, guiDir, tell }: Kit) {
65
70
  /**
66
71
  * The role this session recorded for the pane, tab, and workspace it is in now; undefined when it recorded none there, or when `here` lacks one of the
67
72
  * three. A main also needs proof of a restart (a terminal other than the one it recorded) and the newest main record of its tab: a tab has one main.
73
+ * A tower and a train need the tab Herdr labels as theirs (`here.tabLabel`): the record alone gives neither role.
68
74
  */
69
75
  held(here: Here): RoleRecord["role"] | undefined {
70
76
  const record = within(here);
71
- if (record?.role === "tower") return "tower";
77
+ if (record?.role === "tower") return here.tabLabel === TOWER_LABEL ? "tower" : undefined;
72
78
  if (!record || !record.terminal || !here.terminalId || record.terminal === here.terminalId) return undefined;
73
- // A train takes its role back on the same proof as a main (a new terminal for the same pane, tab, and workspace); a tab has no "newest train" to check, since no one else is crowned beside it.
74
- if (record.role === TRAIN) return TRAIN;
79
+ // A train takes its role back on the same proof as a main (a new terminal for the same pane, tab, and workspace), in the tab that carries its code; a tab has no "newest train" to check, since no one else is crowned beside it.
80
+ if (record.role === TRAIN) return record.train && here.tabLabel === trainLabel(record.train.code) ? TRAIN : undefined;
75
81
  return mainOf(record.tab, record.workspace)?.at === record.at ? "main" : undefined;
76
82
  },
83
+ /** The role the record names for the pane, tab, and workspace the session is in, proven or not: what tells the start to ask Herdr for the tab's label, and what a refusal names. */
84
+ claimed(here: Here): RoleRecord["role"] | undefined {
85
+ return within(here)?.role;
86
+ },
77
87
  /** Whether the record is a main's from this very terminal: a pi started in the shell that outlived the session, which no restore brought. */
78
88
  sameShell(here: Here): boolean {
79
89
  const record = within(here);
@@ -16,7 +16,8 @@ import { writePrivate } from "../trainboard.ts";
16
16
  // 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
17
17
  // forwarded to the integrator it registered as.
18
18
  // - 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.
19
- // 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.
19
+ // 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
20
+ // 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).
20
21
 
21
22
  const KEEP_MS = 24 * 3600_000, MAX_FORWARDS = 512, MAX_FILES = 256;
22
23
  const BASE_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;
@@ -68,6 +69,8 @@ export interface BookDeps {
68
69
  /** The user's known_hosts as the server read it when it started: each check writes it for ssh to use (RR2-F002). Absent, ssh knows no host and an ssh remote cannot be checked. */
69
70
  knownHosts?: string;
70
71
  now(): number;
72
+ /** 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. */
73
+ startedAt?: number;
71
74
  look(session: string): Promise<Look | undefined>;
72
75
  /** The start time of a process, in the form `register` is given; undefined when it cannot be told. */
73
76
  startOf(pid: number): string | undefined;
@@ -196,8 +199,10 @@ export class CarBook {
196
199
  private readonly failures = new Map<string, number[]>();
197
200
  private chain: Promise<unknown> = Promise.resolve();
198
201
  private readonly d: BookDeps;
202
+ /** Since when this book holds forwards: none made before it is here, whatever the disk holds. */
203
+ private readonly since: number;
199
204
 
200
- constructor(deps: BookDeps) { this.d = deps; }
205
+ constructor(deps: BookDeps) { this.d = deps; this.since = deps.startedAt ?? deps.now(); }
201
206
 
202
207
  // ---- the display journal: written here, read by the yard, never read back (CR-F003)
203
208
 
@@ -238,6 +243,14 @@ export class CarBook {
238
243
  if (t.url && !this.remotes.has(t.project)) this.remotes.set(t.project, t.url);
239
244
  }
240
245
  trainOf(project: string, code: string): TrainRecord | undefined { return this.trains.get(`${project}/${code}`); }
246
+ /**
247
+ * What the refusal of a forward this book does not hold adds while a forward made before the server's start would still be kept (todo #154; live, 0.75.0: a slip forwarded 8 minutes before an install restarted the server could be neither received nor
248
+ * returned, and the refusal named no cause). Nothing is restored: the tower's forward to this server is the fact, so the way back is that forward again. After `KEEP_MS` no earlier forward would count, and nothing is added.
249
+ */
250
+ private restartWord(): string {
251
+ if (this.d.now() - this.since >= KEEP_MS) return "";
252
+ return ` The sb server started at ${iso(this.since)} and keeps a tower's forwards in memory only, so a forward made before that is gone with the restart: ask the car's coordinator to send its slip to the tower again (call_tower why=shared); the tower forwards it again, and then the state is set.`;
253
+ }
241
254
 
242
255
  // ---- the registration: defense in depth
243
256
 
@@ -365,8 +378,9 @@ export class CarBook {
365
378
  if (setter.role === "main") {
366
379
  // 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.
367
380
  const sent = this.forwardOf(head, setter.session);
368
- 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)`);
381
+ 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()}`);
369
382
  const slip = sent.slip;
383
+ if (slip.over) throw refusal(slip.over);
370
384
  name = carFileName(slip.app, head);
371
385
  held = this.cars.get(project)?.get(name);
372
386
  file = held?.file;
@@ -55,6 +55,8 @@ export interface StartCars {
55
55
  slot: Slot;
56
56
  run: HerdrRun;
57
57
  now(): number;
58
+ /** When the server started: the book's refusal of a forward made before it names it (todo #154). */
59
+ startedAt?: number;
58
60
  /** The server's own intercom connection, when it is connected. */
59
61
  client(): IntercomLike | undefined;
60
62
  startOf(pid: number): string | undefined;
@@ -92,7 +94,7 @@ function knownHostsOfUser(): string {
92
94
  export function startCars(o: StartCars): Cars {
93
95
  let notices: CarNotices | undefined;
94
96
  const book = new CarBook({
95
- stateDir: o.slot.stateDir, dir: o.slot.dir, now: o.now, look: (session) => look(o, session), git: runGit, knownHosts: knownHostsOfUser(), exists: existsSync, log: o.log,
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,
96
98
  startOf: o.startOf, onChange: () => notices?.kick(), ...o.over,
97
99
  });
98
100
  notices = new CarNotices({ book, now: o.now, intercom: () => o.client(), tower: (workspace) => towerId(o.slot, workspace), log: o.log });
@@ -613,7 +613,7 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
613
613
  if (read.problem !== toldConfig) (toldConfig = read.problem ?? "", read.problem && recordError("config", read.problem));
614
614
  return read;
615
615
  };
616
- cars = startCars({ slot, run: cfg.run, now, client: () => (client?.isConnected() ? client : undefined), startOf, log: (event, facts) => log.line(event, facts), stops });
616
+ cars = startCars({ slot, run: cfg.run, now, startedAt, client: () => (client?.isConnected() ? client : undefined), startOf, log: (event, facts) => log.line(event, facts), stops });
617
617
  towers = createTowers({
618
618
  ally: allyPort(() => link), allows, asks, cars: cars.book,
619
619
  slot, cfg, env, connect: () => mod.connect(), log, pid, startedAt, enabled: () => towerRuns().enabled, server: serverTools,
@@ -72,7 +72,7 @@ export interface ToolHost {
72
72
  /** Whether an ask of the head tower to this tower's workspace is open (headasks.ts): a tower answers with `tower_send {head: true, inReplyTo}` only to one. */
73
73
  headAsked?(id: string): boolean;
74
74
  /** The `call_tower` event (why=shared) this run took, by its id: the code stamps its sender into a forwarded car slip (docs/specs/2026-11-07-train-workers.md §5.5). Undefined when the run took no such event. */
75
- forwardEvent?(id: string): { id: string; from: string; text: string } | undefined;
75
+ forwardEvent?(id: string): { id: string; from: string; text: string; /** When the event came in. */ at?: number } | undefined;
76
76
  /**
77
77
  * The `call_tower` messages (why=shared) this run took, oldest first, each with the sender the broker named, its own text, and the 16-hex id its forward is stamped with: a local run's events, and for an ally run
78
78
  * what local sessions said to the tower for its device (allyroute.ts). The door of an integrator's open.
@@ -87,6 +87,8 @@ export interface ToolHost {
87
87
  /** `tower_memory` of a local run (towermemory.ts): it proposes, and the boss confirms elsewhere. */
88
88
  memory(args: Record<string, unknown>): Promise<ToolResult>;
89
89
  now(): number;
90
+ /** When this server started: the refusal of a forward whose slip came in before it says what a restart lost (todo #154). */
91
+ startedAt?: number;
90
92
  }
91
93
 
92
94
  export interface SlipEvent { fwd: string; from: { id: string; name?: string }; text: string }
@@ -140,6 +142,11 @@ const ASK = /^[0-9a-f]{32}$/;
140
142
 
141
143
  /** The kept integrators the door named for a slip (`ForwardAsBefore`), by the tower and the slip's event id: a forward of that slip goes to one of them and to no other session. Kept for the server's life; the door is asked again after a restart. */
142
144
  const namedFor = new Map<string, readonly string[]>();
145
+ /**
146
+ * What the refusal of a forward the door did not name adds when the slip came in before this server started (todo #154): a run that outlived a restart holds the slip's event (the queue is on disk) but the door's answer is gone, and it is
147
+ * not read back from anywhere (a file here is one a train can write). The way back is the door again, which is the same call.
148
+ */
149
+ const restartWord = (host: ToolHost, at: number | undefined) => (host.startedAt !== undefined && at !== undefined && at < host.startedAt ? ` The sb server started at ${new Date(host.startedAt).toISOString()}, after this slip came in, and keeps the door's answer in memory only: if the door named this slip's integrators before that, its answer is gone with the restart, so ask the door again the same way and forward then.` : "");
143
150
  const PEERS_SLIP = (name: string, id: string) => `${clean(name, 40)} (session ${id}) was opened for a teammate's device, so its slip is a peer's: it reaches the integrator through the ally run of its device, which marks it origin=remote and asks the boss below dispatch, and never through a local run. Forward nothing of it; it sends the slip again to the tower that opened it.`;
144
151
 
145
152
  /**
@@ -151,10 +158,10 @@ async function forwardOf(host: ToolHost, args: Record<string, unknown>, to?: str
151
158
  const id = opt(args, "forward");
152
159
  if (id === undefined) return undefined;
153
160
  const event = host.forwardEvent?.(id);
154
- if (!event) throw new Error(`forward ${id.slice(0, 40)} is no call_tower event (why=shared) that this run took: forward a car slip with the id its event header shows`);
161
+ if (!event) throw new Error(`forward ${id.slice(0, 40)} is no call_tower event (why=shared) that this run took: forward a car slip with the id its event header shows. A slip's event is held only while the run that took it lives and for 24 h: ask its sender to send the slip to the tower again (call_tower why=shared) and forward the new event's id`);
155
162
  const net = await host.reach.read(), peers = (session: string) => deviceToken(net, session) !== undefined || (host.openedAnywhere ?? host.openedFor)?.(session) !== undefined;
156
163
  if (peers(event.from)) throw new Error(PEERS_SLIP(event.from, event.from));
157
- if (to !== undefined && !namedFor.get(`${host.identity} ${event.id}`)?.includes(to)) throw new Error(`forward ${event.id} goes only to an integrator the door named for this slip: call boss_open_main with role "integrator", the slip as the request, and its sender, and forward to one of the sessions its answer names.`);
164
+ if (to !== undefined && !namedFor.get(`${host.identity} ${event.id}`)?.includes(to)) throw new Error(`forward ${event.id} goes only to an integrator the door named for this slip: call boss_open_main with role "integrator", the slip as the request, and its sender, and forward to one of the sessions its answer names.${restartWord(host, event.at)}`);
158
165
  if (to !== undefined && peers(to)) throw new Error(`Session ${to} was opened for a teammate's device, so no slip is forwarded to it. The boss closes it or renames it.`);
159
166
  return { fwd: event.id, fwdFrom: event.from, body: bodyOf(event.text) };
160
167
  }
@@ -787,11 +787,12 @@ export function createTowers(o: TowersOptions): Towers {
787
787
  if (record?.role !== "tower" || typeof record.pane !== "string" || typeof record.workspace !== "string") continue;
788
788
  const pane = ps.find((p) => p.pane_id === record!.pane && p.workspace_id === record!.workspace), workspace = all.find((w) => w.workspace_id === record!.workspace);
789
789
  // A pane that is not in this Herdr belongs to another one (or to a tab that is gone): the record is left for the server that finds it. Herdr ids are short counters that repeat
790
- // across Herdr servers and `roles/` is shared by them all, so the id alone proves nothing: the pane must also be in the recorded tab, and that tab a tower tab or the pane
791
- // run the record's own session file.
790
+ // across Herdr servers and `roles/` is shared by them all, so the id alone proves nothing: the pane must also be in the recorded tab, and that tab a tower tab, or the pane
791
+ // run the record's own session file as a live tower (its `sb_role=tower` mark). The record and the session file are files the session's own shell can write, so they alone
792
+ // never make a seat: the glyph and the mark are Herdr's (docs/specs/2026-11-07-train-workers.md §29).
792
793
  if (!pane || !workspace || isSub(workspace) || record.tab !== pane.tab_id) continue;
793
794
  const glyph = (await tabs(run, workspace.workspace_id)).some((t) => t.tab_id === pane.tab_id && t.label === TOWER_LABEL);
794
- if (!glyph && !(typeof (record as { file?: unknown }).file === "string" && pane.agent_session?.value === (record as { file?: string }).file)) continue;
795
+ if (!glyph && !(pane.tokens?.sb_role === "tower" && typeof (record as { file?: unknown }).file === "string" && pane.agent_session?.value === (record as { file?: string }).file)) continue;
795
796
  if (!services.has(workspace.workspace_id) && !readService(slot, workspace.workspace_id)) {
796
797
  const made: ServiceRecord = { workspace: workspace.workspace_id, label: workspace.label, id: towerId(slot, workspace.workspace_id), name: towerName(slot, workspace.label), pane: pane.pane_id, tab: pane.tab_id, created: new Date(now()).toISOString(), seq: 0 };
797
798
  // A tab that is the tower's by its session file, not by the glyph, gets the glyph: it is what proves the seat after a Herdr restart (typegate.ts `seatGate`).
@@ -1111,7 +1112,7 @@ export function createTowers(o: TowersOptions): Towers {
1111
1112
  link: async (body: Record<string, unknown>) => ((await o.link?.(body, l.record.id)) ?? { ok: false, code: "no_holder", error: "The link holder is not running in the sb server" }) as { ok: boolean; error?: string },
1112
1113
  server: o.server ?? { status: () => ({}), logs: () => [], restart: () => Promise.reject(new Error("The server cannot restart itself here")) },
1113
1114
  expect: (to: string, name: string, text: string) => { if (peer) return route(to, phrase(name, 40), "expect"); try { addExpect(slot, ws, { to, name, at: now(), first: phrase(text, 80) }, now()); } catch (cause) { error("expects", (cause as Error).message); } },
1114
- who, identity: l.record.id, requests: l.requests,
1115
+ who, identity: l.record.id, requests: l.requests, startedAt: o.startedAt,
1115
1116
  allow: (q: { toolCallId: string; tool: string; args: unknown }) => (o.allows ? o.allows.take({ pane: who.pane, ...q, sessions: () => l.client!.listSessions() }) : Promise.resolve({ ok: false as const, reason: "this server holds no Allows" })),
1116
1117
  allowRequest: (q: { toolCallId: string; lines: string[] }) => (o.allows ? o.allows.takeRequest({ pane: who.pane, ...q, sessions: () => l.client!.listSessions() }) : Promise.resolve({ ok: false as const, reason: "this server holds no Allows" })),
1117
1118
  asks: o.asks ?? { open: () => { throw new Error("this server keeps no asks"); } },
@@ -1119,7 +1120,7 @@ export function createTowers(o: TowersOptions): Towers {
1119
1120
  forwardEvent: (id: string) => {
1120
1121
  const event = readQueue(slot, ws).find((e) => e.id === id && e.taken?.run === who.id && e.kind === "intercom" && e.from);
1121
1122
  const fields = event && fieldsOf(event.text);
1122
- return event && fields?.kind === "call_tower" && fields.why === "shared" ? { id: event.id, from: event.from!.id, text: event.text } : undefined;
1123
+ return event && fields?.kind === "call_tower" && fields.why === "shared" ? { id: event.id, from: event.from!.id, text: event.text, at: Date.parse(event.at) } : undefined;
1123
1124
  },
1124
1125
  // A reply that settles a blocked call_tower this run took, while auto mode is on, is listed for the return list with the basis it names (autotower.ts `basisOf`) or `none`.
1125
1126
  decided: (to: string, gist: string, basis: unknown) => {
@@ -4,7 +4,7 @@ import { dirname, join } from "node:path";
4
4
  import { integrationOff } from "../trainswitch.ts";
5
5
  import { type BoardRead, type BoardStep, type CarRow, factsOf, readJsonFile, type ReadBudget, readTrainboards, readYard, trainboardDir, type Writer, yardPath } from "../train/board.ts";
6
6
  import { carFileName, type CarState, type CarView, noticeStatus } from "../train/cars.ts";
7
- import { isName, isObject, isoTime, SHA_RE } from "../train/spec.ts";
7
+ import { isName, isObject, isoTime, MAX_TICKET_CHARS, SHA_RE } from "../train/spec.ts";
8
8
  import { type FactStep, holding, stepWaits, type TrainFacts, type Wait, waitingTrains } from "../train/waits.ts";
9
9
  import type { NetLoad, ProjectYard, ReasonKind, YardAccepted, YardCar, YardFormingRow, YardJoin, YardNotice, Yards, YardStep, YardTrainRow } from "../train/yardview.ts";
10
10
  import { carsFolderOk, readCar } from "../trainboard.ts";
@@ -157,7 +157,7 @@ export function readYards(deps: YardDeps, join_: YardJoin): Yards | undefined {
157
157
  const carView = (row: CarRow, app: string, nods?: Map<string, Map<string, string>>): YardCar => {
158
158
  const accepted = (row.accepted ?? []).slice(0, 8).map((kind): YardAccepted => ((nod) => (nod ? { kind: clean(kind, 32), nod } : { kind: clean(kind, 32) }))(nods?.get(row.head)?.get(kind)));
159
159
  const notice = noticeOf(app, row.head);
160
- return { tickets: row.tickets.slice(0, 16).map((t) => clean(t, 64)), branch: clean(row.branch, 255), head: row.head, departs: clean(row.departs, 300), ...(row.arrived ? { arrived: row.arrived } : {}), accepted, ...(row.unverified ? { unverified: true as const } : {}), ...(notice ? { notice } : {}) };
160
+ return { tickets: row.tickets.map((t) => clean(t, MAX_TICKET_CHARS)), branch: clean(row.branch, 255), head: row.head, departs: clean(row.departs, 300), ...(row.arrived ? { arrived: row.arrived } : {}), accepted, ...(row.unverified ? { unverified: true as const } : {}), ...(notice ? { notice } : {}) };
161
161
  };
162
162
  const trainRow = (read: BoardRead, fact: TrainFacts): YardTrainRow => {
163
163
  if (!read.ok) {
package/src/session.ts CHANGED
@@ -5,7 +5,7 @@ import type { Briefing } from "./briefing.ts";
5
5
  import type { Control } from "./closemain.ts";
6
6
  import type { Digest } from "./digest.ts";
7
7
  import type { Guard } from "./guard.ts";
8
- import { isHead, isSub, type Place, panes, place, report, waitFor, workspaces } from "./herdr.ts";
8
+ import { isHead, isSub, type Place, panes, place, report, tabs, TOWER_LABEL, waitFor, workspaces } from "./herdr.ts";
9
9
  import type { createHost } from "./host.ts";
10
10
  import type { IntegrationWatch } from "./integration.ts";
11
11
  import { CONNECT_MS, type Membership } from "./membership.ts";
@@ -19,7 +19,7 @@ import type { Presence } from "./presence.ts";
19
19
  import type { Reach } from "./reach.ts";
20
20
  import type { Roles } from "./roles.ts";
21
21
  import { ENTRY, type Kit } from "./state.ts";
22
- import { isSessionRole, TRAIN, TRAIN_EVENT, trainFromToken, trainToken } from "./trainrole.ts";
22
+ import { isSessionRole, TRAIN, TRAIN_EVENT, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
23
23
 
24
24
  /** The custom message that asks the launcher to resume the subagents a Herdr restore brought back plain. */
25
25
  const RESUME = "straw-boss-resume";
@@ -48,13 +48,29 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
48
48
  // A session in a sub workspace (a linked git worktree) acts like a subagent: it never joins. Only a definitive answer bars it for good;
49
49
  // a Herdr that could not answer (it is slow under load) leaves the session unplaced, and the check is asked again (`begin`).
50
50
  let placed: Place | undefined; // where Herdr says this session runs, as the sub workspace check found it
51
- type Verdict = { bar?: { text: string; level: "info" } } | { failed: string };
51
+ type Verdict = { bar?: { text: string; level: "info" } } | { failed: string } | { tower: true };
52
52
  type Once = (what: string, text: string, level: "info" | "warning" | "error") => void;
53
53
  /** `tell`, each `what` once per start: a check that is asked again does not repeat its warning. */
54
54
  const onceOf = (): Once => {
55
55
  const seen = new Set<string>();
56
56
  return (what, text, level) => void (seen.has(what) || (seen.add(what), tell(text, level)));
57
57
  };
58
+ /** The label Herdr lists for the tab now: the proof of a tower's or a train's tab (roles.ts). A list that fails throws, and proves nothing. */
59
+ const labelOf = async (here: Place) => (await tabs(run, here.workspaceId)).find((t) => t.tab_id === here.tabId)?.label;
60
+ const shown = (label: string | undefined) => (label === undefined ? "no tab" : JSON.stringify(Array.from(label).slice(0, 40).join("")));
61
+ // Whether the tower role this session claims is proven. Its saved entry and its role record are files its own shell can write, so they only claim; the proof is Herdr's:
62
+ // the pane sits in a tab labelled with the tower glyph, which a restore keeps and no file holds (docs/specs/2026-11-07-train-workers.md §29), and no other pane of that tab runs an
63
+ // agent: the label proves the tab, not the pane, and a tower that starts beside a live one yields by closing the tab (RP131-F001). No proof is a member, told once.
64
+ const towerProof = async (here: Place, once: Once): Promise<boolean> => {
65
+ const entry = Boolean(s.saved.tower);
66
+ if (!entry && roles.claimed(here) !== "tower") return false;
67
+ const label = await labelOf(here);
68
+ const inTab = (entry && label === TOWER_LABEL) || roles.held({ ...here, tabLabel: label }) === "tower";
69
+ const shared = inTab && (await panes(run, here.workspaceId)).some((p) => p.tab_id === here.tabId && p.pane_id !== here.paneId && (p.agent || p.tokens?.sb_role));
70
+ if (inTab && !shared) return true;
71
+ once("tower-claim", `Straw Boss: this session's ${entry ? "saved entry" : "role record"} says it was a tower, but ${shared ? "its pane shares the tower tab with another agent's pane" : `Herdr lists its pane in ${shown(label)}, not in a tower tab`}, so it starts as a member: a file alone gives no role`, "warning");
72
+ return false;
73
+ };
58
74
  const barReason = async (once: Once): Promise<Verdict> => {
59
75
  try {
60
76
  const here = (placed = await place(run)), { workspaceId } = here;
@@ -62,7 +78,8 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
62
78
  const all = await workspaces(run);
63
79
  const sub = all.find((w) => w.workspace_id === workspaceId);
64
80
  if (sub && isHead(sub)) return { bar: { text: "This is the head tower's workspace, so a session typed here cannot join the net; the head tower is its own", level: "info" } };
65
- return sub && isSub(sub) ? { bar: { text: `${sub.label} is a sub workspace, so this session cannot join the net; the main agent of its parent workspace represents it`, level: "info" } } : {};
81
+ if (sub && isSub(sub)) return { bar: { text: `${sub.label} is a sub workspace, so this session cannot join the net; the main agent of its parent workspace represents it`, level: "info" } };
82
+ return (await towerProof(here, once)) ? { tower: true } : {};
66
83
  } catch (error) {
67
84
  return { failed: (error as Error).message };
68
85
  }
@@ -98,9 +115,8 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
98
115
  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)
99
116
  s.branch = () => ctx.sessionManager.getBranch();
100
117
  s.file = ctx.sessionManager.getSessionFile();
101
- // A Herdr restore resumes the pane into this session file without STRAW_BOSS_ROLE and, when pi had not yet written the file, without its entries: the record decides (roles.ts).
102
- // The pane, tab, and workspace must all be the recorded ones; a tower needs no more, since it closes its pane when it quits (roles.ts).
103
- s.isTower ||= Boolean(s.saved.tower) || roles.held({ paneId: env.HERDR_PANE_ID, tabId: env.HERDR_TAB_ID, workspaceId: env.HERDR_WORKSPACE_ID }) === "tower";
118
+ // A tower here is one by its process: started with STRAW_BOSS_ROLE=tower (state.ts), or a tower already in an earlier start of this process. A Herdr restore resumes the pane into this session
119
+ // file without the variable: the saved entry or the role record then claims the role, and the claim is proven against Herdr with the workspace check below (`towerProof`), never taken from the file.
104
120
  const log = ctx.sessionManager;
105
121
  stopWatching();
106
122
  nudges = orphans({ run, file: () => log.getSessionFile(), entries: () => log.getEntries(), sessions: host.sessions, send: reach.send, type: ENTRY, remember: (key) => pi.appendEntry(ENTRY, { nudged: key }), me, tell });
@@ -108,13 +124,13 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
108
124
  restores = restored({ run, sleep: cfg.sleep, file: () => log.getSessionFile(), entries: () => log.getEntries(), active: () => !s.isTower, launcher: () => (me() ? { id: me(), name: who() } : undefined), sessions: host.sessions, send: reach.send, type: ENTRY, remember: (data) => pi.appendEntry(ENTRY, data), resume: (text, details) => pi.sendMessage({ customType: RESUME, content: text, display: true, details }, { triggerTurn: true, deliverAs: "steer" }), tell });
109
125
  nudgeTimer = setInterval(() => void Promise.allSettled([nudges?.poll(), restores?.poll()]), cfg.nudgeMs).unref();
110
126
  // Starting runs in the background: pi awaits session_start handlers in turn, and pi-intercom connects in its own, after this one.
111
- if (s.isTower) {
127
+ const asTower = () => {
112
128
  s.trainSettled = true; // a tower is no train
113
129
  s.barred = s.recheck = undefined; // what an earlier start of this process left (a member's unplaced check) is not a tower's: it dispatches no subagents, and a bar would let its call through
114
- unwatch = cfg.watch(presence.restore);
130
+ unwatch ??= cfg.watch(presence.restore);
115
131
  startTower().catch((error: Error) => tell(`Straw Boss: ${error.message}`, "error"));
116
- return;
117
- }
132
+ };
133
+ if (s.isTower) return asTower();
118
134
  // Asking Herdr whether this is a sub workspace waits in the background too: on a loaded machine a Herdr call takes seconds, and pi-intercom
119
135
  // connects only after this handler returns. Until the answer comes the session counts as barred: a join waits for the answer first (`s.recheck`, membership.ts), and a promotion needs the join, so nothing joins or promotes early.
120
136
  s.barred = CHECKING;
@@ -138,14 +154,24 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
138
154
  const mine = opensAsTrain ? (await panes(run, placed.workspaceId).catch((error) => { throw Object.assign(error as Error, { joining: true }); })).find((p) => p.pane_id === placed!.paneId) : undefined;
139
155
  const token = trainFromToken(mine?.tokens?.sb_train);
140
156
  const saved = trainFromToken(s.saved.train && trainToken(s.saved.train));
141
- if (mine?.tokens?.sb_open_main === "1" && token) {
142
- [s.isTrain, s.train, s.openedBy, trainHow] = [true, token, mine.tokens.sb_opened_by, "claim"];
143
- } else if (event.reason !== "startup" && saved && s.saved.openedPane === placed.paneId) {
144
- [s.isTrain, s.train, s.openedBy, trainHow] = [true, saved, s.saved.openedBy ?? undefined, "reload"];
145
- } else if (roles.held(placed) === TRAIN) {
157
+ if (mine?.tokens?.sb_open_main === "1" && token) return void ([s.isTrain, s.train, s.openedBy, trainHow] = [true, token, mine.tokens.sb_opened_by, "claim"]);
158
+ // The saved entry and the role record are files the session's own shell can write: they name the train it claims to be, and Herdr proves it, by the tab that carries the train's code
159
+ // (`train <MMDDx>`, set by the open and kept by a restore; docs/specs/2026-11-07-train-workers.md §29). A tab list that fails is no answer, as the pane list above.
160
+ const entry = event.reason !== "startup" && saved && s.saved.openedPane === placed.paneId ? saved : undefined;
161
+ // The label carries the short code only. At a /reload the pane still carries the train's own `sb_train` (presence.ts keeps it over the gap), which says the project and the year:
162
+ // an entry that names another train is not taken (RP131-F003). After a restore, or another start in this process, the token is gone and only the label is left.
163
+ const kept = entry && event.reason === "reload" ? (mine ?? (await panes(run, placed.workspaceId).catch((error) => { throw Object.assign(error as Error, { joining: true }); })).find((p) => p.pane_id === placed!.paneId))?.tokens?.sb_train : undefined;
164
+ const other = entry && event.reason === "reload" && kept !== trainToken(entry);
165
+ const named = entry ?? (roles.claimed(placed) === TRAIN ? roles.trainOf(placed) : undefined);
166
+ if (!named) return;
167
+ const label = await labelOf(placed).catch((error) => { throw Object.assign(error as Error, { joining: true }); });
168
+ if (entry && !other && label === trainLabel(entry.code)) {
169
+ [s.isTrain, s.train, s.openedBy, trainHow] = [true, entry, s.saved.openedBy ?? undefined, "reload"];
170
+ } else if (roles.held({ ...placed, tabLabel: label }) === TRAIN) {
146
171
  const record = roles.trainOf(placed);
147
172
  if (record) [s.isTrain, s.train, s.openedBy, trainHow] = [true, record, roles.openerOf(placed), "restore"];
148
- }
173
+ } else if (label !== trainLabel(named.code)) once("train-claim", `Straw Boss: this session's ${entry ? "saved entry" : "role record"} names ${trainLabel(named.code)}, but Herdr lists its pane in ${shown(label)}, not in that train's tab, so it is no train: a file alone gives no role`, "warning");
174
+ else if (other) once("train-claim", `Straw Boss: this session's saved entry names ${trainToken(entry!)}, but its pane carries ${kept ?? "no train's mark"}, so it is no train: a file alone gives no role`, "warning");
149
175
  };
150
176
  const proceed = async () => {
151
177
  if (!s.stopped && !unwatch) unwatch = cfg.watch(presence.restore); // a shutdown that came while Herdr was asked about the workspace has stopped nothing yet
@@ -224,6 +250,8 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
224
250
  return false;
225
251
  }
226
252
  clearTimeout(retryTimer);
253
+ // The claim is proven: the tower starts now, as one started with the variable does at once. It never joins (membership.ts refuses a tower's join).
254
+ if ("tower" in verdict) return ((s.isTower = true), asTower(), false);
227
255
  s.recheck = undefined;
228
256
  s.barred = verdict.bar?.text;
229
257
  if (verdict.bar) return (tell(verdict.bar.text, verdict.bar.level), (s.trainSettled = true), false); // a session that never joins is no train
package/src/stash.ts CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import type { Reply } from "./control.ts";
5
- import { createTab, type HerdrRun, isHead, isStandin, isSub, type Pane, panes, parentOf, report, result, type Session, type Sleep, startPi, tabs, workspaces } from "./herdr.ts";
5
+ import { createTab, type HerdrRun, isHead, isStandin, isSub, type Pane, panes, parentOf, report, result, type Session, type Sleep, startPi, tabs, TOWER_LABEL, workspaces } from "./herdr.ts";
6
6
  import { isSessionRole } from "./trainrole.ts";
7
7
  import { assertSettingsSafe } from "./trust/settings.ts";
8
8
  import { waitPastTrust } from "./trust/wait.ts";
@@ -250,7 +250,7 @@ async function resume({ run, sleep, live, trustDir }: PopDeps, ws: string, paneI
250
250
  * Opens the stash `name` in a new workspace; on any failure the new workspace closes and the manifest goes back, so popping again starts over.
251
251
  * The manifest is claimed first by moving it into stash/.popping/ (one rename, which only one session wins), so two pops never run one session file twice.
252
252
  */
253
- export async function popBase(d: PopDeps, name: string): Promise<{ workspace: string; label: string; sessions: number }> {
253
+ export async function popBase(d: PopDeps, name: string): Promise<{ workspace: string; label: string; sessions: number; warning?: string }> {
254
254
  if (!nameOk(name)) throw new Error(`"${name}" is not a stash name`);
255
255
  const claimed = join(dirOf(d.stateDir), ".popping", `${name}.json`);
256
256
  mkdirSync(dirname(claimed), { recursive: true, mode: 0o700 });
@@ -273,7 +273,14 @@ export async function popBase(d: PopDeps, name: string): Promise<{ workspace: st
273
273
  }
274
274
  }
275
275
  async function open(d: PopDeps, name: string, file: string) {
276
- const { run } = d, st = readStash(d.stateDir, name, file), all = st.tabs.flatMap((t) => t.panes);
276
+ const { run } = d, st = readStash(d.stateDir, name, file), refused: string[] = [];
277
+ // The manifest is a file a session's shell can write, so the tower it names is a claim, as a role record's is (docs/specs/2026-11-07-train-workers.md §29): a pop starts a tower
278
+ // only where the stash made one, alone in a tab labelled with the tower glyph. Anywhere else the pi comes back a member, told once.
279
+ for (const tab of st.tabs) {
280
+ const alone = tab.label === TOWER_LABEL && tab.panes.filter((p) => p.kind !== "shell").length === 1;
281
+ tab.panes = tab.panes.map((p) => (p.kind !== "tower" || alone ? p : (refused.push(p.name ?? p.session ?? "a session"), { ...p, kind: "member" })));
282
+ }
283
+ const all = st.tabs.flatMap((t) => t.panes);
277
284
  const envOf = (kind: StashPane["kind"]) => [...roleEnv(kind), ...(d.agentDir ? [`PI_CODING_AGENT_DIR=${d.agentDir}`] : [])];
278
285
  const gone = [...new Set([...all.filter((p) => p.session && !existsSync(p.session)).map((p) => p.session!), ...all.map((p) => p.cwd).filter((c) => !statSync(c, { throwIfNoEntry: false })?.isDirectory())])];
279
286
  if (gone.length) throw new Error(`Nothing was opened: ${gone.join(", ")} no longer exist${gone.length > 1 ? "" : "s"}`);
@@ -295,7 +302,7 @@ async function open(d: PopDeps, name: string, file: string) {
295
302
  const starts = tab.panes.map((p, j) => ({ p, pane: ids[j]! })).filter(({ p }) => p.kind !== "shell").sort((a, b) => RANK[a.p.kind] - RANK[b.p.kind]);
296
303
  for (const { p, pane } of starts) (await resume(d, ws, pane, p), sessions++);
297
304
  }
298
- return { workspace: ws, label: st.label, sessions };
305
+ return { workspace: ws, label: st.label, sessions, ...(refused.length ? { warning: `Straw Boss: the stash names ${refused.join(", ")} a tower, but not alone in a tower tab, so it came back as a member: a file alone gives no role` } : {}) };
299
306
  } catch (error) {
300
307
  await run(["workspace", "close", ws]).catch(() => {});
301
308
  throw error;
package/src/stashing.ts CHANGED
@@ -58,6 +58,7 @@ export function createStashing({ cfg, s, guiDir, tell, me }: Kit, { host }: { ho
58
58
  const live = async (id: string) => (await host.sessions()).some((x) => x.id === id);
59
59
  const r = await popBase({ run, sleep, stateDir: guiDir, live, agentDir: cfg.env.PI_CODING_AGENT_DIR, trustDir: trustDir(guiDir) }, name);
60
60
  tell(`Popped "${name}": ${r.sessions} sessions are back in ${r.label}`);
61
+ if (r.warning) tell(r.warning, "warning");
61
62
  },
62
63
  };
63
64
  }
package/src/tools.ts CHANGED
@@ -18,7 +18,7 @@ import type { Kit } from "./state.ts";
18
18
  import { snapshotOfBranch } from "./todo.ts";
19
19
  import { todosOf } from "./items.ts";
20
20
  import { integrationOff } from "./trainswitch.ts";
21
- import { ownsBoard, trainLabel } from "./trainrole.ts";
21
+ import { isRoleLabel, ownsBoard, trainLabel } from "./trainrole.ts";
22
22
  import { trustDir } from "./trust/files.ts";
23
23
 
24
24
  /** The tab label for a name, cut at 16 characters as pi-auto-tab-name cuts it, so that extension takes the label as its own and keeps it. */
@@ -138,6 +138,8 @@ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, p
138
138
  const phrase = name.replace(/\s+/g, " ").trim();
139
139
  if (!phrase) throw new Error("The name is empty");
140
140
  if (Array.from(phrase).length > 40) throw new Error(`The name has ${Array.from(phrase).length} characters; keep it a short phrase (at most 16 fit the tab)`);
141
+ // A main's tab takes the name as its label, and a tab labelled as a tower's or a train's is what proves that role after a restore (roles.ts).
142
+ if (isRoleLabel(tabLabel(phrase))) throw new Error("That name is the label of a tower's or a train's tab, which only Straw Boss gives; choose another");
141
143
  const was = pi.getSessionName() || s.ownName || me().slice(0, 8);
142
144
  const before = s.duty;
143
145
  pi.setSessionName(phrase);
@@ -1,4 +1,4 @@
1
- import { acceptanceToken, acceptanceWord, isObject, isoTime, isName, kb, SHA_RE, spokenText } from "./spec.ts";
1
+ import { acceptanceToken, acceptanceWord, isObject, isoTime, isName, kb, MAX_CAR_TICKETS, MAX_TICKET_CHARS, SHA_RE, spokenText } from "./spec.ts";
2
2
 
3
3
  // What a coordinator hands the train and what `train check --accept` proves about it (docs/specs/2026-11-07-train-workers.md §5.1 to §5.4): the slip's `departs` and `accept` lines, the acceptance evidence file, and
4
4
  // `integration.accept` and `stages` of apps.json. Acceptance happens before loading (D11), so a slip or evidence that asks the train for any is refused at once with `acceptanceWord` (D13). Pure: the files and git come in as functions.
@@ -143,11 +143,21 @@ const namesCheckpoints = (path: string) => base(path).toLowerCase().split(/[^a-z
143
143
 
144
144
  export interface SlipOptions { appAccept: readonly string[] }
145
145
 
146
+ /** The refusals of a slip's ticket list over the bound of a car: too many tickets, or a ticket too long. */
147
+ export function ticketBound(tickets: readonly string[]): string[] {
148
+ const out: string[] = [];
149
+ if (tickets.length > MAX_CAR_TICKETS) out.push(`sb: slip tickets names ${tickets.length} tickets, and a car carries at most ${MAX_CAR_TICKETS}: split the car into two or more slips`);
150
+ const long = tickets.find((t) => t.length > MAX_TICKET_CHARS);
151
+ if (long !== undefined) out.push(`sb: slip ticket ${shown(long)} is longer than ${MAX_TICKET_CHARS} characters: name the ticket by its id`);
152
+ return out;
153
+ }
154
+
146
155
  /** The refusals of the slip itself: how it parses, its head and tickets, `departs`, `accept`, an old `uat:` line, and free text that asks the train for acceptance. */
147
156
  export function checkSlip(slip: string, { appAccept }: SlipOptions): string[] {
148
157
  const { fields, tickets, entries, problems } = parseSlip(slip), out: string[] = [...problems], car = tickets[0] ?? fields.branch ?? "unknown";
149
158
  if (!SHA_RE.test(fields.head ?? "")) out.push("sb: slip head must be 40 hex");
150
159
  if (tickets.length === 0) out.push("sb: slip tickets is empty");
160
+ out.push(...ticketBound(tickets));
151
161
  if (present(fields.uat)) {
152
162
  if (fields.uat!.toLowerCase() === "none") out.push("sb: the slip's uat: line is gone; send accept: <evidence file> | none");
153
163
  else out.push(acceptanceWord({ car, what: `UAT (${fields.uat})`, where: "slip line uat:" }));
@@ -235,7 +245,7 @@ export function checkEvidence(raw: string, o: EvidenceOptions): string[] {
235
245
  else {
236
246
  for (const key of Object.keys(car)) if (present(car[key]) && !["app", "tickets", "branch", "head"].includes(key)) out.push(`sb: evidence.car.${key} is not a field`);
237
247
  if (!(isName(car.app))) out.push("sb: evidence.car.app must be a path-safe name");
238
- if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.every((t) => text(t, 64)))) out.push("sb: evidence.car.tickets must be a non-empty list of tickets");
248
+ if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.length <= MAX_CAR_TICKETS && car.tickets.every((t) => text(t, MAX_TICKET_CHARS)))) out.push(`sb: evidence.car.tickets must be a list of 1 to ${MAX_CAR_TICKETS} tickets`);
239
249
  if (!text(car.branch, 255)) out.push("sb: evidence.car.branch must be a non-empty string");
240
250
  if (!SHA_RE.test(String(car.head))) out.push("sb: evidence.car.head must be 40 hex");
241
251
  else if (o.head !== undefined && car.head !== o.head) out.push("sb: evidence.car.head is not the slip's head");
@@ -1,6 +1,6 @@
1
1
  import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, join } from "node:path";
3
- import { FOLDER_CODE_RE, compareCodes, isCode, isObject, isoTime, jsonBytes, KINDS, MAX_SB_BYTES, type Holds, type Kind, type LoadSpec, isName, SHA_RE, kb } from "./spec.ts";
3
+ import { FOLDER_CODE_RE, compareCodes, MAX_CAR_TICKETS, MAX_TICKET_CHARS, isCode, isObject, isoTime, jsonBytes, KINDS, MAX_SB_BYTES, type Holds, type Kind, type LoadSpec, isName, SHA_RE, kb } from "./spec.ts";
4
4
  import type { Clear, FactStep, StepStatus, TrainFacts, TrainState, Wait } from "./waits.ts";
5
5
 
6
6
  // The trainboard (docs/specs/2026-11-07-train-workers.md §10, §11.1): Straw Boss's derived state, one file per writer. A train's extension writes `<state>/trainboard/<project>/<code>/board.json` from its todo list, the integrator's
@@ -32,7 +32,7 @@ const whole = (value: unknown, min: number, max = Number.MAX_SAFE_INTEGER) => ty
32
32
  const unknown = (value: Record<string, unknown>, allowed: string[], path: string) => Object.keys(value).filter((k) => present(value[k]) && !allowed.includes(k)).map((k) => `sb: ${path}.${k} is not a field`);
33
33
 
34
34
  const CAR_FIELDS = ["tickets", "branch", "head", "coordinator", "departs", "accept", "arrived", "accepted", "unverified"];
35
- const CAP = { session: 128, pane: 64, ticket: 64, tickets: 16, branch: 255, coordinator: 128, departs: 300, accept: 1024, name: 64, kind: 32, reason: 600, by: 128, label: 64 };
35
+ const CAP = { session: 128, pane: 64, ticket: MAX_TICKET_CHARS, tickets: MAX_CAR_TICKETS, branch: 255, coordinator: 128, departs: 300, accept: 1024, name: 64, kind: 32, reason: 600, by: 128, label: 64 };
36
36
 
37
37
  function writerRefusals(w: unknown, path: string): string[] {
38
38
  if (!isObject(w)) return [`sb: ${path} must be an object`];
package/src/train/cars.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { parseSlip, slipBlocks } from "./accept.ts";
2
- import { isCode, isObject, isName, isoTime, SHA_RE, shortCode } from "./spec.ts";
1
+ import { parseSlip, slipBlocks, ticketBound } from "./accept.ts";
2
+ import { isCode, isObject, isName, isoTime, MAX_CAR_TICKETS, MAX_TICKET_CHARS, SHA_RE, shortCode } from "./spec.ts";
3
3
 
4
4
  // A car's states and notices (docs/specs/2026-11-07-train-workers.md §5.5, D14), as data: which states a car has, the fields each carries, the car file they are appended to, the text of each notice, and when a notice counts as told.
5
5
  // The train and the integrator only set a state; the sb server sends the intercom, records the broker's answer, and holds the step that depends on it (task 5a builds the tool and the sender). Pure: nothing here sends or writes.
@@ -96,7 +96,7 @@ export function validateCarFile(value: unknown): string[] {
96
96
  const car = isObject(value.car) ? value.car : undefined;
97
97
  if (!car) out.push("sb: car.car must be an object");
98
98
  else {
99
- if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.every((t) => text(t, 64)))) out.push("sb: car.car.tickets must be a non-empty list of tickets");
99
+ if (!(Array.isArray(car.tickets) && car.tickets.length > 0 && car.tickets.length <= MAX_CAR_TICKETS && car.tickets.every((t) => text(t, MAX_TICKET_CHARS)))) out.push(`sb: car.car.tickets must be a list of 1 to ${MAX_CAR_TICKETS} tickets`);
100
100
  if (!text(car.branch, 255)) out.push("sb: car.car.branch must be a non-empty string");
101
101
  if (!SHA_RE.test(String(car.head))) out.push("sb: car.car.head must be 40 hex");
102
102
  }
@@ -280,7 +280,7 @@ export const forwardsFor = (forwards: readonly Forward[], head: string): Forward
280
280
  export const headsIn = (text: string): string[] => [...new Set([...text.matchAll(/(?:^|[\s|])head:\s*([0-9a-f]{40})(?![0-9a-f])/gim)].map((m) => m[1]!))];
281
281
 
282
282
  /** One slip of a forwarded text, as the server reads it: the car's app, tickets, branch and head, and the coordinator the slip names. */
283
- export interface SlipFacts { app: string; tickets: string[]; branch: string; head: string; coordinator?: string }
283
+ export interface SlipFacts { app: string; tickets: string[]; branch: string; head: string; coordinator?: string; /** The refusal when the slip is over the bound of a car; its tickets are then kept only up to the bound, for the word, and the slip is never received. */ over?: string }
284
284
 
285
285
  /** The slips a forwarded text carries: a `car: <app> | tickets: …` that follows the tower's own words starts a block of its own line. Only a slip that parses and names app, tickets, branch and a 40-hex head is returned. */
286
286
  export function slipsInText(body: string): SlipFacts[] {
@@ -288,7 +288,8 @@ export function slipsInText(body: string): SlipFacts[] {
288
288
  return slipBlocks(lines).blocks.flatMap((block) => {
289
289
  const parsed = parseSlip(block), f = parsed.fields;
290
290
  if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return [];
291
- return [{ app: f.car, tickets: parsed.tickets.slice(0, 16), branch: f.branch, head: f.head!, ...(f.coordinator ? { coordinator: f.coordinator } : {}) }];
291
+ 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;
292
+ return [{ app: f.car, tickets, ...(over ? { over } : {}), branch: f.branch, head: f.head!, ...(f.coordinator ? { coordinator: f.coordinator } : {}) }];
292
293
  });
293
294
  }
294
295
 
package/src/train/spec.ts CHANGED
@@ -7,6 +7,8 @@ export type Kind = (typeof KINDS)[number];
7
7
  export const CHECK_TYPES = ["run", "git", "report", "notice"] as const;
8
8
  export type CheckType = (typeof CHECK_TYPES)[number];
9
9
  export const MAX_SB_BYTES = 8 * 1024;
10
+ /** The most tickets one car carries and the longest ticket: the car's identity, so every place that keeps a car's tickets keeps them whole up to this bound, and a slip over it is refused (the sender splits the car). */
11
+ export const MAX_CAR_TICKETS = 64, MAX_TICKET_CHARS = 64;
10
12
 
11
13
  export const SHA_RE = /^[0-9a-f]{40}$/;
12
14
  export const NAME_RE = /^[A-Za-z0-9._-]{1,64}$/;
package/src/trainguard.ts CHANGED
@@ -88,7 +88,7 @@ export function parseManifest(text: string, read: (path: string) => string | und
88
88
  const word = asked ?? (owed ? `sb: car ${ticket}: ${owed.replace(/^sb: /, "")}` : undefined);
89
89
  const head = /^[0-9a-f]{40}$/.test(parsed.fields.head ?? "") ? parsed.fields.head! : undefined;
90
90
  const shown: Acceptance = config.ok ? acceptanceOf(accept ?? "none", evidence, { appAccept, ...(head ? { head } : {}), exists: check.exists, isAncestor: check.isAncestor }) : { unverified: true };
91
- const f = parsed.fields, row: CarRow = { tickets: parsed.tickets.slice(0, 16), branch: f.branch ?? "", head: head ?? "", coordinator: f.coordinator ?? "", departs: f.departs ?? "next", accept: accept ?? "none", ...shown };
91
+ const f = parsed.fields, row: CarRow = { tickets: parsed.tickets, branch: f.branch ?? "", head: head ?? "", coordinator: f.coordinator ?? "", departs: f.departs ?? "next", accept: accept ?? "none", ...shown };
92
92
  cars.push({ ticket, slip, ...(head ? { head } : {}), ...(evidence ? { evidence } : {}), ...(row.tickets.length && row.branch && row.head && row.coordinator ? { row } : {}) });
93
93
  if (word) leftOut.push({ ticket, head: head ?? "", word });
94
94
  }
package/src/trainrole.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { type HerdrRun, panes } from "./herdr.ts";
3
+ import { HEAD_LABEL, type HerdrRun, panes, TOWER_LABEL } from "./herdr.ts";
4
4
  import { appsFile } from "./train/appsconfig.ts";
5
5
  import { isCode, isName, shortCode } from "./train/spec.ts";
6
6
 
@@ -35,6 +35,12 @@ export function trainFromToken(token: unknown): TrainId | undefined {
35
35
  /** The name of a train's tab and session, set by the open and never changed: `train 1106m`. */
36
36
  export const trainLabel = (code: string): string => `train ${shortCode(code)}`;
37
37
 
38
+ /**
39
+ * Whether a label is one only Straw Boss gives a tab: the tower's and the head tower's glyph, and a train's `train <MMDDx>`. Such a tab is what proves a tower or a train after a restore
40
+ * (roles.ts), so a session's `boss_rename` and a tower's `boss_open_main` never name a tab into one.
41
+ */
42
+ export const isRoleLabel = (label: string): boolean => label === TOWER_LABEL || label === HEAD_LABEL || /^train \d{4}[a-z]{1,2}$/.test(label);
43
+
38
44
  /** The first `project:` and `code:` of the manifest the tower passes verbatim as the open's request (§5.3): `key: value` lines or JSON members, the manifest's own header first. */
39
45
  export function trainFromRequest(request: string): TrainId | { refusal: string } {
40
46
  const find = (key: string) => new RegExp(`(?:^|[{,])[ \\t>*-]*["']?${key}["']?[ \\t]*[:=][ \\t]*["']?([^\\s"',}]+)`, "im").exec(request)?.[1];