pi-straw-boss 0.75.0 → 0.75.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.75.0",
3
+ "version": "0.75.2",
4
4
  "description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/balance.d.mts CHANGED
@@ -6,6 +6,6 @@ export interface Resize { pane: string; direction: "left" | "right" | "up" | "do
6
6
  export type Run = (args: string[]) => Promise<string>;
7
7
 
8
8
  export function planBalance(layout: Layout): Resize[];
9
- export const herdr: Run;
9
+ export const herdr: (args: string[], deadline?: number) => Promise<string>;
10
10
  export function balanceTab(paneId: string, options?: { run?: Run; lockRoot?: string }): Promise<void>;
11
11
  export function balanceAfterClose(paneId: string, tabId: string | undefined, options?: { run?: Run; lockRoot?: string; pollMs?: number; waitMs?: number }): Promise<void>;
package/src/balance.mjs CHANGED
@@ -23,6 +23,8 @@ const LOCK_STALE_MS = 30_000;
23
23
  // pi-herdr-agents closes a worker's pane once its lead has taken the result.
24
24
  const CLOSE_WAIT_MS = 30_000;
25
25
  const POLL_MS = 250;
26
+ // One herdr command: a reading or one resize, which Herdr answers at once. Ten seconds is past a CLI start on a loaded machine and well inside LOCK_STALE_MS, after which another helper takes the tab's lock from this one.
27
+ const HERDR_MS = 10_000;
26
28
 
27
29
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
28
30
 
@@ -92,10 +94,10 @@ export function planBalance(layout) {
92
94
  return resizes;
93
95
  }
94
96
 
95
- /** @type {Run} */
96
- export const herdr = (args) =>
97
+ /** With a deadline that holds (exe.mjs): the helper runs detached with nobody to end it, so a herdr that never ends must not keep it, or the tab's lock. @type {Run} */
98
+ export const herdr = (args, deadline = HERDR_MS) =>
97
99
  new Promise((resolve, reject) => {
98
- execFileExe(process.env.HERDR_BIN_PATH || "herdr", args, { encoding: "utf8" }, (error, stdout, stderr) =>
100
+ execFileExe(process.env.HERDR_BIN_PATH || "herdr", args, { encoding: "utf8", deadline }, (error, stdout, stderr) =>
99
101
  error ? reject(Object.assign(error, { stderr })) : resolve(stdout));
100
102
  });
101
103
 
package/src/exe.d.mts CHANGED
@@ -8,5 +8,6 @@ export interface ResolveDeps { env?: NodeJS.ProcessEnv; platform?: NodeJS.Platfo
8
8
  export function searchPath(name: string, deps?: ResolveDeps): string;
9
9
  export function resolveExe(name: string, deps?: ResolveDeps): string;
10
10
  export function forgetExe(name?: string): void;
11
- export function execFileExe(name: string, args: string[], options: ExecFileOptions, done: (error: (Error & { code?: string | number }) | null, stdout: string, stderr: string) => void): ChildProcess | undefined;
11
+ /** `deadline` (ms): the call ends by then whatever the program does, and a program cut off is ended behind it (its group where there are groups, the program alone with `group: false`), by SIGTERM and then SIGKILL after `grace` (ms, 2000). */
12
+ export function execFileExe(name: string, args: string[], options: ExecFileOptions & { deadline?: number; grace?: number; group?: boolean }, done: (error: (Error & { code?: string | number | null }) | null, stdout: string, stderr: string) => void): ChildProcess | undefined;
12
13
  export function execFileSyncExe(name: string, args: string[], options?: ExecFileSyncOptions): string | Buffer;
package/src/exe.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // planted in a repository would run with the user's rights. Every program the package starts by name (herdr, git, tailscale, sh, ps, the clipboard and browser openers) is found here
3
3
  // instead, by a search of PATH that skips what is not an absolute folder (empty, ".", and relative entries) and never looks in the current folder, and is spawned by the path it found.
4
4
  // Plain JavaScript on purpose: balance.mjs, which Node runs from node_modules without stripping types, uses it too.
5
- import { execFile, execFileSync } from "node:child_process";
5
+ import { execFile, execFileSync, spawn } from "node:child_process";
6
6
  import { accessSync, constants, statSync } from "node:fs";
7
7
  import { posix, win32 } from "node:path";
8
8
 
@@ -69,16 +69,76 @@ export function resolveExe(name, deps = {}) {
69
69
  /** Forgets what was found for `name` (all names without one): the next call searches again. @param {string} [name] */
70
70
  export const forgetExe = (name) => void (name === undefined ? cache.clear() : cache.delete(name));
71
71
 
72
+ const GRACE_MS = 2000;
73
+ /** Signals the process group `pid` leads; false when no process of it is left. @param {number} pid @param {NodeJS.Signals | 0} signal */
74
+ const signalGroup = (pid, signal) => {
75
+ try {
76
+ return process.kill(-pid, signal);
77
+ } catch {
78
+ return false;
79
+ }
80
+ };
81
+ /**
82
+ * `execFile` with a deadline that holds (`options.deadline`, in ms). execFile's own `timeout` sends one SIGTERM and calls back when the program has ended, so a program that does not end on SIGTERM holds the
83
+ * callback for as long as it lives (todo #155: a `herdr agent start` given 35 s called back 61 minutes later). Here `done` is called at the deadline at the latest. A program that had ended by then, with a copy
84
+ * of its stdout or stderr still open somewhere, is told by its own exit status, as execFile tells it. One still running is cut off: the error is marked as execFile marks a timeout (`killed`, `signal: "SIGTERM"`,
85
+ * no exit code), with what was read so far, and the program is ended behind the call by SIGTERM, then SIGKILL after `options.grace` (2 s). Where there are process groups it starts as the leader of its own
86
+ * (`detached`) and both signals go to the group, so what it started ends with it; on Windows they end the program alone. Output is read as UTF-8 text, and more than `maxBuffer` of it cuts the program off too.
87
+ * `options.group: false` is for a program whose children are meant to stay (an opener and the file manager it started): it runs in the caller's group, and the signals end it alone.
88
+ * @param {string} file
89
+ * @param {string[]} args
90
+ * @param {import("node:child_process").ExecFileOptions & { deadline: number, grace?: number, group?: boolean }} options
91
+ * @param {(error: (Error & { code?: string | number | null }) | null, stdout: string, stderr: string) => void} done
92
+ */
93
+ function execFileByDeadline(file, args, options, done) {
94
+ const alone = process.platform === "win32" || options.group === false, limit = options.maxBuffer ?? 1024 * 1024, cmd = [file, ...args].join(" ");
95
+ const child = spawn(file, args, { cwd: options.cwd, env: options.env, windowsHide: options.windowsHide, detached: !alone });
96
+ let stdout = "", stderr = "", settled = false;
97
+ /** @type {{ code: number | null, signal: NodeJS.Signals | null } | undefined} */
98
+ let ended;
99
+ /** @param {Error | null} error */
100
+ const settle = (error) => {
101
+ if (settled) return;
102
+ settled = true;
103
+ clearTimeout(timer);
104
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream?.destroy();
105
+ done(error, stdout, stderr);
106
+ };
107
+ /** @param {string} what @param {Record<string, unknown>} marks */
108
+ const failure = (what, marks) => Object.assign(new Error(`${what}: ${cmd}${stderr ? `\n${stderr}` : ""}`), { cmd, ...marks });
109
+ /** @param {{ code: number | null, signal: NodeJS.Signals | null }} status */
110
+ const byStatus = ({ code, signal }) => settle(code === 0 ? null : failure("Command failed", { code, killed: false, signal }));
111
+ /** @param {string} what @param {string | null} code */
112
+ const cutOff = (what, code) => {
113
+ if (settled) return;
114
+ settle(failure(what, { code, killed: true, signal: "SIGTERM" }));
115
+ if (ended) return; // it left by itself: what it left behind is not signalled, and its group's id may be another program's by now
116
+ /** @param {NodeJS.Signals} signal */
117
+ const send = (signal) => (alone || child.pid === undefined ? child.kill(signal) : signalGroup(child.pid, signal));
118
+ send("SIGTERM");
119
+ const hard = setTimeout(() => (send("SIGKILL"), child.unref()), options.grace ?? GRACE_MS);
120
+ // The leader gone and nothing left in its group: there is nothing to kill at the grace.
121
+ child.once("exit", () => (alone || child.pid === undefined || !signalGroup(child.pid, 0)) && clearTimeout(hard));
122
+ };
123
+ const timer = setTimeout(() => (ended ? byStatus(ended) : cutOff(`Command timed out after ${options.deadline} ms`, null)), options.deadline);
124
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => (stdout += chunk).length > limit && cutOff("stdout maxBuffer length exceeded", "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"));
125
+ child.stderr?.setEncoding("utf8").on("data", (chunk) => (stderr += chunk).length > limit && cutOff("stderr maxBuffer length exceeded", "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"));
126
+ child.on("error", settle); // the program could not be started; after the call has ended, a signal that could not be sent
127
+ child.once("exit", (code, signal) => (ended = { code, signal }));
128
+ child.once("close", (code, signal) => byStatus({ code, signal }));
129
+ return child;
130
+ }
131
+
72
132
  /**
73
133
  * `execFile` of a program found by `resolveExe`. A program that is gone when it is started (ENOENT: it was uninstalled or moved since the search) is searched for again once.
74
- * A program that is not found at all calls back with ExeNotFound.
134
+ * A program that is not found at all calls back with ExeNotFound. With `options.deadline` the call ends by that many ms whatever the program does (`execFileByDeadline`), which `options.timeout` does not promise.
75
135
  * @param {string} name
76
136
  * @param {string[]} args
77
- * @param {import("node:child_process").ExecFileOptions} options
78
- * @param {(error: (Error & { code?: string | number }) | null, stdout: string, stderr: string) => void} done
137
+ * @param {import("node:child_process").ExecFileOptions & { deadline?: number, grace?: number, group?: boolean }} options
138
+ * @param {(error: (Error & { code?: string | number | null }) | null, stdout: string, stderr: string) => void} done
79
139
  */
80
140
  export function execFileExe(name, args, options, done) {
81
- const env = options.env ?? process.env;
141
+ const env = options.env ?? process.env, { deadline } = options;
82
142
  /** @param {boolean} again */
83
143
  const start = (again) => {
84
144
  let file;
@@ -88,8 +148,9 @@ export function execFileExe(name, args, options, done) {
88
148
  process.nextTick(done, /** @type {Error} */ (error), "", "");
89
149
  return undefined;
90
150
  }
91
- return execFile(file, args, options, (error, stdout, stderr) => {
92
- if (error && /** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT" && again) {
151
+ /** @param {(Error & { code?: string | number | null }) | null} error @param {string | Buffer} stdout @param {string | Buffer} stderr */
152
+ const finish = (error, stdout, stderr) => {
153
+ if (error && error.code === "ENOENT" && again) {
93
154
  forgetExe(name);
94
155
  let next;
95
156
  try {
@@ -100,12 +161,14 @@ export function execFileExe(name, args, options, done) {
100
161
  if (next !== file) return void start(false);
101
162
  }
102
163
  done(error, String(stdout), String(stderr));
103
- });
164
+ };
165
+ return deadline === undefined ? execFile(file, args, options, finish) : execFileByDeadline(file, args, { ...options, deadline }, finish);
104
166
  };
105
167
  return start(true);
106
168
  }
107
169
  /**
108
- * `execFileSync` of a program found by `resolveExe`, with the same second search. Returns what execFileSync does.
170
+ * `execFileSync` of a program found by `resolveExe`, with the same second search. Returns what execFileSync does. A call with a `timeout` passes `killSignal: "SIGKILL"`: execFileSync sends the signal at
171
+ * the timeout and then waits for the program to end, so one that does not end on the default SIGTERM blocks this process for as long as it lives (todo #155).
109
172
  * @param {string} name
110
173
  * @param {string[]} args
111
174
  * @param {import("node:child_process").ExecFileSyncOptions} [options]
package/src/herdr.ts CHANGED
@@ -33,7 +33,8 @@ const START_ATTEMPTS = 20;
33
33
 
34
34
  export const herdrRun: HerdrRun = (args, timeoutMs = 5000) =>
35
35
  new Promise((resolve, reject) => {
36
- execFileExe(process.env.HERDR_BIN_PATH || "herdr", args, { timeout: timeoutMs }, (error, stdout, stderr) => {
36
+ // `deadline`, not execFile's `timeout`: the call ends by then whatever the CLI does, and a CLI cut off is ended behind it with what it started (exe.mjs; todo #155).
37
+ execFileExe(process.env.HERDR_BIN_PATH || "herdr", args, { deadline: timeoutMs }, (error, stdout, stderr) => {
37
38
  // `stderr` is what Herdr itself said (its error code first), apart from the command line the message repeats. `killed` and `signal` say the command was cut off (the timeout) before it ended: what it was doing is unknown.
38
39
  if (error) reject(Object.assign(new Error(`herdr ${args.join(" ")} failed: ${stderr.trim() || error.message}`), { stderr: stderr.trim(), code: (error as { code?: unknown }).code, killed: (error as { killed?: unknown }).killed === true, signal: (error as { signal?: unknown }).signal ?? undefined }));
39
40
  else resolve(stdout);
@@ -121,13 +122,16 @@ export async function panes(run: HerdrRun, workspace?: string): Promise<Pane[]>
121
122
  // Herdr answers one request per connection with one newline-ended frame, which may arrive in pieces (split anywhere, even inside a character).
122
123
  export const herdrCall = (socketPath = herdrSocket()): HerdrCall => (method, params, timeoutMs = 5000) =>
123
124
  new Promise((resolve, reject) => {
124
- const socket = createConnection(localEndpoint(socketPath)).setTimeout(timeoutMs), text = new StringDecoder("utf8");
125
+ const socket = createConnection(localEndpoint(socketPath)), text = new StringDecoder("utf8");
125
126
  let reply = "";
126
- const fail = (code: string, message: string) => (socket.destroy(), reject(new HerdrError(code, `herdr ${method} failed: ${code} ${message}`.trim())));
127
+ const fail = (code: string, message: string) => (clearTimeout(timer), socket.destroy(), reject(new HerdrError(code, `herdr ${method} failed: ${code} ${message}`.trim())));
128
+ // A deadline for the whole answer, not the socket's idle timeout, which every piece of a frame that never ends would renew.
129
+ const timer = setTimeout(() => fail("timeout", `no answer within ${timeoutMs} ms`), timeoutMs);
127
130
  socket.on("connect", () => socket.write(`${JSON.stringify({ id: `straw-boss-${Date.now()}`, method, params })}\n`));
128
131
  socket.on("data", (chunk) => {
129
132
  reply += text.write(chunk);
130
133
  if (!reply.includes("\n")) return;
134
+ clearTimeout(timer);
131
135
  socket.destroy();
132
136
  try {
133
137
  const { result, error } = JSON.parse(reply.split("\n")[0]!) as { result?: unknown; error?: { code?: string; message?: string } };
@@ -137,7 +141,6 @@ export const herdrCall = (socketPath = herdrSocket()): HerdrCall => (method, par
137
141
  fail("bad_frame", reply.slice(0, 200));
138
142
  }
139
143
  });
140
- socket.on("timeout", () => fail("timeout", `no answer within ${timeoutMs} ms`));
141
144
  socket.on("error", (error) => fail("socket_error", error.message));
142
145
  socket.on("close", () => fail("closed", "the connection closed before an answer"));
143
146
  });
package/src/hygiene.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { execFile } from "node:child_process";
1
+ import { execFileExe } from "./exe.mjs";
2
2
  import { existsSync } from "node:fs";
3
3
  import { isAbsolute, join, resolve } from "node:path";
4
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
@@ -60,7 +60,7 @@ export interface HygieneDeps {
60
60
  track?: (done: Promise<unknown>) => void;
61
61
  }
62
62
 
63
- const run = (file: string, args: string[], cwd: string) => new Promise<string>((resolveRun, reject) => execFile(file, args, { cwd, encoding: "utf8", timeout: 5000, maxBuffer: 1 << 24 }, (error, stdout) => (error ? reject(error) : resolveRun(stdout))));
63
+ const runGit = (cwd: string, args: string[]) => new Promise<string>((resolveRun, reject) => execFileExe("git", args, { cwd, encoding: "utf8", deadline: 5000, maxBuffer: 1 << 24 }, (error, stdout) => (error ? reject(error) : resolveRun(stdout))));
64
64
  const sanitize = (text: string) => text.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
65
65
 
66
66
  /** The owner id of a pi: its pid, with the pi-herdr-agents subagent id in front for a worker (`<id>-<pid>` is unique while the pid lives; a pid reused later has another start time). */
@@ -85,7 +85,7 @@ export function createHygiene(deps: HygieneDeps = {}) {
85
85
  const env = deps.env ?? process.env, platform = deps.platform ?? process.platform, argv = deps.argv ?? process.argv, pid = deps.pid ?? process.pid;
86
86
  const call = deps.call ?? ((request) => callServer(env, request)), now = deps.now ?? Date.now, exists = deps.exists ?? existsSync, real = deps.real ?? physical;
87
87
  const table = deps.table ?? (() => readTable()), cwdsOf = deps.cwds ?? ((pids) => readCwds(pids)), markersOf = deps.markers ?? ((pids) => readOwners(pids));
88
- const git = deps.git ?? ((cwd, args) => run("git", args, cwd)), cli = deps.cli ?? cliCommand;
88
+ const git = deps.git ?? runGit, cli = deps.cli ?? cliCommand;
89
89
  const herdr: HerdrRun = herdrRun;
90
90
  const idleShells = deps.idleShells ?? (async (workspace: string) => {
91
91
  const out: number[] = [];
package/src/lan/ca.ts CHANGED
@@ -35,7 +35,7 @@ export function localName(deps: { platform?: NodeJS.Platform; run?: (program: st
35
35
  let raw: string;
36
36
  try {
37
37
  raw = platform === "darwin"
38
- ? (deps.run ?? ((program, args) => String(execFileSyncExe(program, args, { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }))))("/usr/sbin/scutil", ["--get", "LocalHostName"])
38
+ ? (deps.run ?? ((program, args) => String(execFileSyncExe(program, args, { encoding: "utf8", timeout: 3000, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] }))))("/usr/sbin/scutil", ["--get", "LocalHostName"])
39
39
  : (deps.hostname ?? hostname)();
40
40
  } catch (error) {
41
41
  return { unreadable: error instanceof Error ? error.message : String(error) };
@@ -206,7 +206,7 @@ function shaped(value: unknown): { ca: LanCa } | { lost: CaLost } {
206
206
 
207
207
  /** Keeps the CA out of Time Machine: `tmutil addexclusion` marks the file itself, so the mark survives the rename. Only macOS has Time Machine. */
208
208
  export function timeMachineExclude(path: string, platform: NodeJS.Platform = process.platform) {
209
- if (platform === "darwin") execFileSyncExe("/usr/bin/tmutil", ["addexclusion", path], { stdio: "ignore", timeout: 10_000 });
209
+ if (platform === "darwin") execFileSyncExe("/usr/bin/tmutil", ["addexclusion", path], { stdio: "ignore", timeout: 10_000, killSignal: "SIGKILL" });
210
210
  }
211
211
  export interface WriteDeps {
212
212
  /** Called on the new temporary file after it exists (empty, mode 600) and before the key is written into it; a throw is logged and the file is still written. Default: `timeMachineExclude`. */
@@ -22,9 +22,9 @@ export interface FirewallDeps { platform?: NodeJS.Platform; execPath?: string; e
22
22
 
23
23
  const READ_MS = 60_000;
24
24
  const MAX_BUFFER = 32 * 1024 * 1024;
25
- const run: FirewallExec = (file, args, options) =>
25
+ const run: FirewallExec = (file, args, { timeout, ...options }) =>
26
26
  new Promise((resolve, reject) => {
27
- execFileExe(file, args, { ...options, encoding: "utf8", windowsHide: true, maxBuffer: MAX_BUFFER }, (error, stdout, stderr) => {
27
+ execFileExe(file, args, { ...options, deadline: timeout, encoding: "utf8", windowsHide: true, maxBuffer: MAX_BUFFER }, (error, stdout, stderr) => {
28
28
  if (!error) return resolve(stdout);
29
29
  reject(Object.assign(error, { stderr, stdout }));
30
30
  });
package/src/lanface.ts CHANGED
@@ -37,8 +37,8 @@ export const revealCommand = (paths: string[], platform: NodeJS.Platform = proce
37
37
  export const revealFiles = (paths: string[]) =>
38
38
  new Promise<void>((done, fail) => {
39
39
  const [cmd, args] = revealCommand(paths);
40
- // Explorer exits 1 after it showed the file; a missing command is the only failure worth telling.
41
- execFileExe(cmd, args, { timeout: 10_000 }, (error) => (error && (error as NodeJS.ErrnoException).code === "ENOENT" ? fail(new Error(`Could not show the files with ${cmd}`)) : done()));
40
+ // Explorer exits 1 after it showed the file; a missing command is the only failure worth telling. An opener still there after 10 s is ended alone (`group: false`): the file manager it started stays.
41
+ execFileExe(cmd, args, { deadline: 10_000, group: false }, (error) => (error && (error as NodeJS.ErrnoException).code === "ENOENT" ? fail(new Error(`Could not show the files with ${cmd}`)) : done()));
42
42
  });
43
43
 
44
44
  /** The server's CA as the overlay shows it: `pairedUnder` says a device was allowed over Wi-Fi under this very certificate. */
package/src/link/allow.ts CHANGED
@@ -102,7 +102,7 @@ export function inProject(abs: string, s: Scope): string | undefined {
102
102
  export function readTracked(project: string): Tracked {
103
103
  const files = new Set<string>(), dirs = new Set<string>([""]);
104
104
  try {
105
- const out = execFileSyncExe("git", ["-c", "core.fsmonitor=false", "-C", project, "ls-files", "-z"], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"], env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, timeout: 20_000 });
105
+ const out = execFileSyncExe("git", ["-c", "core.fsmonitor=false", "-C", project, "ls-files", "-z"], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"], env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, timeout: 20_000, killSignal: "SIGKILL" });
106
106
  for (const f of String(out).split("\0")) {
107
107
  if (!f) continue;
108
108
  files.add(f);
package/src/pairing.ts CHANGED
@@ -19,7 +19,7 @@ const CLIPBOARD = clipboardCommand();
19
19
  /** Puts text on the system clipboard (`command` is for tests). */
20
20
  export const copyText = (text: string, [cmd, ...args] = CLIPBOARD) =>
21
21
  new Promise<void>((done, fail) => {
22
- const child = execFileExe(cmd!, args, { timeout: 5_000, ...(process.platform === "win32" && cmd === CLIPBOARD[0] ? { cwd: system32() } : {}) }, (error) => (error ? fail(new Error(`Could not copy with ${cmd}: ${error.message}`)) : done()));
22
+ const child = execFileExe(cmd!, args, { deadline: 5_000, ...(process.platform === "win32" && cmd === CLIPBOARD[0] ? { cwd: system32() } : {}) }, (error) => (error ? fail(new Error(`Could not copy with ${cmd}: ${error.message}`)) : done()));
23
23
  // A missing command fails the child; its stdin then errors too (EPIPE), which unhandled would take the host pi down.
24
24
  child?.stdin?.on("error", () => {}).end(text);
25
25
  });
@@ -24,7 +24,7 @@ export interface GuardDeps {
24
24
  const cwdOfSync = (pid: number): string | undefined => {
25
25
  try {
26
26
  if (process.platform === "linux") return readlinkSync(`/proc/${pid}/cwd`).replace(/ \(deleted\)$/, "");
27
- return parseLsofCwd(String(execFileSyncExe("lsof", ["-a", "-d", "cwd", "-Fpfn", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000 }))).get(pid)?.path;
27
+ return parseLsofCwd(String(execFileSyncExe("lsof", ["-a", "-d", "cwd", "-Fpfn", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000, killSignal: "SIGKILL" }))).get(pid)?.path;
28
28
  } catch {
29
29
  return undefined;
30
30
  }
@@ -57,7 +57,7 @@ export function parsePs(text: string): Proc[] {
57
57
  /** Runs a program and gives its output; a program that exits non-zero still gives what it printed (lsof does when a pid is gone), one that prints nothing and fails throws. */
58
58
  export type Run = (file: string, args: string[]) => Promise<string>;
59
59
  export const run: Run = (file, args) => new Promise((resolve, reject) => {
60
- execFileExe(file, args, { encoding: "utf8", maxBuffer: 1 << 26, timeout: 15_000, env: { ...process.env, LC_ALL: "C", TZ: "UTC" } }, (error, stdout) => (error && !stdout ? reject(error) : resolve(stdout)));
60
+ execFileExe(file, args, { encoding: "utf8", maxBuffer: 1 << 26, deadline: 15_000, env: { ...process.env, LC_ALL: "C", TZ: "UTC" } }, (error, stdout) => (error && !stdout ? reject(error) : resolve(stdout)));
61
61
  });
62
62
 
63
63
  /** The file name behind a `/proc/<pid>/exe` link (a replaced file reads ` (deleted)`); undefined for a name with a control character, which no output may carry. */
package/src/remote.ts CHANGED
@@ -43,7 +43,7 @@ export type Verdict = { origin: string; remote: boolean; device?: string; reissu
43
43
  export type Net = "tailnet" | "lan";
44
44
 
45
45
  export const tailscale: Run = (args) =>
46
- new Promise((done, fail) => execFileExe("tailscale", args, { timeout: 15_000 }, (error, out, err) => (error ? fail(new Error((error as NodeJS.ErrnoException).code === "ENOENT" ? "Tailscale is not installed (no tailscale command on PATH)" : `tailscale ${args.join(" ")} failed: ${err.trim() || error.message}`)) : done(out))));
46
+ new Promise((done, fail) => execFileExe("tailscale", args, { deadline: 15_000 }, (error, out, err) => (error ? fail(new Error((error as NodeJS.ErrnoException).code === "ENOENT" ? "Tailscale is not installed (no tailscale command on PATH)" : `tailscale ${args.join(" ")} failed: ${err.trim() || error.message}`)) : done(out))));
47
47
  interface Status { BackendState?: string; Self?: { DNSName?: string; UserID?: number; Tags?: string[] }; User?: Record<string, { LoginName?: string }> }
48
48
  interface Serve { TCP?: Record<string, { HTTPS?: boolean }>; Web?: Record<string, { Handlers?: Record<string, { Proxy?: string }> }>; AllowFunnel?: Record<string, boolean>; Foreground?: Record<string, Serve> }
49
49
  function parse<T>(text: string, what: string): T {
@@ -16,7 +16,8 @@ import { writePrivate } from "../trainboard.ts";
16
16
  // process that claims a role it is not can, at worst, end the rides of the cars of the train it registered as (it must be that train's session by Herdr's pane record and the server's own open), or put those words in the notice of a car the tower
17
17
  // forwarded to the integrator it registered as.
18
18
  // - A per-session secret that `register` hands the pi process, once. It is defense in depth, not proof: a registration is not replaced while its process lives, the start time of the process is required, and nothing above depends on it.
19
- // The car files and notice records on disk are a display journal for the yard (they are written here, never read here). A restart starts with an empty book: what the disk holds, a train could have written.
19
+ // The car files and notice records on disk are a display journal for the yard (they are written here, never read here). A restart starts with an empty book: what the disk holds, a train could have written. So a forward made before a restart is gone, and the
20
+ // integrator's refusal says so (todo #154): for as long as such a forward would have been kept, it names the server's start and the way back, which is the fact again (the coordinator sends the slip, the tower forwards it).
20
21
 
21
22
  const KEEP_MS = 24 * 3600_000, MAX_FORWARDS = 512, MAX_FILES = 256;
22
23
  const BASE_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;
@@ -68,6 +69,8 @@ export interface BookDeps {
68
69
  /** The user's known_hosts as the server read it when it started: each check writes it for ssh to use (RR2-F002). Absent, ssh knows no host and an ssh remote cannot be checked. */
69
70
  knownHosts?: string;
70
71
  now(): number;
72
+ /** When this server started, as the refusal of a forward it does not hold tells it (todo #154); the moment the book was made when absent. */
73
+ startedAt?: number;
71
74
  look(session: string): Promise<Look | undefined>;
72
75
  /** The start time of a process, in the form `register` is given; undefined when it cannot be told. */
73
76
  startOf(pid: number): string | undefined;
@@ -196,8 +199,10 @@ export class CarBook {
196
199
  private readonly failures = new Map<string, number[]>();
197
200
  private chain: Promise<unknown> = Promise.resolve();
198
201
  private readonly d: BookDeps;
202
+ /** Since when this book holds forwards: none made before it is here, whatever the disk holds. */
203
+ private readonly since: number;
199
204
 
200
- constructor(deps: BookDeps) { this.d = deps; }
205
+ constructor(deps: BookDeps) { this.d = deps; this.since = deps.startedAt ?? deps.now(); }
201
206
 
202
207
  // ---- the display journal: written here, read by the yard, never read back (CR-F003)
203
208
 
@@ -238,6 +243,14 @@ export class CarBook {
238
243
  if (t.url && !this.remotes.has(t.project)) this.remotes.set(t.project, t.url);
239
244
  }
240
245
  trainOf(project: string, code: string): TrainRecord | undefined { return this.trains.get(`${project}/${code}`); }
246
+ /**
247
+ * What the refusal of a forward this book does not hold adds while a forward made before the server's start would still be kept (todo #154; live, 0.75.0: a slip forwarded 8 minutes before an install restarted the server could be neither received nor
248
+ * returned, and the refusal named no cause). Nothing is restored: the tower's forward to this server is the fact, so the way back is that forward again. After `KEEP_MS` no earlier forward would count, and nothing is added.
249
+ */
250
+ private restartWord(): string {
251
+ if (this.d.now() - this.since >= KEEP_MS) return "";
252
+ return ` The sb server started at ${iso(this.since)} and keeps a tower's forwards in memory only, so a forward made before that is gone with the restart: ask the car's coordinator to send its slip to the tower again (call_tower why=shared); the tower forwards it again, and then the state is set.`;
253
+ }
241
254
 
242
255
  // ---- the registration: defense in depth
243
256
 
@@ -365,8 +378,9 @@ export class CarBook {
365
378
  if (setter.role === "main") {
366
379
  // The integrator's: the slip arrived as a tower's forward to this session; the car is what that slip says, and the session that sent it to the tower is the coordinator. Nothing of the car comes from the caller.
367
380
  const sent = this.forwardOf(head, setter.session);
368
- if (!sent) throw refusal(`sb: no forward by a tower carries head ${head.slice(0, 12)} to this session: a car slip reaches the integrator only as the tower's tower_send or tower_reply with forward: (the code stamps fwd-from)`);
381
+ if (!sent) throw refusal(`sb: no forward by a tower carries head ${head.slice(0, 12)} to this session: a car slip reaches the integrator only as the tower's tower_send or tower_reply with forward: (the code stamps fwd-from).${this.restartWord()}`);
369
382
  const slip = sent.slip;
383
+ if (slip.over) throw refusal(slip.over);
370
384
  name = carFileName(slip.app, head);
371
385
  held = this.cars.get(project)?.get(name);
372
386
  file = held?.file;
@@ -28,7 +28,7 @@ export function runGit(cwd: string, args: string[], extra: Record<string, string
28
28
  // git looks for no repository above the root of the file system: the `ls-remote` of `landed` runs at that root with none to find, so no repository configuration is read.
29
29
  Object.assign(env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", GIT_CEILING_DIRECTORIES: parse(resolve(cwd)).root, ...extra });
30
30
  const isolation = ["-c", "core.fsmonitor=", "-c", "core.hooksPath=/dev/null", "-c", "protocol.ext.allow=never", "-c", "submodule.recurse=false", "--no-replace-objects"];
31
- return new Promise((resolvePromise, reject) => execFileExe("git", [...isolation, "-C", cwd, ...args], { encoding: "utf8", timeout: 60_000, env, windowsHide: true }, (error, stdout, stderr) => (error ? reject(Object.assign(error, { stderr })) : resolvePromise(String(stdout).trim()))));
31
+ return new Promise((resolvePromise, reject) => execFileExe("git", [...isolation, "-C", cwd, ...args], { encoding: "utf8", deadline: 60_000, env, windowsHide: true }, (error, stdout, stderr) => (error ? reject(Object.assign(error, { stderr })) : resolvePromise(String(stdout).trim()))));
32
32
  }
33
33
 
34
34
  const reply = (error: unknown): Reply => ({ ok: false, error: (error as Error).message });
@@ -55,6 +55,8 @@ export interface StartCars {
55
55
  slot: Slot;
56
56
  run: HerdrRun;
57
57
  now(): number;
58
+ /** When the server started: the book's refusal of a forward made before it names it (todo #154). */
59
+ startedAt?: number;
58
60
  /** The server's own intercom connection, when it is connected. */
59
61
  client(): IntercomLike | undefined;
60
62
  startOf(pid: number): string | undefined;
@@ -92,7 +94,7 @@ function knownHostsOfUser(): string {
92
94
  export function startCars(o: StartCars): Cars {
93
95
  let notices: CarNotices | undefined;
94
96
  const book = new CarBook({
95
- stateDir: o.slot.stateDir, dir: o.slot.dir, now: o.now, look: (session) => look(o, session), git: runGit, knownHosts: knownHostsOfUser(), exists: existsSync, log: o.log,
97
+ stateDir: o.slot.stateDir, dir: o.slot.dir, now: o.now, ...(o.startedAt !== undefined ? { startedAt: o.startedAt } : {}), look: (session) => look(o, session), git: runGit, knownHosts: knownHostsOfUser(), exists: existsSync, log: o.log,
96
98
  startOf: o.startOf, onChange: () => notices?.kick(), ...o.over,
97
99
  });
98
100
  notices = new CarNotices({ book, now: o.now, intercom: () => o.client(), tower: (workspace) => towerId(o.slot, workspace), log: o.log });
@@ -21,6 +21,7 @@ import type { TowerEnd } from "./towerpanel.ts";
21
21
  import { identity, type Run, switchRemote, tailscale } from "../remote.ts";
22
22
  import { createLanDevices } from "../devices.ts";
23
23
  import { createOpenings } from "../openings.ts";
24
+ import { createIntents } from "../trust/intent.ts";
24
25
  import { createSpawn } from "../spawn.ts";
25
26
  import { popBase, stashedList } from "../stash.ts";
26
27
  import { trustDir } from "../trust/files.ts";
@@ -141,7 +142,7 @@ export function createGuiHost(o: GuiHostOptions) {
141
142
  /** Set while the boss's rotation runs: the GUI commands wait for it, and the start it makes says why its token is new. */
142
143
  let rotating: Promise<unknown> | undefined;
143
144
  // Built once for this process (`lock`: one opening at a time, for every GUI this process starts): pi-intercom has no unregister, so a channel the hub registered stays, and the same hub serves the GUI again after a stop.
144
- const deploys = createDeploys(), openings = createOpenings(join(slot.stateDir, "openings.json")), lock = { busy: false }, trust = createTrustServe({ dir: trustDir(slot.stateDir), herdr: slot.herdr, world: () => cfg.world(), opening: deploys.openingOf });
145
+ const deploys = createDeploys(), openings = createOpenings(join(slot.stateDir, "openings.json")), intents = createIntents(), lock = { busy: false }, trust = createTrustServe({ dir: trustDir(slot.stateDir), herdr: slot.herdr, world: () => cfg.world(), opening: deploys.openingOf });
145
146
  // The record of answered blocks (answered.ts): one file beside paired.json, mode 600, shared by every page of this server and read again by the next.
146
147
  const answered = createAnswered(answeredFileDeps(join(dir, "answered.json")));
147
148
  const live = async (session: string) => (await o.sessions()).some((x) => x.id === session);
@@ -262,7 +263,7 @@ export function createGuiHost(o: GuiHostOptions) {
262
263
  onSaveFailed: (reason) => log.line("error", { code: "paired", text: phrase(reason, 200) }),
263
264
  onRemote: async () => void (await switchRemote(running, true, dir, ts), (remoteNote = undefined), log.line("remote-on", { how: "page" })),
264
265
  onRemoteOff: async () => void (await switchRemote(running, false, dir, ts), (remoteNote = undefined), log.line("remote-off", { why: "page" })),
265
- spawn: createSpawn({ run: cfg.run, sleep: cfg.sleep, call: cfg.call, deploys, lock, trustDir: trustDir(slot.stateDir), openings, note: (event, facts) => log.line(event, facts), live, sessionAt: async (pane) => (await sessions()).find((x) => x.herdrLocation?.paneId === pane)?.id }),
266
+ spawn: createSpawn({ run: cfg.run, sleep: cfg.sleep, call: cfg.call, deploys, lock, trustDir: trustDir(slot.stateDir), openings, intents, note: (event, facts) => log.line(event, facts), live, sessionAt: async (pane) => (await sessions()).find((x) => x.herdrLocation?.paneId === pane)?.id }),
266
267
  close: createCloser({
267
268
  run: cfg.run, sleep: cfg.sleep, me: () => id, sessions, ask: async (key, keepPane, ifStashable) => hub?.close(key, keepPane, ifStashable), check: async (key) => hub?.stashCheck(key), stateDir: slot.stateDir,
268
269
  // The tower the server runs has no pi to ask: the unit the net shows for it (a service, not a waiting one) is closed by ending the service.
@@ -437,6 +438,8 @@ export function createGuiHost(o: GuiHostOptions) {
437
438
  },
438
439
  /** The control requests that concern the GUI; undefined for any other. */
439
440
  async handle(request: Request): Promise<Reply | undefined> {
441
+ // A pane's pi asks whether this server started it for an open/base that is still starting (trust/intent.ts): answered from this process's memory, with or without a GUI.
442
+ if (request.cmd === "open-intent") return { ok: true, opened: intents.has(request.pane, request.cwd) };
440
443
  if (o.listen === false || !["gui", "gui-stop", "gui-remote", "gui-pair", "gui-rotate", "gui-view", ...LAN_CMDS].includes(request.cmd)) return undefined;
441
444
  if (closing) return { ok: false, error: "restarting" };
442
445
  // A rotation in flight is finished first: a start meanwhile would bind the ports before the old listener let go, or read the secrets that are being dropped.
@@ -114,7 +114,7 @@ export const readProcs = (platform: NodeJS.Platform = process.platform): Procs =
114
114
  const { file, args, options } = cimCommand(runId);
115
115
  execFile(file, args, options, (error, stdout) => done(error ? undefined : parseCim(String(stdout))));
116
116
  } else {
117
- execFileExe("ps", ["-A", "-ww", "-o", "pid=,ppid=,lstart=,command="], { encoding: "utf8", timeout: 5000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C", TZ: "UTC" } }, (error, stdout) => done(error ? undefined : parsePs(String(stdout), runId)));
117
+ execFileExe("ps", ["-A", "-ww", "-o", "pid=,ppid=,lstart=,command="], { encoding: "utf8", deadline: 5000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C", TZ: "UTC" } }, (error, stdout) => done(error ? undefined : parsePs(String(stdout), runId)));
118
118
  }
119
119
  } catch {
120
120
  done(undefined);
@@ -613,7 +613,7 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
613
613
  if (read.problem !== toldConfig) (toldConfig = read.problem ?? "", read.problem && recordError("config", read.problem));
614
614
  return read;
615
615
  };
616
- cars = startCars({ slot, run: cfg.run, now, client: () => (client?.isConnected() ? client : undefined), startOf, log: (event, facts) => log.line(event, facts), stops });
616
+ cars = startCars({ slot, run: cfg.run, now, startedAt, client: () => (client?.isConnected() ? client : undefined), startOf, log: (event, facts) => log.line(event, facts), stops });
617
617
  towers = createTowers({
618
618
  ally: allyPort(() => link), allows, asks, cars: cars.book,
619
619
  slot, cfg, env, connect: () => mod.connect(), log, pid, startedAt, enabled: () => towerRuns().enabled, server: serverTools,
@@ -72,7 +72,7 @@ export interface ToolHost {
72
72
  /** Whether an ask of the head tower to this tower's workspace is open (headasks.ts): a tower answers with `tower_send {head: true, inReplyTo}` only to one. */
73
73
  headAsked?(id: string): boolean;
74
74
  /** The `call_tower` event (why=shared) this run took, by its id: the code stamps its sender into a forwarded car slip (docs/specs/2026-11-07-train-workers.md §5.5). Undefined when the run took no such event. */
75
- forwardEvent?(id: string): { id: string; from: string; text: string } | undefined;
75
+ forwardEvent?(id: string): { id: string; from: string; text: string; /** When the event came in. */ at?: number } | undefined;
76
76
  /**
77
77
  * The `call_tower` messages (why=shared) this run took, oldest first, each with the sender the broker named, its own text, and the 16-hex id its forward is stamped with: a local run's events, and for an ally run
78
78
  * what local sessions said to the tower for its device (allyroute.ts). The door of an integrator's open.
@@ -87,6 +87,8 @@ export interface ToolHost {
87
87
  /** `tower_memory` of a local run (towermemory.ts): it proposes, and the boss confirms elsewhere. */
88
88
  memory(args: Record<string, unknown>): Promise<ToolResult>;
89
89
  now(): number;
90
+ /** When this server started: the refusal of a forward whose slip came in before it says what a restart lost (todo #154). */
91
+ startedAt?: number;
90
92
  }
91
93
 
92
94
  export interface SlipEvent { fwd: string; from: { id: string; name?: string }; text: string }
@@ -140,6 +142,11 @@ const ASK = /^[0-9a-f]{32}$/;
140
142
 
141
143
  /** The kept integrators the door named for a slip (`ForwardAsBefore`), by the tower and the slip's event id: a forward of that slip goes to one of them and to no other session. Kept for the server's life; the door is asked again after a restart. */
142
144
  const namedFor = new Map<string, readonly string[]>();
145
+ /**
146
+ * What the refusal of a forward the door did not name adds when the slip came in before this server started (todo #154): a run that outlived a restart holds the slip's event (the queue is on disk) but the door's answer is gone, and it is
147
+ * not read back from anywhere (a file here is one a train can write). The way back is the door again, which is the same call.
148
+ */
149
+ const restartWord = (host: ToolHost, at: number | undefined) => (host.startedAt !== undefined && at !== undefined && at < host.startedAt ? ` The sb server started at ${new Date(host.startedAt).toISOString()}, after this slip came in, and keeps the door's answer in memory only: if the door named this slip's integrators before that, its answer is gone with the restart, so ask the door again the same way and forward then.` : "");
143
150
  const PEERS_SLIP = (name: string, id: string) => `${clean(name, 40)} (session ${id}) was opened for a teammate's device, so its slip is a peer's: it reaches the integrator through the ally run of its device, which marks it origin=remote and asks the boss below dispatch, and never through a local run. Forward nothing of it; it sends the slip again to the tower that opened it.`;
144
151
 
145
152
  /**
@@ -151,10 +158,10 @@ async function forwardOf(host: ToolHost, args: Record<string, unknown>, to?: str
151
158
  const id = opt(args, "forward");
152
159
  if (id === undefined) return undefined;
153
160
  const event = host.forwardEvent?.(id);
154
- if (!event) throw new Error(`forward ${id.slice(0, 40)} is no call_tower event (why=shared) that this run took: forward a car slip with the id its event header shows`);
161
+ if (!event) throw new Error(`forward ${id.slice(0, 40)} is no call_tower event (why=shared) that this run took: forward a car slip with the id its event header shows. A slip's event is held only while the run that took it lives and for 24 h: ask its sender to send the slip to the tower again (call_tower why=shared) and forward the new event's id`);
155
162
  const net = await host.reach.read(), peers = (session: string) => deviceToken(net, session) !== undefined || (host.openedAnywhere ?? host.openedFor)?.(session) !== undefined;
156
163
  if (peers(event.from)) throw new Error(PEERS_SLIP(event.from, event.from));
157
- if (to !== undefined && !namedFor.get(`${host.identity} ${event.id}`)?.includes(to)) throw new Error(`forward ${event.id} goes only to an integrator the door named for this slip: call boss_open_main with role "integrator", the slip as the request, and its sender, and forward to one of the sessions its answer names.`);
164
+ if (to !== undefined && !namedFor.get(`${host.identity} ${event.id}`)?.includes(to)) throw new Error(`forward ${event.id} goes only to an integrator the door named for this slip: call boss_open_main with role "integrator", the slip as the request, and its sender, and forward to one of the sessions its answer names.${restartWord(host, event.at)}`);
158
165
  if (to !== undefined && peers(to)) throw new Error(`Session ${to} was opened for a teammate's device, so no slip is forwarded to it. The boss closes it or renames it.`);
159
166
  return { fwd: event.id, fwdFrom: event.from, body: bodyOf(event.text) };
160
167
  }
@@ -1112,7 +1112,7 @@ export function createTowers(o: TowersOptions): Towers {
1112
1112
  link: async (body: Record<string, unknown>) => ((await o.link?.(body, l.record.id)) ?? { ok: false, code: "no_holder", error: "The link holder is not running in the sb server" }) as { ok: boolean; error?: string },
1113
1113
  server: o.server ?? { status: () => ({}), logs: () => [], restart: () => Promise.reject(new Error("The server cannot restart itself here")) },
1114
1114
  expect: (to: string, name: string, text: string) => { if (peer) return route(to, phrase(name, 40), "expect"); try { addExpect(slot, ws, { to, name, at: now(), first: phrase(text, 80) }, now()); } catch (cause) { error("expects", (cause as Error).message); } },
1115
- who, identity: l.record.id, requests: l.requests,
1115
+ who, identity: l.record.id, requests: l.requests, startedAt: o.startedAt,
1116
1116
  allow: (q: { toolCallId: string; tool: string; args: unknown }) => (o.allows ? o.allows.take({ pane: who.pane, ...q, sessions: () => l.client!.listSessions() }) : Promise.resolve({ ok: false as const, reason: "this server holds no Allows" })),
1117
1117
  allowRequest: (q: { toolCallId: string; lines: string[] }) => (o.allows ? o.allows.takeRequest({ pane: who.pane, ...q, sessions: () => l.client!.listSessions() }) : Promise.resolve({ ok: false as const, reason: "this server holds no Allows" })),
1118
1118
  asks: o.asks ?? { open: () => { throw new Error("this server keeps no asks"); } },
@@ -1120,7 +1120,7 @@ export function createTowers(o: TowersOptions): Towers {
1120
1120
  forwardEvent: (id: string) => {
1121
1121
  const event = readQueue(slot, ws).find((e) => e.id === id && e.taken?.run === who.id && e.kind === "intercom" && e.from);
1122
1122
  const fields = event && fieldsOf(event.text);
1123
- return event && fields?.kind === "call_tower" && fields.why === "shared" ? { id: event.id, from: event.from!.id, text: event.text } : undefined;
1123
+ return event && fields?.kind === "call_tower" && fields.why === "shared" ? { id: event.id, from: event.from!.id, text: event.text, at: Date.parse(event.at) } : undefined;
1124
1124
  },
1125
1125
  // A reply that settles a blocked call_tower this run took, while auto mode is on, is listed for the return list with the basis it names (autotower.ts `basisOf`) or `none`.
1126
1126
  decided: (to: string, gist: string, basis: unknown) => {
@@ -105,7 +105,7 @@ function check(flags: Record<string, string | true>, io: TrainIo): number {
105
105
  const exists = io.exists ?? ((path: string) => existsSync(resolve(cwd, path)));
106
106
  const isAncestor = io.isAncestor ?? ((older: string, newer: string) => {
107
107
  try {
108
- execFileSyncExe("git", ["merge-base", "--is-ancestor", older, newer], { cwd, stdio: "ignore", timeout: 15_000 });
108
+ execFileSyncExe("git", ["merge-base", "--is-ancestor", older, newer], { cwd, stdio: "ignore", timeout: 15_000, killSignal: "SIGKILL" });
109
109
  return true;
110
110
  } catch {
111
111
  return false;
@@ -4,7 +4,7 @@ import { dirname, join } from "node:path";
4
4
  import { integrationOff } from "../trainswitch.ts";
5
5
  import { type BoardRead, type BoardStep, type CarRow, factsOf, readJsonFile, type ReadBudget, readTrainboards, readYard, trainboardDir, type Writer, yardPath } from "../train/board.ts";
6
6
  import { carFileName, type CarState, type CarView, noticeStatus } from "../train/cars.ts";
7
- import { isName, isObject, isoTime, SHA_RE } from "../train/spec.ts";
7
+ import { isName, isObject, isoTime, MAX_TICKET_CHARS, SHA_RE } from "../train/spec.ts";
8
8
  import { type FactStep, holding, stepWaits, type TrainFacts, type Wait, waitingTrains } from "../train/waits.ts";
9
9
  import type { NetLoad, ProjectYard, ReasonKind, YardAccepted, YardCar, YardFormingRow, YardJoin, YardNotice, Yards, YardStep, YardTrainRow } from "../train/yardview.ts";
10
10
  import { carsFolderOk, readCar } from "../trainboard.ts";
@@ -157,7 +157,7 @@ export function readYards(deps: YardDeps, join_: YardJoin): Yards | undefined {
157
157
  const carView = (row: CarRow, app: string, nods?: Map<string, Map<string, string>>): YardCar => {
158
158
  const accepted = (row.accepted ?? []).slice(0, 8).map((kind): YardAccepted => ((nod) => (nod ? { kind: clean(kind, 32), nod } : { kind: clean(kind, 32) }))(nods?.get(row.head)?.get(kind)));
159
159
  const notice = noticeOf(app, row.head);
160
- return { tickets: row.tickets.slice(0, 16).map((t) => clean(t, 64)), branch: clean(row.branch, 255), head: row.head, departs: clean(row.departs, 300), ...(row.arrived ? { arrived: row.arrived } : {}), accepted, ...(row.unverified ? { unverified: true as const } : {}), ...(notice ? { notice } : {}) };
160
+ return { tickets: row.tickets.map((t) => clean(t, MAX_TICKET_CHARS)), branch: clean(row.branch, 255), head: row.head, departs: clean(row.departs, 300), ...(row.arrived ? { arrived: row.arrived } : {}), accepted, ...(row.unverified ? { unverified: true as const } : {}), ...(notice ? { notice } : {}) };
161
161
  };
162
162
  const trainRow = (read: BoardRead, fact: TrainFacts): YardTrainRow => {
163
163
  if (!read.ok) {