pi-straw-boss 0.77.2 → 0.78.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.
@@ -3,6 +3,7 @@ import type { IntercomLike } from "./kit.ts";
3
3
  import type { Session } from "../herdr.ts";
4
4
  import { isHead, isSub, type HerdrRun, workspaces } from "../herdr.ts";
5
5
  import { type Incoming } from "./kit.ts";
6
+ import { WATCH_BRIEF } from "./autowatch.ts";
6
7
  import { answerAsk, asked, openAsks } from "./headasks.ts";
7
8
  import type { Locale } from "../towerprompt/messages.ts";
8
9
  import { buildHeadBrief, headTools, type HeadWorkspace } from "./headbrief.ts";
@@ -105,7 +106,7 @@ export async function headBrief(d: HeadBriefDeps, input: { woken: number; run: R
105
106
  expired: section.expired,
106
107
  text: buildHeadBrief({
107
108
  identity: d.record().id, woken: `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`, boss: Boolean(input.run.conversation), chapter,
108
- workspaces: rows, ...(d.auto?.() ? { auto: d.auto()! } : {}),
109
+ workspaces: rows, ...(d.auto?.() ? { auto: `${d.auto()!}\n${WATCH_BRIEF}` } : {}),
109
110
  asks: openAsks(d.slot, d.now()).map((a) => ({ id: a.id, label: phrase(a.label, 60), age: ageOf(d.now() - a.at), first: a.first, ...(a.answers.at(-1) ? { answer: a.answers.at(-1)!.first } : {}) })),
110
111
  memory: section.text, lapsed: kept.memory.entries.filter((e) => e.for === "boss" && lapsed(e, d.now())).map((e) => e.id), ...(note ? { note: { text: note.note, age: ageOf(d.now() - Date.parse(note.at)) } } : {}), tools: headTools(d.locale), flags: [],
111
112
  }),
@@ -30,6 +30,7 @@ import { createLog, tailLog } from "./log.ts";
30
30
  import { type Cars, carsReply, startCars } from "./carops.ts";
31
31
  import { procsReply, startProcs, type StartProcs } from "./procsops.ts";
32
32
  import { startStall, type StartStall } from "./stallops.ts";
33
+ import { reportWatch, startAutoWatch, type StartWatch } from "./watchops.ts";
33
34
  import { gateRun, type RunInfo } from "./rungate.ts";
34
35
  import type { ServerTools } from "./runtools.ts";
35
36
  import {
@@ -115,6 +116,8 @@ export interface ServerOptions {
115
116
  procs?: StartProcs["over"];
116
117
  /** The stall watch's seams (stallops.ts), for tests: without them a test run has no watch. */
117
118
  stall?: StartStall["over"];
119
+ /** The auto watch's seams (watchops.ts), for tests: without them a test run has no watch. */
120
+ autoWatch?: StartWatch["over"];
118
121
  touchMs?: number;
119
122
  brokerMs?: number;
120
123
  herdrGoneMs?: number;
@@ -178,7 +181,7 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
178
181
  let link: LinkService | undefined, linkFirst: Promise<void> | undefined;
179
182
  let procs: ReturnType<typeof startProcs> | undefined; // the owner registry (procsops.ts), assigned before the first request is taken
180
183
  // Auto mode (docs/specs/2026-11-09-auto-mode.md): the primary server alone writes `auto.json` at the state root, so every Herdr slot of this computer reads one file; the head's notices go through the tower service once it exists.
181
- const auto = slot.primary ? createAutoMode({ dir: slot.stateDir, now, log: (event, facts) => log.line(event, facts), parked: () => towers?.parked() ?? [], unpark: () => towers?.unpark(), tellHead: (text) => { const workspace = towers?.head.status()?.workspace; if (workspace) towers!.runs.notice(workspace, text, `auto:${now()}`); } }) : undefined;
184
+ const auto = slot.primary ? createAutoMode({ dir: slot.stateDir, now, log: (event, facts) => log.line(event, facts), parked: () => towers?.parked() ?? [], unpark: () => towers?.unpark(), watch: reportWatch(slot, now, () => towers), tellHead: (text) => { const workspace = towers?.head.status()?.workspace; if (workspace) towers!.runs.notice(workspace, text, `auto:${now()}`); } }) : undefined;
182
185
  // A secondary slot follows the primary's files and forwards its asks (autofollow.ts, AMC-F002).
183
186
  const follower = slot.primary ? undefined : createAutoFollower({ dir: slot.stateDir, primary: { ...slot, primary: true, dir: slot.stateDir }, log: (event, facts) => log.line(event, facts), unpark: () => towers?.unpark(), tellHead: (text) => { const workspace = towers?.head.status()?.workspace; if (workspace) towers!.runs.notice(workspace, text, `auto:${now()}`); } });
184
187
  // An unattended device has no boss at it (autoops.ts): the link holder says which this computer is.
@@ -632,6 +635,8 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
632
635
  }, () => (log.line("herdr-lost", { at: Date.now() }), towers?.runs.herdrLost())));
633
636
  // The stall watch (stallwatch.ts): a pi that froze is told to its workspace's tower from the registry's tick; it signals nothing.
634
637
  const stall = startStall({ dir: slot.dir, stateDir: slot.stateDir, pid, platform, now, log: (event, facts) => log.line(event, facts), run: cfg.run, sessions: () => (client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected"))), towers: () => towers, ...(o.stall ? { over: o.stall } : {}) });
638
+ // The auto watch (autowatch.ts): while auto mode is on, the head tower is woken about every 15 minutes with what the server's own state shows of each workspace; the primary server's, as auto mode is.
639
+ if (auto) ((stop) => stop && stops.push(stop))(startAutoWatch({ auto, slot, env, now, log: (event, facts) => log.line(event, facts), run: cfg.run, world: cfg.world, sessions: () => (client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected"))), towers: () => towers, stalls: () => stall?.list() ?? [], book: () => cars?.book, ...(o.autoWatch ? { over: o.autoWatch } : {}) }));
635
640
  procs = startProcs({ dir: slot.dir, stateDir: slot.stateDir, env, pid, platform, now, log: (event, facts) => log.line(event, facts), run: cfg.run, events: cfg.events, ...(stall ? { watch: (table) => stall.sample(table) } : {}), ...(o.procs ? { over: o.procs } : {}), stops, timers, leaving: () => Boolean(leaving) || phase === "stopping" || phase === "restarting" });
636
641
  let downSince: number | undefined;
637
642
  const herdrUp = o.herdrUp ?? (() => herdrListens({ slot, platform }));
@@ -20,8 +20,9 @@ import type { Log } from "./log.ts";
20
20
  import { noteEvent } from "./headasks.ts";
21
21
  import type { Slot } from "./record.ts";
22
22
  import { addNote, clearTimer, listRuns, pruneRuns, readNotes, readTimer, type Outcome, type RunRecord, writeRun, writeTimer } from "./towerrunstore.ts";
23
- import { appendEvent, dropParked, parkEvent, type QueuedEvent, readQueue, removeEvent, type ServiceRecord, unparkEvent, updateEvent } from "./towerstore.ts";
23
+ import { addTold, appendEvent, dropParked, HEAD_KEY, parkEvent, type QueuedEvent, readQueue, readTold, removeEvent, type ServiceRecord, unparkEvent, updateEvent } from "./towerstore.ts";
24
24
  import { RUN_CAP_MINUTES } from "./towerbrief.ts";
25
+ import { WATCH_KEY } from "./autowatch.ts";
25
26
  import { HEAD_RUN_TOOLS, LOCAL_RUN_TOOLS } from "../runallow.ts";
26
27
  import { appendChapter, headResume, recapOf } from "./headchapters.ts";
27
28
  import type { RunWho } from "./rungate.ts";
@@ -391,13 +392,15 @@ export function createRuns(o: RunsOptions) {
391
392
  };
392
393
  /** The head tower's service (kind `head`): its runs resume one conversation in chapters and have the head's tools (docs/specs/2026-11-04-head-tower.md, Runs). */
393
394
  const isHeadSvc = (svc: Svc) => svc.ref.record().kind === "head";
395
+ /** Whether a run of that id is held and has not ended. */
396
+ const liveRun = (id: string) => Boolean(byRun.get(id) && !byRun.get(id)!.ended);
394
397
  const headRun = (a: Active) => a.rec.kind === "local" && isHeadSvc(a.svc);
395
398
 
396
399
  // --- events -----------------------------------------------------------------------------------------------------------------------------------------------------
397
400
 
398
- /** Events waiting for a run: not taken, not offered, a timer only when due; the boss first, then in the order the server received them. */
401
+ /** Events waiting for a run: not taken, not offered, not stale (`drop`), a timer only when due; the boss first, then in the order the server received them. */
399
402
  const waitingOf = (svc: Svc, offered: ReadonlySet<string> = new Set()): QueuedEvent[] =>
400
- readQueue(slot, svc.ref.workspace).filter((e) => !e.taken && !offered.has(e.id)).sort((a, b) => (PRIORITY[a.kind] ?? 1) - (PRIORITY[b.kind] ?? 1) || a.seq - b.seq);
403
+ readQueue(slot, svc.ref.workspace).filter((e) => !e.taken && !e.drop && !offered.has(e.id)).sort((a, b) => (PRIORITY[a.kind] ?? 1) - (PRIORITY[b.kind] ?? 1) || a.seq - b.seq);
401
404
  const noticeOf = (svc: Svc, n: Omit<Notice, "at">) => {
402
405
  svc.notices = [...svc.notices.filter((x) => x.id !== n.id), { ...n, at: now() }].slice(-10);
403
406
  };
@@ -949,18 +952,26 @@ export function createRuns(o: RunsOptions) {
949
952
  slots = Math.max(0, slots - 1);
950
953
  if (svc.run === a) svc.run = undefined;
951
954
  const ally = a.rec.kind === "ally";
952
- const taken = ally ? [] : readQueue(slot, ws).filter((e) => e.taken?.run === a.rec.id);
955
+ const mine = ally ? [] : readQueue(slot, ws), taken = mine.filter((e) => e.taken?.run === a.rec.id);
953
956
  const failed = outcome === "crashed" || outcome === "timeout";
954
957
  // The device keeps its run until its messages are handed back: a run begun meanwhile would take them again (A6).
955
958
  if (ally) await finishAlly(a, outcome, failed, keepTaken).finally(() => void (a.rec.device && svc.allies.get(a.rec.device) === a && svc.allies.delete(a.rec.device)));
956
959
  for (const e of taken) {
957
960
  try {
958
- if (!failed && outcome !== "herdr-restart" && !keepTaken) removeEvent(slot, ws, e);
961
+ // The head's ledger (the watch's keys alone, RV5-F001): a notice a head run took to a good end is told; one it was quit, crashed or stopped with is not (AW-D20).
962
+ if (outcome === "done" && !keepTaken && e.kind === "notice" && e.messageId && e.messageId.startsWith(WATCH_KEY) && isHeadSvc(svc)) addTold(slot, e.messageId);
963
+ // A stale event goes with the run that held it, whatever its end (AW-D21).
964
+ if (e.drop) removeEvent(slot, ws, e);
965
+ else if (!failed && outcome !== "herdr-restart" && !keepTaken) removeEvent(slot, ws, e);
959
966
  else if (outcome === "herdr-restart" || keepTaken) updateEvent(slot, ws, { ...withoutTaken(e), flag: "crash" });
960
967
  else if ((e.crashes ?? 0) + 1 >= 2) (parkEvent(slot, ws, { ...withoutTaken(e), crashes: (e.crashes ?? 0) + 1, flag: "crash" }), noticeOf(svc, { id: `parked-${e.id}`, level: "warning", kind: "late", text: `An event was parked after two runs crashed with it: ${e.kind} ${e.from?.name ?? e.from?.id ?? ""}`.trim() }));
961
968
  else updateEvent(slot, ws, { ...withoutTaken(e), crashes: (e.crashes ?? 0) + 1, flag: "crash" });
962
969
  } catch (cause) { error("run-events", (cause as Error).message); }
963
970
  }
971
+ // A stale event offered to this run and never taken goes with it too.
972
+ for (const e of mine.filter((x) => x.drop && !x.taken && a.offered.has(x.id))) {
973
+ try { removeEvent(slot, ws, e); } catch (cause) { error("run-events", (cause as Error).message); }
974
+ }
964
975
  if (failed) {
965
976
  try { addNote(slot, ws, { kind: a.rec.kind, ...(a.rec.device ? { device: a.rec.device } : {}), run: a.rec.id, at: iso(now()), note: `(${outcome === "timeout" ? "timed out" : "crashed"}: ${detail ?? outcome})` }); } catch (cause) { error("run-note", (cause as Error).message); }
966
977
  }
@@ -1585,12 +1596,52 @@ export function createRuns(o: RunsOptions) {
1585
1596
  /** A late outcome of something a run sent after the run ended, or a notice the server raises (the stall watch): a notice event for the next run. False when the server stands in for no tower there. */
1586
1597
  notice(workspace: string, text: string, key: string): boolean {
1587
1598
  const svc = services.get(workspace);
1588
- if (!svc) return false;
1599
+ if (stopped || !svc) return false; // a server that is stopping queues nothing (RV5-F002)
1589
1600
  if (waitingOf(svc).some((e) => e.kind === "notice" && e.messageId === key)) return true;
1590
1601
  append(slot, svc.ref.record(), { kind: "notice", text, at: iso(now()), messageId: key });
1591
1602
  poke(svc);
1592
1603
  return true;
1593
1604
  },
1605
+ /**
1606
+ * Whether a notice whose key starts with `prefix` waits in the queue: not taken yet, or held by a run that has not ended; a stale one (`drop`) does not count. The auto watch sends no second one over it, even when
1607
+ * its own mark of the last notice is lost with its period file (AW-D21, W2).
1608
+ */
1609
+ noticeWaits(workspace: string, prefix: string): boolean {
1610
+ if (!services.get(workspace)) return false;
1611
+ return readQueue(slot, workspace).some((e) => e.kind === "notice" && !e.drop && Boolean(e.messageId?.startsWith(prefix)) && (!e.taken || liveRun(e.taken.run)));
1612
+ },
1613
+ /**
1614
+ * Where the head's notice of key `key` is: held by a head run that has not ended (`taken`), in the queue otherwise (waiting, offered, or held by a run that is gone), parked after two runs crashed with it, `told` (a
1615
+ * head run that took it ended well: the head's ledger has it), or `gone` (it left the queue with no run that ended well: a run that was quit, a purge, a drop). Read in the head's own folder, not through its
1616
+ * workspace's binding: the head that closes unbinds it, and its untaken notice must not read as gone (RV3-F001; AW-D20).
1617
+ */
1618
+ noticeState(key: string): "queued" | "taken" | "parked" | "told" | "gone" {
1619
+ const ours = (e: QueuedEvent) => e.kind === "notice" && e.messageId === key;
1620
+ const e = readQueue(slot, HEAD_KEY).find(ours);
1621
+ if (e) return e.taken && liveRun(e.taken.run) ? "taken" : "queued";
1622
+ if (readQueue(slot, HEAD_KEY, true).some(ours)) return "parked";
1623
+ return readTold(slot).includes(key) ? "told" : "gone";
1624
+ },
1625
+ /**
1626
+ * Auto mode ended: the notices whose key starts with `prefix` are stale. Read in the head's own folder whether or not a head is open (RV4-F003): the ones queued or parked go; one a live head run holds (taken or
1627
+ * offered) is marked `drop`, so that run may finish it but it goes when the run ends and no other run is offered it (AW-D21). Returns how many went at once.
1628
+ */
1629
+ dropNotices(prefix: string): number {
1630
+ const ours = (e: QueuedEvent) => e.kind === "notice" && Boolean(e.messageId?.startsWith(prefix));
1631
+ const live = [...byRun.values()].filter((a) => !a.ended && a.rec.kind === "local" && isHeadSvc(a.svc));
1632
+ let gone = 0;
1633
+ for (const e of readQueue(slot, HEAD_KEY).filter(ours)) {
1634
+ const holder = live.find((a) => e.taken?.run === a.rec.id || a.offered.has(e.id));
1635
+ if (!holder) (removeEvent(slot, HEAD_KEY, e), gone++);
1636
+ else if (!e.drop) {
1637
+ const marked: QueuedEvent = { ...e, drop: true };
1638
+ updateEvent(slot, HEAD_KEY, marked);
1639
+ if (holder.offered.has(e.id)) holder.offered.set(e.id, { ...holder.offered.get(e.id)!, drop: true });
1640
+ }
1641
+ }
1642
+ for (const e of readQueue(slot, HEAD_KEY, true).filter(ours)) (dropParked(slot, HEAD_KEY, e), gone++);
1643
+ return gone;
1644
+ },
1594
1645
  /** The service is held because the standing pane runs a program of the boss's: it is Retried by itself once the pane is free (standing.ts). */
1595
1646
  paneBusy(workspace: string) {
1596
1647
  const svc = services.get(workspace);
@@ -83,7 +83,7 @@ export interface StallDeps {
83
83
  /** Pids that are never a pi session: this server (its tower identities are in pi-intercom's list under its pid). */
84
84
  self?: number[];
85
85
  }
86
- export interface StallRow { pid: number; session: string; pane: string; signals: Signal[]; told: number }
86
+ export interface StallRow { pid: number; session: string; pane: string; /** The workspace of its pane, when Herdr named one. */ workspace?: string; signals: Signal[]; told: number }
87
87
  export interface StallWatch {
88
88
  /** One look at the table of a tick; it does nothing until a minute has passed since the last sample, or while a sample runs. Never rejects. */
89
89
  sample(table: readonly Proc[]): Promise<void>;
@@ -316,6 +316,6 @@ export function createStallWatch(d: StallDeps): StallWatch {
316
316
  busy = false;
317
317
  }
318
318
  },
319
- list: () => [...watched.values()].flatMap((w) => (w.incident ? [{ pid: w.pid, session: w.session ?? "(unknown)", pane: w.pane, signals: [...w.incident.signals], told: w.incident.told }] : [])),
319
+ list: () => [...watched.values()].flatMap((w) => (w.incident ? [{ pid: w.pid, session: w.session ?? "(unknown)", pane: w.pane, ...(w.workspace ? { workspace: w.workspace } : {}), signals: [...w.incident.signals], told: w.incident.told }] : [])),
320
320
  };
321
321
  }
@@ -60,6 +60,8 @@ export interface QueuedEvent {
60
60
  press?: true;
61
61
  /** Who sent a boss event over the control socket, as the request reported it (auto mode records it; docs/specs/2026-11-09-auto-mode.md, §2). */
62
62
  requester?: Requester;
63
+ /** The event is stale (the auto watch's notice of a period that ended): the run that holds it may finish it, but it goes when that run ends, whatever the outcome, and no other run is offered it (AW-D21). */
64
+ drop?: true;
63
65
  }
64
66
 
65
67
  /** A file name for a Herdr id: ids are short counters, but nothing a caller sends may leave the folder. */
@@ -188,6 +190,16 @@ export function unparkEvent(slot: Slot, workspace: string, event: QueuedEvent):
188
190
  export function dropParked(slot: Slot, workspace: string, event: Pick<QueuedEvent, "seq" | "id">): void {
189
191
  rmSync(join(parkedDir(slot, workspace), nameOf(event)), { force: true });
190
192
  }
193
+ /** The head's ledger of the notices a head run finished well (`told.json` in `head/`): the auto watch counts its notice as told only when its key is here (AW-D20). Newest last. */
194
+ const TOLD = "told.json", TOLD_KEPT = 50;
195
+ export function readTold(slot: Slot): string[] {
196
+ const list = readJson<unknown>(join(headDir(slot), TOLD));
197
+ return Array.isArray(list) ? list.filter((k): k is string => typeof k === "string") : [];
198
+ }
199
+ export function addTold(slot: Slot, key: string): void {
200
+ ensureDir(headDir(slot));
201
+ writeDurable(join(headDir(slot), TOLD), [...readTold(slot).filter((k) => k !== key), key].slice(-TOLD_KEPT));
202
+ }
191
203
  export function queueLength(slot: Slot, workspace: string): number {
192
204
  try {
193
205
  return readdirSync(queueDir(slot, workspace)).filter((name) => name.endsWith(".json")).length;
@@ -262,14 +274,14 @@ const countFiles = (dir: string): number => {
262
274
  for (const e of readdirSync(dir, { withFileTypes: true })) n += e.isDirectory() ? countFiles(join(dir, e.name)) : 1;
263
275
  return n;
264
276
  };
265
- /** The flag is off: every workspace's `service.json`, queue (parked events too), runs, notes, expectations, timer, dedupe ledger and opener's ledger go, the head's in `head/` with them, but not its conversation, memory, asks, or chapters (message text stays on disk with no time limit otherwise). Returns how many files went. */
277
+ /** The flag is off: every workspace's `service.json`, queue (parked events too), runs, notes, expectations, timer, dedupe ledger, opener's ledger and the head's told ledger go, the head's in `head/` with them, but not its conversation, memory, asks, or chapters (message text stays on disk with no time limit otherwise). Returns how many files went. */
266
278
  export function purgeAll(slot: Slot): number {
267
279
  let gone = 0, names: string[] = [];
268
280
  try {
269
281
  names = readdirSync(towersDir(slot));
270
282
  } catch { /* none */ }
271
283
  for (const dir of [...names.map((name) => join(towersDir(slot), name)), headDir(slot)]) {
272
- for (const entry of ["queue", "runs", SERVICE, OPENED, "notes.jsonl", "expects.json", "timer.json", "seen.jsonl", ...ALLY_FILES]) {
284
+ for (const entry of ["queue", "runs", SERVICE, OPENED, "notes.jsonl", "expects.json", "timer.json", "seen.jsonl", TOLD, ...ALLY_FILES]) {
273
285
  const path = join(dir, entry), stat = statSync(path, { throwIfNoEntry: false });
274
286
  if (!stat) continue;
275
287
  gone += stat.isDirectory() ? countFiles(path) : 1;
@@ -1,9 +1,9 @@
1
- import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { availableParallelism, loadavg, userInfo } from "node:os";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { execFileSyncExe } from "../exe.mjs";
5
5
  import { checkAcceptRef, checkCar, checkEvidence, parseAppAccept, parseSlip } from "../train/accept.ts";
6
- import { readAppIntegration, readApps } from "../train/appsconfig.ts";
6
+ import { appsFile, projectAppsDir, readAppIntegration, repoRoot } from "../train/appsconfig.ts";
7
7
  import { type Board, boardPath, boardState, MAX_TRAINS, trainboardDir, factsOf, MAX_CLEARS, readBoard, readTrainboards, type Writer, writeBoard } from "../train/board.ts";
8
8
  import { isName, isObject, validateStep } from "../train/spec.ts";
9
9
  import { noticeStatus, stateLine, type Attempt } from "../train/cars.ts";
@@ -92,14 +92,20 @@ function check(flags: Record<string, string | true>, io: TrainIo): number {
92
92
  if (accept.refusal) refusals.push(accept.refusal);
93
93
  if (slip?.refusal) refusals.push(slip.refusal);
94
94
  if (!setting.ok) refusals.push(setting.refusal);
95
- // What the app requires is the file's (TB-F001): the project's apps.json in this folder, for the app `--app` names, else the slip's `car:`, else the evidence's `car.app`. `--app-accept` can only add to it. A folder with no apps.json
96
- // (a coordinator's worktree may have none) is checked with the flag alone; the integrator's guard and the train read the project's file.
95
+ // What the app requires is the file's (TB-F001): the project's apps.json, for the app `--app` names, else the slip's `car:` (or `app:`), else the evidence's `car.app`. `--app-accept` can only add to it. The file is this folder's, else
96
+ // that of the repository's main checkout (a coordinator's linked worktree may have none, and the tower reads the project's). When neither has one, a named app could not be checked, and the check says so instead of ok (0.77.3);
97
+ // with no app named, the flag alone is checked.
97
98
  let required: string[] = setting.ok ? setting.accept : [];
98
- if (!accept.refusal && !slip?.refusal && setting.ok && !readApps(cwd).missing) {
99
+ if (!accept.refusal && !slip?.refusal && setting.ok) {
99
100
  const app = typeof flags.app === "string" ? flags.app : slip ? parseSlip(slip.text!).fields.car : evidenceApp(accept.text);
100
- const found = app ? readAppIntegration(cwd, app) : { ok: false as const, refusal: "sb: the project has an apps.json, so name the app to check against: --app <name>" };
101
- if (found.ok) required = [...new Set([...required, ...found.accept])];
102
- else refusals.push(found.refusal);
101
+ const dir = projectAppsDir(cwd);
102
+ if (dir === undefined) {
103
+ if (app) refusals.push(`sb: app ${app} could not be checked: ${noAppsWhere(cwd)}; run train check in the project's checkout`);
104
+ } else {
105
+ const found = app ? readAppIntegration(dir, app) : { ok: false as const, refusal: "sb: the project has an apps.json, so name the app to check against: --app <name>" };
106
+ if (found.ok) required = [...new Set([...required, ...found.accept])];
107
+ else refusals.push(found.refusal);
108
+ }
103
109
  }
104
110
  if (!accept.refusal && !slip?.refusal && setting.ok && !refusals.length) {
105
111
  const exists = io.exists ?? ((path: string) => existsSync(resolve(cwd, path)));
@@ -119,6 +125,13 @@ function check(flags: Record<string, string | true>, io: TrainIo): number {
119
125
  return refusals.length ? 2 : 0;
120
126
  }
121
127
 
128
+ /** Where `train check` looked for an apps.json and found none: the folder's git root, and the repository's main checkout when that is another folder. */
129
+ function noAppsWhere(cwd: string): string {
130
+ const real = (path: string) => { try { return realpathSync(path); } catch { return path; } };
131
+ const here = appsFile(real(cwd)).both, main = appsFile(repoRoot(cwd)).both;
132
+ return `no apps.json at ${here}${main === here ? "" : `, nor in the main checkout of this repository (${main})`}`;
133
+ }
134
+
122
135
  /** The app an evidence file names (`car.app`), if it is one. */
123
136
  function evidenceApp(text: string | undefined): string | undefined {
124
137
  try { const car = (JSON.parse(text ?? "null") as { car?: { app?: unknown } } | null)?.car; return typeof car?.app === "string" ? car.app : undefined; } catch { return undefined; }
@@ -0,0 +1,90 @@
1
+ import { join } from "node:path";
2
+ import { boardSeam } from "../boardview.ts";
3
+ import type { HerdrRun, HerdrWorld, Session } from "../herdr.ts";
4
+ import { netSource } from "../net.ts";
5
+ import type { AutoMode, Period } from "./automode.ts";
6
+ import { type AutoWatch, createAutoWatch, type NoticeWhere, type WatchDeps, type WatchReport, WATCH_KEY, WATCH_TICK_MS, factsOf, watchSection } from "./autowatch.ts";
7
+ import { readAsks } from "./headasks.ts";
8
+ import { headSeam } from "./headnet.ts";
9
+ import type { Slot } from "./record.ts";
10
+ import type { StallRow } from "./stallwatch.ts";
11
+ import { inTestRun } from "./testguard.ts";
12
+ import { towerPanel } from "./towerpanel.ts";
13
+ import type { Towers } from "./towers.ts";
14
+ import { trainyardSeam, type YardDeps } from "./trainyard.ts";
15
+
16
+ // The server's side of the auto watch (autowatch.ts): the reading of the net it takes its facts from, the head tower it wakes, and its timer. Kept out of main.ts, which carries a line budget.
17
+
18
+ export interface StartWatch {
19
+ auto: AutoMode;
20
+ slot: Slot;
21
+ env: NodeJS.ProcessEnv;
22
+ now(): number;
23
+ log(event: string, facts: Record<string, string | number | boolean | undefined>): void;
24
+ run: HerdrRun;
25
+ world?: HerdrWorld;
26
+ /** pi-intercom's list as the server's own connection sees it; rejects while it is not connected. */
27
+ sessions(): Promise<Session[]>;
28
+ towers(): Towers | undefined;
29
+ /** The stall watch's open incidents (none where it does not run). */
30
+ stalls(): StallRow[];
31
+ /** The server's book of cars, for the yards (trainyard.ts). */
32
+ book?: () => YardDeps["book"] | undefined;
33
+ /** The seams of a test: the watch's own deps and how often it looks. In a test run there is no watch without them (it would read the net of a fake Herdr and wake the head of every test that leaves auto mode on). */
34
+ over?: Partial<WatchDeps> & { tickMs?: number };
35
+ }
36
+
37
+ /**
38
+ * What the switch does for the watch (boss, 11/12): switched on with no head tower open, the server opens one, since the boss is at their switch and the watch has nobody to wake otherwise; a head that is gone later in the
39
+ * night is not opened again (the readings count it for the morning). Switched off, the watch's notices are stale and nothing of the watch acts once the boss is back: they are dropped from the head's own folder whether or
40
+ * not a head tower is open (RV4-F003), and one a live head run holds goes when that run ends, whatever its end (AW-D21).
41
+ */
42
+ export function watchSwitch(o: { towers(): Towers | undefined; log: StartWatch["log"] }) {
43
+ return (change: { from: { on: boolean }; to: { on: boolean } }): void => {
44
+ const towers = o.towers();
45
+ if (!towers || change.from.on === change.to.on) return;
46
+ if (!change.to.on) {
47
+ const dropped = towers.runs.dropNotices(WATCH_KEY);
48
+ if (dropped) o.log("watch-dropped", { notices: dropped });
49
+ return;
50
+ }
51
+ if (towers.head.status()) return;
52
+ void towers.head.ensure().then((got) => o.log("watch-head", { opened: got.opened, workspace: got.workspace }), (cause: Error) => o.log("watch-head", { error: String(cause?.message ?? cause).slice(0, 200) }));
53
+ };
54
+ }
55
+
56
+ /** The watch's section of the return list for the period that ends (automode.ts `watch`): the head's asks are read here, so the nudges since the last wake are in it, and the queue, so a notice a run took to a good end since the last reading counts as told. */
57
+ export const reportWatch = (slot: Slot, now: () => number, towers: () => Towers | undefined) => (period: Period, until: string): WatchReport | undefined => watchSection(period.watch, period.since, until, asksOf(slot, now), (p) => noticeState(towers, p));
58
+ /** Where a notice of the watch is, read in the head's own folder; queued while the towers are not known (it is not taken for told). */
59
+ const noticeState = (towers: () => Towers | undefined, p: { key: string }): NoticeWhere => towers()?.runs.noticeState(p.key) ?? "queued";
60
+ /** The head's asks; none when the file cannot be read (the watch's count of the head's own messages then stands where it was, and the return list is still written). */
61
+ const asksOf = (slot: Slot, now: () => number) => { try { return readAsks(slot, now()); } catch { return []; } };
62
+
63
+ /**
64
+ * The watch of this server with its timer, or none (a test run without seams). The facts come from a reading of the net of its own, the one the pages draw (net.ts): the tower services, the head's asks, the work board, and the
65
+ * yards; it is read when a wake is due, not at each look. The stop is returned.
66
+ */
67
+ export function startAutoWatch(o: StartWatch): (() => void) | undefined {
68
+ if (inTestRun() && !o.over) return undefined;
69
+ const { tickMs, ...over } = o.over ?? {};
70
+ const offSwitch = o.auto.onSwitch(watchSwitch(o));
71
+ const net = netSource({
72
+ services: (workspace) => towerPanel(o.towers).view(workspace), head: headSeam(o.slot, o.now), run: o.run, ...(o.world ? { world: o.world } : {}), sessions: o.sessions,
73
+ board: boardSeam({ dir: join(o.slot.stateDir, "board"), now: o.now }), trainyard: trainyardSeam({ env: o.env, stateDir: o.slot.stateDir, now: o.now, ...(o.book ? { book: o.book } : {}) }),
74
+ });
75
+ let stopped = false;
76
+ const watch: AutoWatch = createAutoWatch({
77
+ stopped: () => stopped,
78
+ now: o.now, log: o.log, auto: o.auto,
79
+ // The head tower is woken where the server stands in for it; a service that is held starts no run, so its notices would only pile up.
80
+ head: () => ((row) => (row ? { workspace: row.workspace, ...(row.service?.state === "held" ? { held: true } : {}) } : undefined))(o.towers()?.head.status()),
81
+ facts: async (input) => factsOf(await net.read(), { ...input, stalls: o.stalls() }),
82
+ asks: () => asksOf(o.slot, o.now),
83
+ waiting: (workspace) => o.towers()?.runs.noticeWaits(workspace, WATCH_KEY) ?? false,
84
+ noticeState: (_workspace, key) => noticeState(o.towers, { key }),
85
+ wake: (workspace, text, key) => o.towers()?.runs.notice(workspace, text, key) ?? false,
86
+ ...over,
87
+ });
88
+ const timer = setInterval(() => void watch.tick(), tickMs ?? WATCH_TICK_MS);
89
+ return () => ((stopped = true), clearInterval(timer), offSwitch());
90
+ }
@@ -17,8 +17,11 @@ const text = (value: unknown, max = 1000): value is string => typeof value === "
17
17
 
18
18
  // ---- the slip
19
19
 
20
- /** The keys of a slip (the receive-car playbook's block); any other key refuses the slip. */
21
- export const SLIP_KEYS = ["car", "tickets", "branch", "head", "tested-on", "review", "light", "migrations", "lane", "deploy", "departs", "accept", "uat", "auth", "coordinator"];
20
+ /**
21
+ * The keys of a slip (the receive-car playbook's block); any other key refuses the slip. `car:` names the car's app (its `name` in apps.json), never a ticket: the tickets go in `tickets:`, and the first of them is what `train_car`'s
22
+ * `car` names. `app:` is the same field under its plain name (0.77.3); a slip may give either, or both when they agree.
23
+ */
24
+ export const SLIP_KEYS = ["car", "app", "tickets", "branch", "head", "tested-on", "review", "light", "migrations", "lane", "deploy", "departs", "accept", "uat", "auth", "coordinator"];
22
25
  /** One `key: value` of a slip, in the order written; a segment with no key has `key` empty. Every entry is read for a request, including a repeated key and a keyless line. */
23
26
  export interface SlipEntry { key: string; value: string; line: number }
24
27
  export interface ParsedSlip { fields: Record<string, string>; tickets: string[]; entries: SlipEntry[]; problems: string[] }
@@ -65,16 +68,29 @@ export function parseSlip(slip: string): ParsedSlip {
65
68
  else fields[key] = value;
66
69
  }
67
70
  });
71
+ // `app:` is `car:` under its plain name: one names the other's value, and two that differ are refused, since the slip would name two apps (a ticket written in `car:` is the usual cause).
72
+ if (fields.app !== undefined) {
73
+ if (fields.car === undefined) fields.car = fields.app;
74
+ else if (fields.car !== fields.app) problems.push(`sb: slip: app: ${shown(fields.app)} and car: ${shown(fields.car)} name two apps: car: names the car's app (app: is the same field), and its tickets go in tickets:`);
75
+ }
68
76
  const tickets = (fields.tickets ?? "").replace(/\([^)]*\)/g, " ").split(/[\s,]+/).filter(Boolean);
69
77
  return { fields, tickets, entries, problems };
70
78
  }
71
79
 
72
- /** A slip block starts at a `car:` line and runs over the lines of `key: value | key: value` segments up to a blank line or the next `car:` line; what comes before the first block is the manifest's header. */
80
+ /** A line that starts a slip block: one that starts with `car:`, or with `app:` and goes on to a `car:` or `tickets:` segment (a manifest's header `app: <name>` line stands alone, and starts none). */
81
+ const SLIP_START = /^\s*(?:car:|app:[^|\n]*\|\s*(?:car|tickets):)/i;
82
+ /** Whether `line` starts a slip block. */
83
+ export const startsSlip = (line: string) => SLIP_START.test(line);
84
+
85
+ /** A text with each slip on a line of its own: a `car: <app> | tickets: …` (or `app: <app> | car:`/`tickets:`) that follows other words on its line starts a new line; one that follows a ` | ` is a segment of the slip before it. */
86
+ export const slipLines = (body: string) => body.replace(/([^\s|])[ \t]+((?:car|app):[ \t]*[A-Za-z0-9._-]+[ \t]*\|[ \t]*(?:tickets|car):)/gi, "$1\n$2");
87
+
88
+ /** A slip block starts at a `car:` line (or an `app:` slip line, `startsSlip`) and runs over the lines of `key: value | key: value` segments up to a blank line or the next `car:` line; what comes before the first block is the manifest's header. */
73
89
  export function slipBlocks(text: string): { header: string; blocks: string[] } {
74
90
  const header: string[] = [], blocks: string[][] = [];
75
91
  let open = false;
76
92
  for (const line of text.split(/\r?\n/)) {
77
- if (/^\s*car:/i.test(line)) (blocks.push([line]), (open = true));
93
+ if (startsSlip(line)) (blocks.push([line]), (open = true));
78
94
  else if (open && line.trim() !== "" && /^\s*[A-Za-z][A-Za-z0-9-]*:/.test(line)) blocks.at(-1)!.push(line);
79
95
  else {
80
96
  open = false;
@@ -67,7 +67,7 @@ export function noTrainRefusal(dir: string, apps: readonly string[]): string | u
67
67
  if (!read.ok) return `sb: ${read.refusal.replace(/, so integration\.accept of the app is unknown$/, "")}, so no app here takes the merge train`;
68
68
  for (const app of apps) {
69
69
  const entry = read.apps.find((a) => a.name === app);
70
- if (!entry) return `sb: ${read.file} has no app named ${app}, so its car takes no train`;
70
+ if (!entry) return `sb: ${read.file} has no app named ${app}, so its car takes no train (the slip's car: names the car's app as apps.json names it, not a ticket)`;
71
71
  if (!isObject(entry.integration)) return `sb: ${read.file}: app ${app} has no integration, so it takes no train`;
72
72
  }
73
73
  return undefined;
@@ -85,6 +85,16 @@ export function openRefusal(dir: string, app: string | undefined): string | unde
85
85
  return out.length ? `sb: ${out.join("; ")}` : undefined;
86
86
  }
87
87
 
88
+ /**
89
+ * The folder whose apps.json speaks for the project at `dir`: `dir` when its git root has one, else the main checkout of its repository when that has one (a linked worktree of a coordinator often lacks an untracked
90
+ * `.claude/straw-boss/apps.json` the main checkout keeps, and the tower reads the project's), else undefined: no apps.json is found, and nothing that needs one can be checked.
91
+ */
92
+ export function projectAppsDir(dir: string): string | undefined {
93
+ if (appsFile(dir).exists) return dir;
94
+ const main = repoRoot(dir);
95
+ return appsFile(main).exists ? main : undefined;
96
+ }
97
+
88
98
  /** The repository `dir` is a checkout of, as its main checkout's real folder: a linked worktree's `.git` is a file naming its git dir, whose `commondir` leads to the repository's own `.git`. Two worktrees of one repository answer the same; anything else answers its git root. */
89
99
  export function repoRoot(dir: string): string {
90
100
  const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } };
package/src/train/cars.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { parseSlip, slipBlocks, ticketBound } from "./accept.ts";
1
+ import { parseSlip, slipBlocks, slipLines, ticketBound } from "./accept.ts";
2
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.
@@ -290,16 +290,16 @@ export const forwardsFor = (forwards: readonly Forward[], head: string): Forward
290
290
  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]!))];
291
291
 
292
292
  /** 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. */
293
- 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 }
293
+ 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; /** What the parse refused in the slip (a key that is no slip field, a repeated key, `app:` and `car:` that differ): the door refuses such a slip with these words, so nothing in it is dropped unsaid (0.77.3). */ problems?: string[] }
294
294
 
295
- /** The slips a forwarded text carries: a `car: <app> | tickets: …` that follows the tower's own words starts a block of its own line. Only a slip that parses and names app, tickets, branch and a 40-hex head is returned. */
295
+ /** The slips a forwarded text carries: a `car: <app> | tickets: …` that follows the tower's own words starts a block of its own line (`slipLines`). Only a slip that names app, tickets, branch and a 40-hex head is returned, with what its parse refused. */
296
296
  export function slipsInText(body: string): SlipFacts[] {
297
- const lines = body.replace(/(\S)[ \t]+(car:[ \t]*[A-Za-z0-9._-]+[ \t]*\|[ \t]*tickets:)/gi, "$1\n$2");
297
+ const lines = slipLines(body);
298
298
  return slipBlocks(lines).blocks.flatMap((block) => {
299
299
  const parsed = parseSlip(block), f = parsed.fields;
300
300
  if (!f.car || !isName(f.car) || !parsed.tickets.length || !f.branch || !SHA_RE.test(f.head ?? "")) return [];
301
301
  const over = ticketBound(parsed.tickets).join("; "), tickets = over ? parsed.tickets.slice(0, MAX_CAR_TICKETS).map((t) => t.slice(0, MAX_TICKET_CHARS)) : parsed.tickets;
302
- return [{ app: f.car, tickets, ...(over ? { over } : {}), branch: f.branch, head: f.head!, ...(f.coordinator ? { coordinator: f.coordinator } : {}) }];
302
+ return [{ app: f.car, tickets, ...(over ? { over } : {}), branch: f.branch, head: f.head!, ...(f.coordinator ? { coordinator: f.coordinator } : {}), ...(parsed.problems.length ? { problems: parsed.problems } : {}) }];
303
303
  });
304
304
  }
305
305
 
package/src/traincar.ts CHANGED
@@ -8,7 +8,7 @@ import { callControl, type Reply } from "./server/socket.ts";
8
8
  import { startOf } from "./startof.ts";
9
9
  import type { Kit } from "./state.ts";
10
10
  import { snapshotOfBranch } from "./todo.ts";
11
- import { parseSlip } from "./train/accept.ts";
11
+ import { parseSlip, slipLines } from "./train/accept.ts";
12
12
  import { CAR_STATES, type CarState, type CarView, coordinatorWord, forwardsOf, noticeText, validateStateFields } from "./train/cars.ts";
13
13
  import { isName, isObject, type Json } from "./train/spec.ts";
14
14
  import { type Manifest, rowsOfSnapshot, slipBlocks, type TrainGuard } from "./trainguard.ts";
@@ -125,8 +125,7 @@ const FIELD_KEYS = ["train", "departs", "reason", "round", "evidence", "version"
125
125
 
126
126
  /** The slip blocks of a forwarded message body: a `car: <app> | tickets: …` that follows the tower's own words starts a block of its own line. */
127
127
  function slipsOf(body: string) {
128
- const lines = body.replace(/(\S)[ \t]+(car:[ \t]*[A-Za-z0-9._-]+[ \t]*\|[ \t]*tickets:)/gi, "$1\n$2");
129
- return slipBlocks(lines).blocks.map(parseSlip);
128
+ return slipBlocks(slipLines(body)).blocks.map(parseSlip);
130
129
  }
131
130
 
132
131
  const assembles = (rows: ReturnType<typeof rowsOfSnapshot>["rows"]) => rows.flatMap((r) => {
@@ -141,7 +140,7 @@ export async function trainCar(deps: CarToolDeps, params: CarParams, ctx: CarCtx
141
140
  if (!role) throw new Error("sb: train_car is for a train and for the integrator; this session is neither");
142
141
  const state = params.state;
143
142
  if (!(CAR_STATES as readonly string[]).includes(state)) throw new Error(`sb: state "${String(state)}" is not one of ${CAR_STATES.join(", ")}`);
144
- if (typeof params.car !== "string" || !params.car.trim()) throw new Error("sb: car is the car's first ticket");
143
+ if (typeof params.car !== "string" || !params.car.trim()) throw new Error("sb: car is the car's first ticket (the first of the slip's tickets:, not its car:, which names the app)");
145
144
  const ticket = params.car.trim();
146
145
  if (role === "train" && state === "received") throw new Error("sb: a train does not set received: the integrator does, at receipt");
147
146
  if (role === "main" && (state === "dropped" || state === "landed")) throw new Error(`sb: only a train sets ${state}; the integrator sets received and returned`);
@@ -225,7 +224,7 @@ export function trainCarTool(kit: Kit, guard: () => TrainGuard | undefined, link
225
224
  name: "train_car", label: "train_car",
226
225
  description: "Set what became of a car: the sb server tells the car's coordinator by session id and confirms the delivery, and the step that depends on it waits for that. For the integrator (state received with train and departs, or returned with reason, at receipt) and a train (returned with reason, dropped with round, reason and evidence, landed with version and commit). Never send a coordinator a notice yourself.",
227
226
  parameters: Type.Object({
228
- car: Type.String({ description: "The car's first ticket, as the slip names it." }),
227
+ car: Type.String({ description: "The car's first ticket: the first of the slip's tickets:, not the slip's car: (which names the car's app)." }),
229
228
  state: Type.Union(CAR_STATES.map((x) => Type.Literal(x))),
230
229
  project: Type.Optional(Type.String({ description: "Integrator only, when no train todo names the project yet." })),
231
230
  train: Type.Optional(Type.String({ description: "received: the train's code, YYYY-MM-DD-<letters>." })),
package/src/trainrole.ts CHANGED
@@ -52,7 +52,7 @@ export function trainFromRequest(request: string): TrainId | { refusal: string }
52
52
  }
53
53
 
54
54
  /** The manifest header's `app:` line, if it has one (the same line the train's manifest check reads). */
55
- export const appFromRequest = (request: string): string | undefined => /^\s*app:\s*([A-Za-z0-9._-]{1,64})\s*$/m.exec(request.split(/\r?\n(?=\s*car:)/i)[0] ?? request)?.[1];
55
+ export const appFromRequest = (request: string): string | undefined => /^\s*app:\s*([A-Za-z0-9._-]{1,64})\s*$/m.exec(request.split(/\r?\n(?=\s*(?:car:|app:[^|\n]*\|\s*(?:car|tickets):))/i)[0] ?? request)?.[1];
56
56
 
57
57
  /** `integration.maxTrains` as apps.json gives it: absent is the default; anything but a whole number from 1 to 32 is a refusal naming the field. */
58
58
  export function maxTrainsOf(value: unknown): number | { refusal: string } {