pi-straw-boss 0.75.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");
@@ -4492,7 +4502,7 @@ var text2 = (value, max) => typeof value === "string" && value.trim() !== "" &&
4492
4502
  var whole = (value, min, max = Number.MAX_SAFE_INTEGER) => typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
4493
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`);
4494
4504
  var CAR_FIELDS = ["tickets", "branch", "head", "coordinator", "departs", "accept", "arrived", "accepted", "unverified"];
4495
- 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 };
4496
4506
  function writerRefusals(w, path) {
4497
4507
  if (!isObject2(w)) return [`sb: ${path} must be an object`];
4498
4508
  const out = unknown(w, ["session", "pane", "pid", "started"], path);
@@ -4833,7 +4843,7 @@ function validateCarFile(value) {
4833
4843
  const car = isObject2(value.car) ? value.car : void 0;
4834
4844
  if (!car) out.push("sb: car.car must be an object");
4835
4845
  else {
4836
- 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`);
4837
4847
  if (!text3(car.branch, 255)) out.push("sb: car.car.branch must be a non-empty string");
4838
4848
  if (!SHA_RE.test(String(car.head))) out.push("sb: car.car.head must be 40 hex");
4839
4849
  }
@@ -4936,7 +4946,8 @@ function slipsInText(body) {
4936
4946
  return slipBlocks(lines).blocks.flatMap((block) => {
4937
4947
  const parsed = parseSlip(block), f = parsed.fields;
4938
4948
  if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return [];
4939
- 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 } : {} }];
4940
4951
  });
4941
4952
  }
4942
4953
  var coordinatorWord = (ticket, coordinator, sender) => `sb: car ${ticket} names coordinator ${coordinator}, but ${sender} sent it; the slip is refused`;
@@ -6631,6 +6642,7 @@ export {
6631
6642
  LockBusy,
6632
6643
  takeLock,
6633
6644
  MAX_SB_BYTES,
6645
+ MAX_TICKET_CHARS,
6634
6646
  SHA_RE,
6635
6647
  isName,
6636
6648
  isObject2 as isObject,
@@ -86,7 +86,7 @@ import {
86
86
  writeBoard,
87
87
  writeJson,
88
88
  writerAlive
89
- } from "./chunk-4OLRDO5C.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,
@@ -207,7 +208,7 @@ import {
207
208
  writeStartError,
208
209
  writerAlive,
209
210
  yardPath
210
- } from "./chunk-4OLRDO5C.mjs";
211
+ } from "./chunk-SDNV6G3O.mjs";
211
212
 
212
213
  // src/server/main.ts
213
214
  import { homedir as homedir14 } from "node:os";
@@ -9753,7 +9754,7 @@ function readYards(deps, join_) {
9753
9754
  const carView = (row2, app, nods) => {
9754
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)));
9755
9756
  const notice = noticeOf(app, row2.head);
9756
- 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 } : {} };
9757
9758
  };
