pi-straw-boss 0.76.0 → 0.77.2

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.
Files changed (59) hide show
  1. package/README.md +1 -1
  2. package/README.zh-TW.md +1 -4
  3. package/dist/gui/assets/{allyasks-Czxu9N0_.js → allyasks-B157BVSK.js} +1 -1
  4. package/dist/gui/assets/{allyunits-Cu820tRD.js → allyunits-D49tC5yS.js} +1 -1
  5. package/dist/gui/assets/{answer-D3Fc6DBr.js → answer-B_eEaZuu.js} +1 -1
  6. package/dist/gui/assets/{ask-DK8Sf6Pa.js → ask-Cf4u8awy.js} +1 -1
  7. package/dist/gui/assets/{asks-DqkFBBS7.js → asks-BP9fh8zE.js} +1 -1
  8. package/dist/gui/assets/{askview-gHx_Hk2d.js → askview-BzFy3A9l.js} +1 -1
  9. package/dist/gui/assets/{autoback-CZkFJtdj.js → autoback-mQmgZrYL.js} +1 -1
  10. package/dist/gui/assets/{blockschunk-DUknCMor.js → blockschunk-Bcf8T3l_.js} +1 -1
  11. package/dist/gui/assets/{box-BUf9E97Z.js → box-CdTJxlY3.js} +1 -1
  12. package/dist/gui/assets/{chat-CraWb-vz.js → chat-pwXYtfIJ.js} +1 -1
  13. package/dist/gui/assets/{drawer-DyN2PbF3.js → drawer-C4b67hAK.js} +1 -1
  14. package/dist/gui/assets/index-Dvw58cHb.js +4 -0
  15. package/dist/gui/assets/{lanwait-y3ZgXxvk.js → lanwait-D8XQhI49.js} +1 -1
  16. package/dist/gui/assets/{layer-BMeWKQ6w.js → layer-CcPpb9oC.js} +1 -1
  17. package/dist/gui/assets/{lightbox-BtmIeJYB.js → lightbox-cGNtXXLf.js} +1 -1
  18. package/dist/gui/assets/{link-_ku8_F1J.js → link-CfF8WoKX.js} +1 -1
  19. package/dist/gui/assets/{linkdialogs-BHiWLB73.js → linkdialogs-BtrIR5oZ.js} +1 -1
  20. package/dist/gui/assets/{mdbody-DmC2OoJ3.js → mdbody-CM0vyeve.js} +1 -1
  21. package/dist/gui/assets/{pair-6RKgnkV8.js → pair-BdBNEx-I.js} +1 -1
  22. package/dist/gui/assets/{picker-C9mN-2Ml.js → picker-CBlvQLT5.js} +1 -1
  23. package/dist/gui/assets/{server-D8Peiga1.js → server-CSZVUOSr.js} +1 -1
  24. package/dist/gui/assets/{sessionfacts-C-3Lh2Gu.js → sessionfacts-R0PNxQ07.js} +1 -1
  25. package/dist/gui/assets/{settings-C5nXwYtK.js → settings-Bqjz9KP-.js} +1 -1
  26. package/dist/gui/assets/{spawn-DmP1vT7z.js → spawn-DlKByPlr.js} +1 -1
  27. package/dist/gui/assets/{termcard-BWctoI4H.js → termcard-acLQMoog.js} +1 -1
  28. package/dist/gui/assets/{towerturns-Cd9alhqa.js → towerturns-Cldgw4hX.js} +1 -1
  29. package/dist/gui/assets/{trains-GY_I0p6W.js → trains-CY_wPPrG.js} +1 -1
  30. package/dist/gui/assets/{trust-D-_wrdAz.js → trust-DYlVFo7K.js} +1 -1
  31. package/dist/gui/assets/{views-SvadD2NQ.js → views-BxBhtxB1.js} +1 -1
  32. package/dist/gui/assets/{waitcard-Xgi9yQRE.js → waitcard-BF4toG4g.js} +1 -1
  33. package/dist/gui/assets/{yard-C6xyMp5L.js → yard-Bqrbq1yf.js} +1 -1
  34. package/dist/gui/index.html +2 -2
  35. package/dist/gui/themes/raven/{raven-DGx4eH2o.js → raven-Dr7te0ib.js} +2 -2
  36. package/dist/gui/themes/zen/{zen-BQrgqRoA.js → zen-C2J8hYV2.js} +1 -1
  37. package/dist/gui/themes.json +2 -2
  38. package/dist/server/{chunk-7HXSLT4U.mjs → chunk-ENYILM47.mjs} +4 -0
  39. package/dist/server/cli.mjs +1 -1
  40. package/dist/server/main.mjs +208 -42
  41. package/package.json +1 -1
  42. package/prompts/apps-config.md +1 -1
  43. package/prompts/integrator.md +1 -1
  44. package/prompts/main.md +1 -1
  45. package/prompts/planning.md +1 -1
  46. package/prompts/tower-run.md +1 -1
  47. package/prompts/train.md +1 -1
  48. package/src/carwait.ts +105 -0
  49. package/src/index.ts +1 -1
  50. package/src/server/carbook.ts +186 -33
  51. package/src/server/carnotices.ts +14 -8
  52. package/src/server/carops.ts +3 -1
  53. package/src/train/cars.ts +12 -2
  54. package/src/train/contract-legacy.ts +19 -0
  55. package/src/train/contract.ts +51 -0
  56. package/src/traincar.ts +32 -6
  57. package/src/trainguard.ts +11 -12
  58. package/dist/gui/assets/index-LCc1BzpW.js +0 -4
  59. package/src/train/anchorloop.ts +0 -78