9758
9759
  const trainRow = (read4, fact) => {
9759
9760
  if (!read4.ok) {
@@ -17253,8 +17254,11 @@ var CarBook = class {
17253
17254
  failures = /* @__PURE__ */ new Map();
17254
17255
  chain = Promise.resolve();
17255
17256
  d;
17257
+ /** Since when this book holds forwards: none made before it is here, whatever the disk holds. */
17258
+ since;
17256
17259
  constructor(deps) {
17257
17260
  this.d = deps;
17261
+ this.since = deps.startedAt ?? deps.now();
17258
17262
  }
17259
17263
  // ---- the display journal: written here, read by the yard, never read back (CR-F003)
17260
17264
  writeCar(project, name2, held) {
@@ -17302,6 +17306,14 @@ var CarBook = class {
17302
17306
  trainOf(project, code) {
17303
17307
  return this.trains.get(`${project}/${code}`);
17304
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
+ }
17305
17317
  // ---- the registration: defense in depth
17306
17318
  /**
17307
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
@@ -17426,8 +17438,9 @@ var CarBook = class {
17426
17438
  let file2, name2, held, label;
17427
17439
  if (setter.role === "main") {
17428
17440
  const sent = this.forwardOf(head, setter.session);
17429
- 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()}`);
17430
17442
  const slip = sent.slip;
17443
+ if (slip.over) throw refusal3(slip.over);
17431
17444
  name2 = carFileName(slip.app, head);
17432
17445
  held = this.cars.get(project)?.get(name2);
17433
17446
  file2 = held?.file;
@@ -17775,6 +17788,7 @@ function startCars(o) {
17775
17788
  stateDir: o.slot.stateDir,
17776
17789
  dir: o.slot.dir,
17777
17790
  now: o.now,
17791
+ ...o.startedAt !== void 0 ? { startedAt: o.startedAt } : {},
17778
17792
  look: (session) => look2(o, session),
17779
17793
  git: runGit,
17780
17794
  knownHosts: knownHostsOfUser(),
@@ -20568,15 +20582,16 @@ var opt2 = (args, name2) => typeof args[name2] === "string" && args[name2] ? arg
20568
20582
  var json = (result2) => ({ text: JSON.stringify(result2, null, 2), details: result2 });
20569
20583
  var NO_HOLDER2 = /* @__PURE__ */ new Set(["no_holder", "no_link"]);
20570
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.` : "";
20571
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.`;
20572
20587
  async function forwardOf(host, args, to) {
20573
20588
  const id = opt2(args, "forward");
20574
20589
  if (id === void 0) return void 0;
20575
20590
  const event = host.forwardEvent?.(id);
20576
- 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`);
20577
20592
  const net = await host.reach.read(), peers = (session) => deviceToken(net, session) !== void 0 || (host.openedAnywhere ?? host.openedFor)?.(session) !== void 0;
20578
20593
  if (peers(event.from)) throw new Error(PEERS_SLIP(event.from, event.from));
20579
- 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)}`);
20580
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.`);
20581
20596
  return { fwd: event.id, fwdFrom: event.from, body: bodyOf(event.text) };
20582
20597
  }
@@ -23768,6 +23783,7 @@ function createTowers(o) {
23768
23783
  who: who2,
23769
23784
  identity: l.record.id,
23770
23785
  requests: l.requests,
23786
+ startedAt: o.startedAt,
23771
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" }),
23772
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" }),
23773
23789
  asks: o.asks ?? { open: () => {
@@ -23777,7 +23793,7 @@ function createTowers(o) {
23777
23793
  forwardEvent: (id) => {
23778
23794
  const event = readQueue(slot, ws).find((e) => e.id === id && e.taken?.run === who2.id && e.kind === "intercom" && e.from);
23779
23795
  const fields = event && fieldsOf(event.text);
23780
- 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;
23781
23797
  },
23782
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`.
23783
23799
  decided: (to, gist, basis) => {
@@ -25062,7 +25078,7 @@ async function runServer(o) {
25062
25078
  if (read4.problem !== toldConfig) toldConfig = read4.problem ?? "", read4.problem && recordError("config", read4.problem);
25063
25079
  return read4;
25064
25080
  };
25065
- 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 });
25066
25082
  towers = createTowers({
25067
25083
  ally: allyPort(() => link),
25068
25084
  allows,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.75.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",
@@ -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
  }
@@ -1112,7 +1112,7 @@ export function createTowers(o: TowersOptions): Towers {
1112
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 },
1113
1113
  server: o.server ?? { status: () => ({}), logs: () => [], restart: () => Promise.reject(new Error("The server cannot restart itself here")) },
1114
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); } },
1115
- who, identity: l.record.id, requests: l.requests,
1115
+ who, identity: l.record.id, requests: l.requests, startedAt: o.startedAt,
1116
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" })),
1117
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" })),
1118
1118
  asks: o.asks ?? { open: () => { throw new Error("this server keeps no asks"); } },
@@ -1120,7 +1120,7 @@ export function createTowers(o: TowersOptions): Towers {
1120
1120
  forwardEvent: (id: string) => {
1121
1121
  const event = readQueue(slot, ws).find((e) => e.id === id && e.taken?.run === who.id && e.kind === "intercom" && e.from);
1122
1122
  const fields = event && fieldsOf(event.text);
1123
- 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;
1124
1124
  },
1125
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`.
1126
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) {
@@ -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
  }