package/src/carwait.ts ADDED
@@ -0,0 +1,105 @@
1
+ import { type CarView, livesOf, noticeStatus } from "./train/cars.ts";
2
+
3
+ // The integrator's wait for a `returned` notice (docs/specs/2026-11-07-train-workers.md §5.5; issue #13). A car the integrator returns at receipt has no train, so no todo of anyone waits for its notice: when the sb server stops before the notice is
4
+ // delivered (after a failed first send, or between setting the state and the first send), its book is gone, the journal on disk is not read back (CR-F003), and nobody would tell the coordinator. So the session that returned the car waits itself: it asks
5
+ // the server's book (`cars-read`) until the notice is told, and when the server no longer holds the car it calls the tower `blocked` with the notice text. The wait is this process's memory; nothing is read from disk. A session that ends while it
6
+ // still waits (the tower closes an idle integrator) hands what it waits for to the tower first, since nobody waits after it, and so does a wait the server left undelivered for a day; a process that is killed hands over nothing.
7
+
8
+ const KEEP_MS = 24 * 3600_000, CALL_RETRY_MS = 30_000, CALL_TRIES = 10;
9
+
10
+ /** One returned car whose notice this session waits for: the car, the session that set it, the moment the server set the state (`at`, which names that state among the car's lives), who is told, and the notice line. */
11
+ export interface ReturnWait { session: string; project: string; app: string; head: string; ticket: string; coordinator: string; at: string; line: string; since: number; calls?: number; called?: number }
12
+
13
+ /** Where the waits of this process are kept: on `globalThis`, so a `/reload` (a new module in the same process) goes on waiting; never in a file. */
14
+ const HELD = Symbol.for("pi-straw-boss.cars.returns");
15
+ const heldWaits = (): ReturnWait[] => ((globalThis as { [HELD]?: ReturnWait[] })[HELD] ??= []);
16
+
17
+ export interface ReturnWatchDeps {
18
+ /** This session's id; a wait another session of this process made is left alone. */
19
+ session(): string | undefined;
20
+ /** The cars of a project as the server shows them to this session (`cars-read`); rejects when the server does not answer. */
21
+ read(project: string): Promise<CarView[]>;
22
+ /** One `blocked` call to the tower of this session's workspace, no reply expected; rejects when the tower did not take it. */
23
+ callTower(text: string): Promise<unknown>;
24
+ now(): number;
25
+ /** Where the waits are kept (a test gives its own). */
26
+ waits?: ReturnWait[];
27
+ log?(text: string): void;
28
+ }
29
+
30
+ /** Why a notice is handed to the tower: the server lost it, the session that waited for it ends, or the server did not deliver it in a day. */
31
+ export const WHY = {
32
+ lost: "the sb server restarted and holds neither the car nor its notice",
33
+ ended: "its integrator's session ends while the notice is not delivered yet (the sb server may still deliver it, and nobody else waits for it)",
34
+ stale: "the sb server has not delivered the notice in a day",
35
+ } as const;
36
+ /** What the tower is told of a returned car whose notice nobody can confirm. */
37
+ export const handedWord = (wait: Pick<ReturnWait, "ticket" | "project" | "app" | "coordinator" | "line">, why: string) =>
38
+ `car ${wait.ticket} is returned (${wait.project}/${wait.app}) and sb cannot confirm that its coordinator ${wait.coordinator} was told: ${why}. Tell that coordinator the notice, by its session id, or find its owner. The notice: ${wait.line}`;
39
+
40
+ export function createReturnWatch(d: ReturnWatchDeps) {
41
+ const waits = d.waits ?? heldWaits();
42
+ let running: Promise<void> | undefined;
43
+ const drop = (wait: ReturnWait) => { const i = waits.indexOf(wait); if (i >= 0) waits.splice(i, 1); };
44
+ const mine = () => { const session = d.session(); return waits.filter((w) => w.session === session); };
45
+
46
+ /** Hands a notice to the tower: taken, the wait is over; not taken, it is asked again 30 s later, ten times at most (as the server's sender asks). */
47
+ async function hand(wait: ReturnWait, why: string, now: number): Promise<void> {
48
+ if (wait.called !== undefined && now - wait.called < CALL_RETRY_MS) return;
49
+ wait.called = now;
50
+ wait.calls = (wait.calls ?? 0) + 1;
51
+ try {
52
+ await d.callTower(handedWord(wait, why));
53
+ drop(wait);
54
+ } catch (error) {
55
+ d.log?.(`the tower did not take the call for car ${wait.ticket} (${(error as Error).message.slice(0, 160)})`);
56
+ if (wait.calls >= CALL_TRIES) drop(wait);
57
+ }
58
+ }
59
+
60
+ /** One look at every wait of this session: told or answered by a later state ends it, a car the server no longer holds is handed to the tower, and a server that does not answer is asked again at the next look. */
61
+ function tick(): Promise<void> {
62
+ if (running) return running;
63
+ running = look().finally(() => { running = undefined; });
64
+ return running;
65
+ }
66
+ async function look(): Promise<void> {
67
+ const now = d.now(), views = new Map<string, CarView[] | undefined>();
68
+ for (const wait of mine()) {
69
+ if (!views.has(wait.project)) views.set(wait.project, await d.read(wait.project).catch(() => undefined));
70
+ const cars = views.get(wait.project);
71
+ if (!cars) continue; // the server does not answer (it may be starting): the wait stays, however long
72
+ const lives = livesOf(cars, wait.app, wait.head), life = lives.find((v) => v.file.states.some((s) => s.state === "returned" && s.at === wait.at));
73
+ if (life) {
74
+ // The server holds the state: told (delivered, or the tower was told by the server) ends the wait. While it still sends, the wait goes on, for a day: the server stops sending then, so the tower is handed what it left.
75
+ if (noticeStatus(life.notice, "returned").kind !== "pending") drop(wait);
76
+ else if (now - wait.since > KEEP_MS) await hand(wait, WHY.stale, now);
77
+ continue;
78
+ }
79
+ // The car is in the book with another state: its coordinator sent the slip again after a restart, and that slip's state is the answer it gets.
80
+ if (lives.length) { drop(wait); continue; }
81
+ // The server holds nothing of the car: it started again and the notice went with its book.
82
+ await hand(wait, WHY.lost, now);
83
+ }
84
+ }
85
+
86
+ /** The session ends (not a reload): the look in flight finishes first (so a wait it hands over is not handed twice, car-forward-F005), one last look, then every notice still awaited is handed to the tower, once, and the wait is over either way. */
87
+ async function end(): Promise<void> {
88
+ if (running) await running;
89
+ await tick();
90
+ for (const wait of mine()) {
91
+ drop(wait);
92
+ try { await d.callTower(handedWord(wait, WHY.ended)); } catch (error) { d.log?.(`the tower did not take the call for car ${wait.ticket} (${(error as Error).message.slice(0, 160)})`); }
93
+ }
94
+ }
95
+
96
+ return {
97
+ end,
98
+ /** A car this session just returned: its notice is waited for from now on. */
99
+ add(wait: Omit<ReturnWait, "session" | "since" | "calls" | "called">): void { waits.push({ ...wait, session: d.session() ?? "", since: d.now() }); },
100
+ tick,
101
+ /** How many notices this session still waits for. */
102
+ size: () => mine().length,
103
+ };
104
+ }
105
+ export type ReturnWatch = ReturnType<typeof createReturnWatch>;
package/src/index.ts CHANGED
@@ -87,7 +87,7 @@ export function createStrawBoss({ run: given, world: reading, api = herdrApi(),
87
87
  // The cars' way to the sb server (traincar.ts): the integrator's and the trains' `train_car` tool, added at the join, and the guard's source for notices.
88
88
  const cars = carLink(kit);
89
89
  let trainGuard: TrainGuard | undefined;
90
- const addTrainCar = trainCarTool(kit, () => trainGuard, cars);
90
+ const addTrainCar = trainCarTool(kit, () => trainGuard, cars, (text) => reach.callTower(text, undefined, false, "blocked"));
91
91
  const membership = createMembership(kit, { presence, election, guard, briefing, roles, openTower: reach.openTower, register: () => (tools.addNetTools(), tools.addPromote(), tools.addDuty(), addTrainCar()), onMain: link.look, control: () => control });
92
92
  // `look` (above) starts and upgrades the sb server (src/server/) and is the way to it; a session that is no part of that has none.
93
93
  const tools = createTools(kit, { ...reach, mainDuty, promote: membership.promote, digest, closeMain: (query) => control.closeMain(query), link, server: look, boardFill: createBoardFill(kit) });
@@ -3,7 +3,8 @@ import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, w
3
3
  import { hostname } from "node:os";
4
4
  import { isAbsolute, join, parse } from "node:path";
5
5
  import { carsDir, trainboardDir } from "../train/board.ts";
6
- import { addState, type CarFile, carFileName, type CarState, type CarView, coordinatorWord, emptyCar, headsIn, type NoticeRecord, type Setter, type SlipFacts, slipsInText, type StateEntry, type StateNotice, validateStateFields } from "../train/cars.ts";
6
+ import { readApps } from "../train/appsconfig.ts";
7
+ import { addState, type CarFile, carFileName, type CarState, type CarView, coordinatorWord, emptyCar, endOf, headsIn, landedWord, type NoticeRecord, type Setter, type SlipFacts, slipsInText, type StateEntry, stateLine, type StateNotice, validateStateFields } from "../train/cars.ts";
7
8
  import { isCode, isName, isObject, SHA_RE } from "../train/spec.ts";
8
9
  import { writePrivate } from "../trainboard.ts";
9
10
 
@@ -12,6 +13,9 @@ import { writePrivate } from "../trainboard.ts";
12
13
  // rests on a caller's word. The book holds three kinds of thing:
13
14
  // - Facts the server establishes itself. A car's identity (app, tickets, branch, head, coordinator) is read from the slip the tower forwarded, which the tower's code stamped (the forward record, in memory). `landed` is a commit that git finds on the real
14
15
  // remote branch of the base: its tip read by `ls-remote` with no repository, then fetched into a repository this server makes for that check alone (inspected, then removed) from a URL the server read at the open. The cars a train may touch are the heads of the manifest the server was handed at the open. A notice is told when the broker answered.
16
+ // A car lands once (#15): `received` is refused for a head the same git check finds on the base's remote branch already, which holds after a restart because it rests on nothing the book remembers.
17
+ // - A car's lives (#14). A car ends `returned`, `dropped` or `landed`. A forward of the same head that the tower made after that end is its coordinator sending the slip again, so the integrator's next state starts a new life of the car: a new car file under
18
+ // the same name, with notices of its own. The life before stays in the book under `<name>#<n>` (its notice is still sent, and the train that dropped it still reads it); the journal shows the current life.
15
19
  // - Claims, each limited to the claimer's own train and granting nothing: `dropped` and `returned` of a car on the claimer's train (it only ends that car's ride), the `version` text of `landed`, and the integrator's `train`, `departs` and `reason` text. A
16
20
  // process that claims a role it is not can, at worst, end the rides of the cars of the train it registered as (it must be that train's session by Herdr's pane record and the server's own open), or put those words in the notice of a car the tower
17
21
  // forwarded to the integrator it registered as.
@@ -72,6 +76,8 @@ export interface BookDeps {
72
76
  /** 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
77
  startedAt?: number;
74
78
  look(session: string): Promise<Look | undefined>;
79
+ /** The checkout folder of the Herdr workspace a session runs in (where the open reads a project's remote); left out, or undefined, the session's own folder is used. */
80
+ checkoutOf?(look: Look): Promise<string | undefined>;
75
81
  /** The start time of a process, in the form `register` is given; undefined when it cannot be told. */
76
82
  startOf(pid: number): string | undefined;
77
83
  /** git in a folder, with the folder's own configuration kept out of it (carops.ts `runGit`), and `env` added to the environment the server scrubbed; rejects when git exits non-zero. */
@@ -96,13 +102,28 @@ interface Registration { session: string; pid: number; started: string; pane: st
96
102
  /** What a caller says of a car. For the integrator only the head (and the project) count: the rest is read from the forward, and a claim that differs from it is refused. */
97
103
  export interface CarRef { project?: string; app?: string; head: string; tickets?: string[]; branch?: string; coordinator?: string }
98
104
  export interface SetRequest { secret: unknown; state: CarState; car: CarRef; fields?: Record<string, unknown> }
99
- export interface SetResult { state: CarState; at: string; file: string; coordinator: string }
105
+ /** `notice` is the line the coordinator is sent for the state: the integrator's wait for a `returned` notice hands it to the tower when this server's book is gone before it was delivered (#13). */
106
+ export interface SetResult { state: CarState; at: string; file: string; coordinator: string; notice?: string; /** Set on a `received` the server could not check against the base (the remote of the checkout was not read): why. */ unchecked?: string }
100
107
  interface Held { file: CarFile; notice?: NoticeRecord }
108
+ /** The check at `received` run before the queue (`precheck`): for which car, and why it was not checked when it could not be. */
109
+ interface Checked { head: string; app: string; unchecked?: string }
101
110
 
102
111
  const text = (v: unknown, max: number): v is string => typeof v === "string" && v.trim() !== "" && v.length <= max;
103
112
  const iso = (ms: number) => new Date(ms).toISOString();
104
113
  const noticeName = (name: string) => name.replace(/\.json$/, ".notice.json");
114
+ /** What follows a car file's name in the key of an earlier life (`<name>#<n>`); no file name holds it. */
115
+ const PAST = "#";
116
+ const changedAt = (held: Held) => held.file.states.at(-1)?.at ?? "";
105
117
  const firstLine = (error: unknown) => String((error as { stderr?: unknown }).stderr || (error as Error).message).trim().split("\n")[0]!.slice(0, 200);
118
+ /** Why git could not reach a remote, read from its first line of stderr; undefined for any other failure. Only `received` acts on it (0.77.2). */
119
+ export function reachClass(line: string): "auth" | "connection" | "repository-not-found" | undefined {
120
+ if (/could not read (?:Username|Password)|terminal prompts disabled|Authentication failed|Access denied|Permission denied \(publickey|returned error: 40[13]|Host key verification failed/i.test(line)) return "auth";
121
+ if (/Repository not found|does not appear to be a git repository|returned error: 404|not found/i.test(line)) return "repository-not-found";
122
+ if (/Could not resolve host|Connection refused|Connection timed out|timed out|Failed to connect|Network is unreachable|Could not read from remote repository|unable to access|Connection reset|Connection closed/i.test(line)) return "connection";
123
+ return undefined;
124
+ }
125
+ /** A refusal of a remote git could not reach: `reach` names the class. */
126
+ const unreached = (text: string, line: string) => Object.assign(refusal(text), { reach: reachClass(line) });
106
127
  const same = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((x, i) => x === b[i]);
107
128
  /** git's settings for the mirror: no commit-graph, multi-pack-index, or automatic gc is read or written, so nothing but the objects the fetch hashed itself decides the answer. */
108
129
  const MIRROR_FLAGS = ["-c", "core.commitGraph=false", "-c", "fetch.writeCommitGraph=false", "-c", "gc.auto=0", "-c", "maintenance.auto=false", "-c", "core.multiPackIndex=false"];
@@ -207,6 +228,7 @@ export class CarBook {
207
228
  // ---- the display journal: written here, read by the yard, never read back (CR-F003)
208
229
 
209
230
  private writeCar(project: string, name: string, held: Held) {
231
+ if (name.includes(PAST)) return; // an earlier life of a car: the file of that name shows the life it lives now
210
232
  const dir = carsDir(this.d.stateDir, project), root = trainboardDir(this.d.stateDir);
211
233
  try {
212
234
  writePrivate(join(dir, name), `${JSON.stringify(held.file)}\n`, root);
@@ -283,7 +305,7 @@ export class CarBook {
283
305
  check(secret: unknown): boolean { return typeof secret === "string" && this.regs.has(secret); }
284
306
 
285
307
  /** Who a secret is: the registration, checked against what Herdr and the broker say now. */
286
- private async who(secret: unknown): Promise<{ reg: Registration; setter: Setter; train?: { project: string; code: string } }> {
308
+ private async who(secret: unknown): Promise<{ reg: Registration; setter: Setter; look: Look; train?: { project: string; code: string } }> {
287
309
  const reg = typeof secret === "string" ? this.regs.get(secret) : undefined;
288
310
  if (!reg) throw refusal("sb: this request is not from a registered session: a car state is set from the pi session itself with the train_car tool");
289
311
  const look = await this.d.look(reg.session);
@@ -293,7 +315,7 @@ export class CarBook {
293
315
  if (role === "train" && !look.train) throw refusal(`sb: session ${look.name} is a train with no train token`);
294
316
  // A pane token is Herdr state any process of the user can write: the train is the session this server opened for that code, not the one whose pane says so.
295
317
  if (role === "train" && this.trainOf(look.train!.project, look.train!.code)?.session !== reg.session) throw refusal(`sb: this server did not open train ${look.train!.code} of project ${look.train!.project} for session ${reg.session}`);
296
- return { reg, setter: { role, name: look.name, session: reg.session, ...(look.workspace ? { workspace: look.workspace } : {}) }, ...(look.train ? { train: look.train } : {}) };
318
+ return { reg, setter: { role, name: look.name, session: reg.session, ...(look.workspace ? { workspace: look.workspace } : {}) }, look, ...(look.train ? { train: look.train } : {}) };
297
319
  }
298
320
 
299
321
  // ---- reading
@@ -310,19 +332,28 @@ export class CarBook {
310
332
  return held && held.file.app === app && held.file.car.head === head ? { file: held.file, ...(held.notice ? { notice: held.notice } : {}) } : undefined;
311
333
  }
312
334
  /**
313
- * The cars a registered session may see (`cars-read`): a train sees, in its own project, the cars of its manifest; the integrator sees the cars a tower forwarded to it and the ones it set. The guard asks for nothing else.
335
+ * The cars a registered session may see (`cars-read`): a train sees, in its own project, the cars of its manifest, each in the life it acts on (`lifeFor`); the integrator sees the cars a tower forwarded to it and the ones it set, every life of each,
336
+ * the newest `MAX_FILES` of them. The guard asks for nothing else.
314
337
  */
315
338
  async readFor(req: { secret: unknown; project: unknown }): Promise<CarView[]> {
316
339
  const { setter, train } = await this.who(req.secret);
317
340
  if (!isName(req.project)) throw refusal("sb: cars-read needs a project (a path-safe name)");
318
- const project = req.project;
319
- let visible: (view: CarView) => boolean;
341
+ const project = req.project, view = (h: Held): CarView => ({ file: structuredClone(h.file), ...(h.notice ? { notice: structuredClone(h.notice) } : {}) });
320
342
  if (setter.role === "train") {
321
343
  if (project !== train!.project) throw refusal(`sb: this train works for project ${train!.project}, not ${project}`);
322
- const heads = new Set(this.trainOf(project, train!.code)?.heads ?? []);
323
- visible = (v) => heads.has(v.file.car.head);
324
- } else visible = (v) => v.file.states.some((s) => s.by.session === setter.session) || this.forwardOf(v.file.car.head, setter.session) !== undefined;
325
- return this.read(project).filter(visible);
344
+ return [...new Set(this.trainOf(project, train!.code)?.heads ?? [])].flatMap((head) => { const life = this.lifeFor(project, head, train!.code); return life ? [view(life[1])] : []; });
345
+ }
346
+ const mine = (h: Held) => h.file.states.some((s) => s.by.session === setter.session) || this.forwardOf(h.file.car.head, setter.session) !== undefined;
347
+ return [...(this.cars.get(project)?.values() ?? [])].filter(mine).slice(-MAX_FILES).map(view);
348
+ }
349
+ /**
350
+ * The life of a car (by its head) a train acts on and reads: the newest one the integrator received for this train, else the life the car lives now. A car that was dropped and then sent again rides another train in a new life (#14),
351
+ * and the train that dropped it still reads, and waits for, the state it set.
352
+ */
353
+ private lifeFor(project: string, head: string, code: string): [string, Held] | undefined {
354
+ const lives = [...(this.cars.get(project)?.entries() ?? [])].filter(([, h]) => h.file.car.head === head);
355
+ const newest = (list: typeof lives) => list.reduce<(typeof lives)[number] | undefined>((top, life) => (top && changedAt(top[1]) >= changedAt(life[1]) ? top : life), undefined);
356
+ return newest(lives.filter(([, h]) => h.file.states.some((s) => s.state === "received" && s.train === code))) ?? newest(lives);
326
357
  }
327
358
  /** Every state whose notice is not yet told, oldest first, for the sender. */
328
359
  pending(): { project: string; name: string; file: CarFile; entry: StateEntry; notice?: StateNotice }[] {
@@ -338,30 +369,63 @@ export class CarBook {
338
369
  }
339
370
  return out.sort((a, b) => a.entry.at.localeCompare(b.entry.at));
340
371
  }
341
- /** The notice record of one state of one car file, as it is now. */
342
- noticeOf(project: string, name: string, state: CarState): StateNotice | undefined { return this.cars.get(project)?.get(name)?.notice?.states[state]; }
343
- /** Changes one notice record (the sender is the only caller) and writes it. */
344
- updateNotice(project: string, name: string, state: CarState, change: (record: StateNotice) => void): void {
345
- const held = this.cars.get(project)?.get(name);
346
- if (!held) return;
372
+ /**
373
+ * The life a state entry belongs to, wherever the book keeps it now: a new life of the car moves the one before to `<name>#<n>` (#14), maybe while the sender awaits a send of that earlier life (car-forward-F001). A life's later states keep the entries of its
374
+ * earlier ones (`addState` copies the list, not the entries), so the entry names its life and no other.
375
+ */
376
+ private lifeOf(project: string, name: string, entry: StateEntry): [string, Held] | undefined {
377
+ for (const [key, held] of this.cars.get(project) ?? []) if ((key === name || key.startsWith(`${name}${PAST}`)) && held.file.states.includes(entry)) return [key, held];
378
+ return undefined;
379
+ }
380
+ /** The notice record of one state of the life `entry` was set in, as it is now. */
381
+ noticeOf(project: string, name: string, entry: StateEntry): StateNotice | undefined { return this.lifeOf(project, name, entry)?.[1].notice?.states[entry.state]; }
382
+ /** Changes the notice record of one state of the life `entry` was set in (the sender is the only caller) and writes it. */
383
+ updateNotice(project: string, name: string, entry: StateEntry, change: (record: StateNotice) => void): void {
384
+ const life = this.lifeOf(project, name, entry);
385
+ if (!life) return;
386
+ const [key, held] = life, state = entry.state;
347
387
  const notice: NoticeRecord = held.notice ?? { v: 1, states: {} };
348
388
  const record: StateNotice = notice.states[state] ?? { attempts: [] };
349
389
  change(record);
350
390
  notice.states[state] = record;
351
391
  held.notice = notice;
352
- this.writeCar(project, name, held);
392
+ this.writeCar(project, key, held);
353
393
  }
354
394
 
355
395
  // ---- setting a state
356
396
 
397
+ /**
398
+ * Sets are taken one at a time. The git check at `received` (`unlanded`, a fetch of the base) runs before the request joins that queue, since it reads nothing the book holds: a train's `landed` behind a few receipts is not held up by their fetches
399
+ * (car-forward-F002). Inside the queue the check runs again only when the book changed in between so that the receipt needs it and it was not run.
400
+ */
357
401
  set(req: SetRequest): Promise<SetResult> {
358
- const run = this.chain.then(() => this.setNow(req));
359
- this.chain = run.catch(() => undefined);
402
+ const run = this.precheck(req).then((checked) => {
403
+ const next = this.chain.then(() => this.setNow(req, checked));
404
+ this.chain = next.catch(() => undefined);
405
+ return next;
406
+ });
360
407
  return run;
361
408
  }
409
+ /** The check at `received` of a receipt that would start a car or a life, run outside the queue. Anything other than the check's own refusal is left for `setNow` to say. */
410
+ private async precheck(req: SetRequest): Promise<Checked | undefined> {
411
+ if (req.state !== "received" || !isObject(req.car) || !SHA_RE.test(String(req.car.head))) return undefined;
412
+ const head = String(req.car.head);
413
+ let found: { setter: Setter; look: Look } | undefined;
414
+ try { found = await this.who(req.secret); } catch { return undefined; }
415
+ const project = req.car.project, sent = this.forwardOf(head, found.setter.session);
416
+ if (found.setter.role !== "main" || !isName(project) || !sent || sent.slip.over) return undefined;
417
+ const name = carFileName(sent.slip.app, head);
418
+ if (!this.startsLife(project, name, sent.at)) return undefined;
419
+ return { head, app: sent.slip.app, ...(await this.unlanded(project, sent.slip.app, head, sent.slip.tickets[0] ?? name, found.look)) };
420
+ }
421
+ /** Whether a receipt now would start the car or a new life of it (no car under `name`, or one that ended before the forward). */
422
+ private startsLife(project: string, name: string, sentAt: number): boolean {
423
+ const file = this.cars.get(project)?.get(name)?.file, ended = file ? endOf(file) : undefined;
424
+ return !file || (ended !== undefined && sentAt > Date.parse(ended.at));
425
+ }
362
426
 
363
- private async setNow(req: SetRequest): Promise<SetResult> {
364
- const { setter, train } = await this.who(req.secret);
427
+ private async setNow(req: SetRequest, checked?: Checked): Promise<SetResult> {
428
+ const { setter, train, look } = await this.who(req.secret);
365
429
  const state = req.state, fields = isObject(req.fields) ? { ...req.fields } : {};
366
430
  const bad = validateStateFields(state, fields);
367
431
  if (bad.length) throw refusal(bad.join("; "));
@@ -374,7 +438,7 @@ export class CarBook {
374
438
  if (setter.role === "main" && (state === "dropped" || state === "landed")) throw refusal(`sb: only a train sets ${state}; the integrator sets received and returned`);
375
439
  if (setter.role === "train" && state === "received") throw refusal("sb: only the integrator sets received");
376
440
 
377
- let file: CarFile | undefined, name: string, held: Held | undefined, label: string;
441
+ let file: CarFile | undefined, name: string, held: Held | undefined, label: string, before: Held | undefined, unchecked: string | undefined;
378
442
  if (setter.role === "main") {
379
443
  // 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.
380
444
  const sent = this.forwardOf(head, setter.session);
@@ -388,6 +452,16 @@ export class CarBook {
388
452
  const claims: [string, boolean][] = [["app", car.app === undefined || car.app === slip.app], ["tickets", car.tickets === undefined || same(car.tickets, slip.tickets)], ["branch", car.branch === undefined || car.branch === slip.branch], ["coordinator", car.coordinator === undefined || car.coordinator === slip.coordinator]];
389
453
  const off = claims.find(([, ok]) => !ok);
390
454
  if (off) throw refusal(`sb: car ${label} does not match the forwarded slip: ${off[0]} differs from what the slip the tower forwarded says`);
455
+ // A forward the tower made after the car ended is its coordinator sending the same head again (#14): the car starts a new life, and the state set here is its first. A landed car is not received again in any life (#15); returned, it tells the coordinator so.
456
+ const ended = file ? endOf(file) : undefined;
457
+ if (ended && sent.at > Date.parse(ended.at)) {
458
+ if (ended.state === "landed" && state === "received") throw refusal(landedWord(label, head, `landed in ${String(ended.version).slice(0, 60)}`));
459
+ // A train reads the life received for its own code (`lifeFor`), so a new life does not ride a train an earlier life of the car left.
460
+ const rode = [...(this.cars.get(project)?.entries() ?? [])].some(([key, h]) => (key === name || key.startsWith(`${name}${PAST}`)) && h.file.states.some((s) => s.state === "received" && s.train === fields.train));
461
+ if (state === "received" && rode) throw refusal(`sb: car ${label} rode train ${String(fields.train)} in an earlier life and left it; received names the train it rides now`);
462
+ before = held;
463
+ held = file = undefined;
464
+ }
391
465
  if (file?.states.some((s) => s.state === "received")) throw refusal(`sb: car ${label} is already received${state === "returned" ? "; the integrator returns a car at receipt only" : ""}`);
392
466
  if (!slip.coordinator) throw refusal("sb: the slip names no coordinator");
393
467
  if (slip.coordinator !== sent.from) {
@@ -396,14 +470,16 @@ export class CarBook {
396
470
  // A returned car goes to the session that really sent it, with the word.
397
471
  fields.reason = word;
398
472
  }
473
+ if (state === "received" && !file) unchecked = checked && checked.head === head && checked.app === slip.app ? checked.unchecked : (await this.unlanded(project, slip.app, head, label, look)).unchecked;
399
474
  file ??= emptyCar({ project, app: slip.app, tickets: slip.tickets, branch: slip.branch, head, coordinator: sent.from });
400
475
  } else {
401
476
  // A train's claim, limited to its own train: the car is one of the manifest the server was handed at the open, and the integrator received it.
402
477
  const record = this.trainOf(project, train!.code)!;
403
478
  if (!record.heads.includes(head)) throw refusal(`sb: car with head ${head.slice(0, 12)} is not in the manifest of train ${train!.code}: the server read the cars of the manifest at the open, and a train sets only those`);
404
- held = [...(this.cars.get(project)?.entries() ?? [])].find(([, h]) => h.file.car.head === head)?.[1];
479
+ const life = this.lifeFor(project, head, train!.code);
480
+ held = life?.[1];
405
481
  file = held?.file;
406
- name = file ? carFileName(file.app, head) : head;
482
+ name = life?.[0] ?? head;
407
483
  label = file?.car.tickets[0] ?? head.slice(0, 12);
408
484
  if (!file) throw refusal(`sb: car with head ${head.slice(0, 12)} is not in the book of project ${project}: only a car the integrator received can be set`);
409
485
  const receipt = file.states.find((s) => s.state === "received");
@@ -416,14 +492,23 @@ export class CarBook {
416
492
  }
417
493
  let next: CarFile;
418
494
  try { next = addState(file, { state, fields, by: setter, at: iso(this.d.now()) }); } catch (error) { throw refusal((error as Error).message); }
419
- const entry = next.states.at(-1)!, stored: Held = { file: next, ...(held?.notice ? { notice: held.notice } : {}) };
495
+ // A new life starts with a notice record of its own, written at once so the journal never shows the new file beside the old life's record.
496
+ const entry = next.states.at(-1)!, stored: Held = { file: next, ...(held?.notice ? { notice: held.notice } : before ? { notice: { v: 1, states: {} } } : {}) };
420
497
  const forProject = this.cars.get(project) ?? new Map<string, Held>();
421
- forProject.set(name, stored);
498
+ if (before) {
499
+ // The new life goes last in the book, where a new car would, and the life before right after it under a key of its own: a reader that takes the first entry of a head (a client older than lives, `.find`) gets the life the car lives now (car-forward-F004).
500
+ const past = `${name}${PAST}${[...forProject.keys()].filter((k) => k.startsWith(`${name}${PAST}`)).length + 1}`;
501
+ forProject.delete(name);
502
+ forProject.set(name, stored);
503
+ forProject.set(past, before);
504
+ } else forProject.set(name, stored);
422
505
  this.cars.set(project, forProject);
423
506
  this.writeCar(project, name, stored);
424
507
  this.d.log?.("cars-set", { project, state, car: label.slice(0, 40) });
425
508
  queueMicrotask(() => this.d.onChange?.());
426
- return { state, at: entry.at, file: name, coordinator: next.coordinator };
509
+ let notice: string | undefined;
510
+ try { notice = stateLine(next, entry); } catch { notice = undefined; }
511
+ return { state, at: entry.at, file: name, coordinator: next.coordinator, ...(notice ? { notice } : {}), ...(unchecked ? { unchecked } : {}) };
427
512
  }
428
513
 
429
514
  /**
@@ -456,6 +541,73 @@ export class CarBook {
456
541
  if (!record.url) throw refusal(`sb: the remote of project ${project} was not read when train ${code} opened (the open names none or none that is safe to fetch from, or this server learned of the train after a restart), so ${label}'s commit cannot be checked`);
457
542
  const url = record.url, first = this.remotes.get(project);
458
543
  if (first !== undefined && first !== url) throw refusal(`sb: the remote of project ${project} changed between two opens of this server (${first.slice(0, 120)}, then ${url.slice(0, 120)}); landed is not checked against a remote that moved`);
544
+ await this.withBase({ project, url, base, key: code, state: "landed" }, async (git, tip) => {
545
+ try { await git("merge-base", "--is-ancestor", commit, tip); } catch { throw refusal(`sb: landed.commit ${commit.slice(0, 12)} is not on ${base} of the project's remote: a car has landed only when its commit is on the base's branch there`); }
546
+ });
547
+ }
548
+ /**
549
+ * A car lands once (#15): `received` is refused for a head that git, run here, finds on the base's branch of the project's remote already. Nothing the book remembers is asked, so it holds after a restart, when the book no longer knows that the car landed, and
550
+ * for a head somebody pushed to the base by hand. The remote and the base are read now: the remote of the checkout of the integrator's workspace (where an open reads it) and the app's `integration.base` in that checkout's apps.json. The fetch is the one of
551
+ * `landed`, into a mirror of its own. When the checkout's remote cannot be read nothing is checked (`cars-received-unchecked` is logged, and the integrator's tool says so): an open reads the remote from the same checkout, so a train of such a project has no remote and
552
+ * cannot set `landed` either. When the remote is read but the app names no usable `integration.base`, `received` is refused (car-forward-F003; the boss's rule that a car is never landed twice wins), and so it is when git fails for any reason but reaching the remote. When
553
+ * `ls-remote` or the fetch fails because the remote cannot be reached or authenticated (the server's git has no credential helper, RR3-F002; repository not found counts), the car is received unchecked with that class as the reason (0.77.2). A head that is not in the base's history is the usual car. A car merged by squash or rebase has no head on the base and is not found here.
554
+ */
555
+ private async unlanded(project: string, app: string, head: string, label: string, look: Look): Promise<{ unchecked?: string }> {
556
+ const where = await this.baseOf(look, app);
557
+ if ("unread" in where) {
558
+ this.d.log?.("cars-received-unchecked", { project, car: label.slice(0, 40), reason: "unread" });
559
+ return { unchecked: `the remote of the integrator's workspace checkout could not be read, so whether head ${head.slice(0, 12)} is on the base already was not checked` };
560
+ }
561
+ if ("refused" in where) {
562
+ const word = `sb: car ${label} is not received: ${where.refused}, so whether its head ${head.slice(0, 12)} is on the base already cannot be checked. A car that is on the base is never received again: the boss sets integration.base of app ${app}`;
563
+ this.d.log?.("cars-received-refused", { project, car: label.slice(0, 40), reason: word.slice(0, 200) });
564
+ throw refusal(word);
565
+ }
566
+ const { url, base } = where;
567
+ let on: boolean;
568
+ try {
569
+ on = await this.withBase({ project, url, base, key: "receipt", state: "received" }, async (git, tip) => {
570
+ if (tip === head) return true;
571
+ try { await git("cat-file", "-e", `${head}^{commit}`); } catch { return false; }
572
+ try { await git("merge-base", "--is-ancestor", head, tip); return true; } catch (error) {
573
+ if ((error as { code?: unknown }).code === 1) return false;
574
+ throw refusal(`sb: git could not compare ${head.slice(0, 12)} with the tip of ${base}: ${firstLine(error)}`);
575
+ }
576
+ });
577
+ } catch (error) {
578
+ // The remote could not be reached or would not let the server in (its git has no credential helper, RR3-F002): the boss's 0.77.2 rule receives the car unchecked and says why.
579
+ const reach = (error as { reach?: string }).reach;
580
+ if (reach) {
581
+ this.d.log?.("cars-received-unchecked", { project, car: label.slice(0, 40), reason: reach });
582
+ return { unchecked: `the server could not reach the project's remote (${reach}: ${(error as Error).message.replace(/^sb: /, "").slice(0, 200)}), so whether head ${head.slice(0, 12)} is on ${base} already was not checked` };
583
+ }
584
+ const word = `sb: car ${label} is not received: whether its head ${head.slice(0, 12)} is on ${base} of the project's remote already could not be checked (${(error as Error).message.replace(/^sb: /, "").slice(0, 300)}). A car that is on the base is never received again, so the check has to run: try again`;
585
+ this.d.log?.("cars-received-refused", { project, car: label.slice(0, 40), reason: word.slice(0, 200) });
586
+ throw refusal(word);
587
+ }
588
+ if (on) throw refusal(landedWord(label, head, `is on ${base} of the project's remote already`));
589
+ return {};
590
+ }
591
+ /** Where a car of `app` lands, read now and from nothing the book holds: the remote of the checkout of the session's workspace (its own folder when the workspace has none) and the app's `integration.base` in that checkout's apps.json. `unread` when the remote cannot be read, `refused` (why) when the remote is read and the base is not there or not usable. */
592
+ private async baseOf(look: Look, app: string): Promise<{ url: string; base: string } | { unread: true } | { refused: string }> {
593
+ let checkout: string | undefined;
594
+ try { checkout = await this.d.checkoutOf?.(look); } catch { checkout = undefined; }
595
+ checkout ??= look.cwd;
596
+ const url = await this.remoteOf(checkout);
597
+ if (!checkout || !url) return { unread: true };
598
+ const apps = readApps(checkout), entry = apps.ok ? apps.apps.find((a) => a.name === app) : undefined;
599
+ if (!apps.ok) return { refused: "the apps.json of the integrator's workspace checkout cannot be read" };
600
+ if (!entry) return { refused: `the apps.json of the integrator's workspace checkout names no app ${app}` };
601
+ const base = isObject(entry.integration) ? entry.integration.base : undefined;
602
+ if (typeof base !== "string" || !BASE_RE.test(base) || base.includes("..")) return { refused: `app ${app} names no usable integration.base in the apps.json of the integrator's workspace checkout` };
603
+ return { url, base };
604
+ }
605
+ /**
606
+ * The base's branch of a remote, fetched for one check and removed after it: the steps the comment of `landed` gives, which the check at `received` shares. `answer` gets git in the mirror and the tip `ls-remote` read; the mirror is inspected once more after it
607
+ * answered. `key` names the mirror's one ref, and `state` the state the refusals speak of.
608
+ */
609
+ private async withBase<T>(o: { project: string; url: string; base: string; key: string; state: "landed" | "received" }, answer: (git: (...args: string[]) => Promise<string>, tip: string) => Promise<T>): Promise<T> {
610
+ const { project, url, base, key: code, state } = o;
459
611
  let work: string | undefined, mirror = "", hosts = "";
460
612
  try {
461
613
  mkdirSync(this.d.dir, { recursive: true, mode: 0o700 });
@@ -470,25 +622,26 @@ export class CarBook {
470
622
  }
471
623
  const env = { GIT_SSH_COMMAND: sshCommand(hosts), GIT_ALLOW_PROTOCOL: "https:ssh" };
472
624
  const ref = `refs/heads/${base}`, mine = `refs/sb/base/${code}`;
473
- const tampered = (problems: string[]) => refusal(`sb: the mirror the server made for this check was written to by something else (${problems.slice(0, 4).join(", ")}); landed is not accepted from it. Check again`);
625
+ const tampered = (problems: string[]) => refusal(`sb: the mirror the server made for this check was written to by something else (${problems.slice(0, 4).join(", ")}); ${state} is not accepted from it. Check again`);
474
626
  try {
475
627
  // The tip, from no repository: git reads no repository configuration there.
476
628
  let listed: string;
477
- try { listed = await this.d.git(parse(this.d.dir).root, [...REMOTE_FLAGS, "ls-remote", "--exit-code", "--", url, ref], env); } catch (error) { throw refusal(`sb: git ls-remote of ${base} from the project's remote failed: ${firstLine(error)}`); }
629
+ try { listed = await this.d.git(parse(this.d.dir).root, [...REMOTE_FLAGS, "ls-remote", "--exit-code", "--", url, ref], env); } catch (error) { const line = firstLine(error); throw unreached(`sb: git ls-remote of ${base} from the project's remote failed: ${line}`, line); }
478
630
  const tip = listed.split("\n").map((l) => l.split("\t")).find(([, name]) => name === ref)?.[0];
479
631
  if (!tip || !/^[0-9a-f]{40,64}$/.test(tip)) throw refusal(`sb: the project's remote lists no branch ${base}`);
480
632
  try { await this.d.git(mirror, ["init", "--bare", "-q", "--template=", "."]); } catch (error) { throw refusal(`sb: the server's mirror for project ${project} cannot be made: ${firstLine(error)}`); }
481
633
  const inMirror = (...args: string[]) => this.d.git(mirror, ["--git-dir", mirror, ...MIRROR_FLAGS, ...args], env);
482
634
  const fresh = inspectMirror(mirror, code, "init");
483
635
  if (fresh.problems.length) throw tampered(fresh.problems);
484
- try { await inMirror(...REMOTE_FLAGS, ...FETCH_FLAGS, "fetch", "--no-tags", "--no-recurse-submodules", "--", url, `+${ref}:${mine}`); } catch (error) { throw refusal(`sb: git fetch of ${base} from the project's remote failed: ${firstLine(error)}`); }
636
+ try { await inMirror(...REMOTE_FLAGS, ...FETCH_FLAGS, "fetch", "--no-tags", "--no-recurse-submodules", "--", url, `+${ref}:${mine}`); } catch (error) { const line = firstLine(error); throw unreached(`sb: git fetch of ${base} from the project's remote failed: ${line}`, line); }
485
637
  const fetched = inspectMirror(mirror, code, "fetch", fresh.look);
486
638
  if (fetched.problems.length) throw tampered(fetched.problems);
487
639
  const got = (await inMirror("rev-parse", "--verify", "-q", mine)).trim();
488
- if (got !== tip) throw refusal(`sb: the fetch brought ${got.slice(0, 12)} as the tip of ${base}, but ls-remote read ${tip.slice(0, 12)} (the branch moved between the two, or the fetch was served from another repository); landed is not accepted. Check again`);
489
- try { await inMirror("merge-base", "--is-ancestor", commit, tip); } catch { throw refusal(`sb: landed.commit ${commit.slice(0, 12)} is not on ${base} of the project's remote: a car has landed only when its commit is on the base's branch there`); }
640
+ if (got !== tip) throw refusal(`sb: the fetch brought ${got.slice(0, 12)} as the tip of ${base}, but ls-remote read ${tip.slice(0, 12)} (the branch moved between the two, or the fetch was served from another repository); ${state} is not accepted. Check again`);
641
+ const out = await answer(inMirror, tip);
490
642
  const after = inspectMirror(mirror, code, "check", fetched.look);
491
643
  if (after.problems.length) throw tampered(after.problems);
644
+ return out;
492
645
  } finally { this.dropMirror(work); }
493
646
  }
494
647
  /** Removes the mirror this server made. `rmSync` unlinks a symlink where the folder was, it never follows one out. */
@@ -5,8 +5,8 @@ import { type Attempt, type CarState, RETRY_MS, stateLine, type StateEntry, type
5
5
  import type { CarBook } from "./carbook.ts";
6
6
 
7
7
  // The sb server's sender of car notices (docs/specs/2026-11-07-train-workers.md §5.5, D14): for every car state without a told notice it sends one intercom message to the coordinator's session id under a `car_notice` header, writes what the broker
8
- // answered, tries again at 30 s, 2 min and 5 min, and when the coordinator is not live, or the retries are spent, tells the tower of the setter's workspace once with a `blocked` call. The records are keyed by (car, state), so a state is sent once and a server that
9
- // restarts resumes from them. The sender is driven by `tick()` (a 5 s timer and `kick()` after a state is set); a name is never a target, only the session id the slip named and the tower's forward confirmed.
8
+ // answered, tries again at 30 s, 2 min and 5 min, and when the coordinator is not live, or the retries are spent, tells the tower of the setter's workspace once with a `blocked` call. The records are keyed by (car, state), so a state is sent once while the
9
+ // server runs. The sender is driven by `tick()` (a 5 s timer and `kick()` after a state is set); a name is never a target, only the session id the slip named and the tower's forward confirmed.
10
10
 
11
11
  export const TICK_MS = 5000;
12
12
  const KEEP_MS = 24 * 3600_000, TOWER_RETRY_MS = 30_000, TOWER_TRIES = 10, SEND_TRIES = 1 + RETRY_MS.length;
@@ -27,6 +27,11 @@ export interface NoticeDeps {
27
27
 
28
28
  const iso = (ms: number) => new Date(ms).toISOString();
29
29
  const short = (text: string, n = 160) => text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, n);
30
+ /**
31
+ * The stem of the message ids of one state's notice: the car and the moment the state was set. The broker keeps the ids a sender used for an hour and does not deliver one again, so a state of a car's later life (#14), or one set again after a
32
+ * restart, needs ids the earlier one did not use; the time the state was set tells them apart.
33
+ */
34
+ const idStem = (item: { project: string; file: { app: string; car: { head: string } }; entry: { state: string; at: string } }) => `car-${createHash("sha256").update(`${item.project}/${item.file.app}/${item.file.car.head}/${item.entry.at}`).digest("hex").slice(0, 12)}-${item.entry.state}`;
30
35
 
31
36
  export class CarNotices {
32
37
  private busy = false;
@@ -65,14 +70,15 @@ export class CarNotices {
65
70
  if (record.deliveredAt || now - Date.parse(entry.at) > KEEP_MS) return;
66
71
  const intercom = this.d.intercom();
67
72
  if (!intercom) return;
68
- const key = `${project}/${name}/${state}`, gone = this.away.get(key);
73
+ // Keyed by the state's own life (its id stem names the moment it was set), not by the car's file name, which a new life takes over (car-forward-F001).
74
+ const key = idStem(item), gone = this.away.get(key);
69
75
  if (gone && now < gone.next) return;
70
76
  let live: boolean;
71
77
  try { live = (await intercom.listSessions()).some((s) => s.id === file.coordinator); } catch { return; } // the broker cannot be asked: not the coordinator's absence
72
78
  if (live) this.away.delete(key);
73
79
  else { const wait = gone ? Math.min(gone.wait * 2, MAX_AWAY_MS) : AWAY_MS; this.away.set(key, { next: now + wait, wait }); }
74
80
  const sends = record.attempts.filter((a) => a.outcome !== "not-live");
75
- const change = (fn: (r: StateNotice) => void) => this.d.book.updateNotice(project, name, state, fn);
81
+ const change = (fn: (r: StateNotice) => void) => this.d.book.updateNotice(project, name, entry, fn);
76
82
  if (!live) {
77
83
  // Not live at an attempt: told to the tower once; a coordinator that comes back live later still gets the notice.
78
84
  if (!record.escalatedAt) {
@@ -84,7 +90,7 @@ export class CarNotices {
84
90
  if (sends.length >= SEND_TRIES) { if (!record.escalatedAt) await this.escalate(item, `${sends.length} sends were not delivered`); return; }
85
91
  const due = sends.length === 0 ? now : Date.parse(sends.at(-1)!.at) + RETRY_MS[sends.length - 1]!;
86
92
  if (now < due) return;
87
- const n = sends.length + 1, messageId = `car-${createHash("sha256").update(`${project}/${name}`).digest("hex").slice(0, 12)}-${state}-${n}`;
93
+ const n = sends.length + 1, messageId = `${idStem(item)}-${n}`;
88
94
  const at = iso(now);
89
95
  // The attempt is written before the send: a server that stops in the middle finds an unknown outcome and tries again, never a send nobody wrote down.
90
96
  change((r) => { r.id = messageId; r.attempts.push({ at, outcome: "unknown" }); });
@@ -119,7 +125,7 @@ export class CarNotices {
119
125
 
120
126
  /** One `blocked` call to the tower of the setter's workspace, naming the car, the state, the coordinator and the notice text. It counts once the tower's mailbox has it. */
121
127
  private async escalate(item: ReturnType<CarBook["pending"]>[number], why: string): Promise<void> {
122
- const { project, name, file, entry } = item, state = entry.state, record: StateNotice = this.d.book.noticeOf(project, name, state) ?? { attempts: [] };
128
+ const { project, name, file, entry } = item, state = entry.state, record: StateNotice = this.d.book.noticeOf(project, name, entry) ?? { attempts: [] };
123
129
  if (record.escalatedAt) return;
124
130
  const tries = record.tower ?? [], now = this.d.now();
125
131
  if (tries.length >= TOWER_TRIES) return;
@@ -133,13 +139,13 @@ export class CarNotices {
133
139
  let attempt: Attempt;
134
140
  let taken = false;
135
141
  try {
136
- const result = await intercom.send(to, { text: message, messageId: `car-${createHash("sha256").update(`${project}/${name}`).digest("hex").slice(0, 12)}-${state}-tower-${tries.length + 1}` });
142
+ const result = await intercom.send(to, { text: message, messageId: `${idStem(item)}-tower-${tries.length + 1}` });
137
143
  taken = result.delivered === true;
138
144
  attempt = { at: iso(now), outcome: taken ? "delivered" : "failed", ...(taken ? {} : { answer: short(result.reason ?? "not delivered") }) };
139
145
  } catch (error) {
140
146
  attempt = { at: iso(now), outcome: "failed", answer: short((error as Error).message) };
141
147
  }
142
- this.d.book.updateNotice(project, name, state, (r) => {
148
+ this.d.book.updateNotice(project, name, entry, (r) => {
143
149
  (r.tower ??= []).push(attempt);
144
150
  if (taken) r.escalatedAt = iso(this.d.now());
145
151
  });
@@ -4,7 +4,7 @@ import { homedir } from "node:os";
4
4
  import { join, parse, resolve } from "node:path";
5
5
  import type { IntercomLike } from "./kit.ts";
6
6
  import type { HerdrRun } from "../herdr.ts";
7
- import { panes } from "../herdr.ts";
7
+ import { panes, workspaces } from "../herdr.ts";
8
8
  import { trainFromToken } from "../trainrole.ts";
9
9
  import { CarBook, type Look } from "./carbook.ts";
10
10
  import { CarNotices } from "./carnotices.ts";
@@ -95,6 +95,8 @@ export function startCars(o: StartCars): Cars {
95
95
  let notices: CarNotices | undefined;
96
96
  const book = new CarBook({
97
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,
98
+ // The checkout of the session's workspace, as the tower's open reads it (towers.ts): where the check at `received` finds the project's remote and the app's base.
99
+ checkoutOf: async (seen) => (seen.workspace ? (await workspaces(o.run)).find((w) => w.workspace_id === seen.workspace)?.worktree?.checkout_path : undefined) ?? seen.cwd,
98
100
  startOf: o.startOf, onChange: () => notices?.kick(), ...o.over,
99
101
  });
100
102
  notices = new CarNotices({ book, now: o.now, intercom: () => o.client(), tower: (workspace) => towerId(o.slot, workspace), log: o.log });