crewbus 10.0.9 → 10.0.11

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.
@@ -9,6 +9,7 @@ import path from "node:path";
9
9
  import crypto from "node:crypto";
10
10
  import { readJson, writeJson, newId, fail, cleanChannelName, listJson } from "./store.js";
11
11
  import { isHigh, relTime } from "./mail.js";
12
+ import { authorizeCheck } from "./identity.js"; // member-scoped channel mirrors (C4; call-time use only — hoisted declarations tolerate the identity→groups→channels cycle)
12
13
 
13
14
  // cleanChannelName lives in store.js (canonical home for all clean* helpers).
14
15
 
@@ -103,7 +104,16 @@ export function summarizePosts(posts, limit) {
103
104
 
104
105
  export function mirrorToGroupChannels(d, { groups, from, body, subject, replyTo, batch, priority, rev, at }) {
105
106
  const mirrored = [];
107
+ const skipped = [];
106
108
  for (const g of groups || []) {
109
+ // Member-scoped mirrors (C4): a worker's brief lands on grp-<g> channel
110
+ // only if it is a member of <g> (or lead/admin). Non-members' DMs still
111
+ // deliver — the channel mirror is skipped with a visible note.
112
+ const gate = authorizeCheck(d, from, "channel-post", { channelGroup: g });
113
+ if (!gate || !gate.ok) {
114
+ skipped.push({ group: g, reason: (gate && gate.reason) || "member posting required" });
115
+ continue;
116
+ }
107
117
  const chan = groupChannelName(g);
108
118
  const post = { id: newId("ch"), from, body, at };
109
119
  if (subject) post.subject = subject;
@@ -114,7 +124,7 @@ export function mirrorToGroupChannels(d, { groups, from, body, subject, replyTo,
114
124
  appendChannelPost(d, chan, post);
115
125
  mirrored.push({ group: g, channel: chan, id: post.id });
116
126
  }
117
- return mirrored;
127
+ return { mirrored, skipped };
118
128
  }
119
129
 
120
130
  export function lockHash(scope) {
@@ -175,6 +175,8 @@ export function checkToken(d, agent, token) { // line 361
175
175
  // as register, zero extra round-trip). Returns { created } so callers can
176
176
  // print the token exactly once — it is never shown again via send.
177
177
  export function ensureSender(d, agent, token) { // line 387
178
+ const sentinel = reservedNameReason(agent);
179
+ if (sentinel) fail(sentinel);
178
180
  const rec = readAgent(d, agent);
179
181
  if (!rec) {
180
182
  if (isBoardFrozen(d)) fail(`board is frozen — new registrations refused (ask an admin to register --from <admin> --for ${agent})`);
@@ -228,6 +230,128 @@ export function ensureSender(d, agent, token) { // line 387
228
230
  return { created: false };
229
231
  }
230
232
 
233
+ // ---------------------------------------------------------------------------
234
+ // Identity recovery (C1): an agent that survives compaction/restart amnesia
235
+ // loses its name. The compaction hooks rehydrate from a session map; when
236
+ // even that is lost the harness texts used to mint throwaway identities
237
+ // (logs/unknown.token) that nobody owns. Two fixes: reserved sentinel names
238
+ // never mint, and a read-only recovery cross-check finds the real identity
239
+ // from what the board still knows.
240
+ // ---------------------------------------------------------------------------
241
+
242
+ // Scan logs/<name>.token: { name -> token | null } (best-effort; a missing
243
+ // or unreadable file is just "no evidence").
244
+ function listTokenFiles(d) {
245
+ const out = new Map();
246
+ try {
247
+ for (const f of fs.readdirSync(path.join(d.root, "logs"))) {
248
+ const m = /^([A-Za-z0-9_-]+)\.token$/.exec(f);
249
+ if (!m) continue;
250
+ try {
251
+ const t = fs.readFileSync(path.join(d.root, "logs", f), "utf8").trim();
252
+ if (t) out.set(m[1], t);
253
+ } catch {}
254
+ }
255
+ } catch {}
256
+ return out;
257
+ }
258
+
259
+ // { name, role, sessionId, lastDir, lastSeen, tokenHash, salt } for the scan.
260
+ function findAgentRecords(d) {
261
+ const records = [];
262
+ try {
263
+ for (const f of fs.readdirSync(d.agents)) {
264
+ if (!f.endsWith(".json")) continue;
265
+ try {
266
+ const doc = readJson(path.join(d.agents, f));
267
+ if (!doc || !doc.name || doc.offboarded) continue;
268
+ records.push({
269
+ name: String(doc.name),
270
+ role: roleOfRecord(doc),
271
+ sessionId: doc.sessionId || undefined,
272
+ lastDir: doc.lastDir || undefined,
273
+ lastSeen: doc.lastSeen || undefined,
274
+ tokenHash: doc.tokenHash || undefined,
275
+ salt: doc.salt || undefined,
276
+ });
277
+ } catch {}
278
+ }
279
+ } catch {}
280
+ return records;
281
+ }
282
+
283
+ // Rank identity candidates for an amnesiac agent. Read-only, never throws.
284
+ // opts: { sessionID, cwd, hashToken?, loadTokenFile? } (injectors let the
285
+ // CLI do the token-file↔tokenHash cross-check; plugin copies ship a lite
286
+ // variant without hash-verify).
287
+ // Returns [{ name, role, score, proven, why }] best-first.
288
+ export function recoverIdentity(d, opts = {}) {
289
+ const records = findAgentRecords(d);
290
+ const tokens = listTokenFiles(d);
291
+ const cwd = opts.cwd ? String(opts.cwd) : undefined;
292
+ const sessionID = opts.sessionID ? String(opts.sessionID) : undefined;
293
+ const canVerify = typeof opts.hashToken === "function" && typeof opts.loadTokenFile === "function";
294
+ const cands = [];
295
+ for (const rec of records) {
296
+ let score = 0;
297
+ let proven = false;
298
+ const why = [];
299
+ // Register-time session binding (register --session <id>) is the
300
+ // strongest cross-check: it names THIS harness session explicitly.
301
+ if (sessionID && rec.sessionId && rec.sessionId === sessionID) {
302
+ score += 4;
303
+ why.push("session id matches register binding");
304
+ }
305
+ // Token-file evidence: existence is a hint; a real cross-check against
306
+ // the stored hash is proof (hashToken(token, salt) === tokenHash).
307
+ if (tokens.has(rec.name)) {
308
+ score += 1;
309
+ why.push("token file exists for this name");
310
+ if (canVerify && rec.tokenHash && rec.salt) {
311
+ try {
312
+ const t = opts.loadTokenFile(d.root, rec.name);
313
+ if (t && opts.hashToken(t, rec.salt) === rec.tokenHash) {
314
+ proven = true;
315
+ score += 3;
316
+ why.push("token file cross-checks the stored hash");
317
+ }
318
+ } catch {}
319
+ }
320
+ }
321
+ if (cwd && rec.lastDir && arePathsSameDir(rec.lastDir, cwd)) {
322
+ score += 1;
323
+ why.push("worked from this directory");
324
+ }
325
+ if (score <= 0) continue;
326
+ cands.push({ name: rec.name, role: rec.role, score, proven, why: why.join("; ") });
327
+ }
328
+ cands.sort((a, b) => b.score - a.score || String(a.name).localeCompare(String(b.name)));
329
+ return cands;
330
+ }
331
+
332
+ // Case-insensitive directory comparison for Windows case-insensitivity +
333
+ // symlink noise tolerance (best-effort: trailing slashes, backslashes).
334
+ function arePathsSameDir(a, b) {
335
+ const norm = (p) => String(p).replace(/[\\/]+$/, "").toLowerCase();
336
+ if (norm(a) === norm(b)) return true;
337
+ // Partial tolerance: a registered cwd may be a subpath of the board root.
338
+ const aN = norm(a).split(/[\\/]/);
339
+ const bN = norm(b).split(/[\\/]/);
340
+ return aN.length !== bN.length && (aN.join("/").includes(bN.join("/")) || bN.join("/").includes(aN.join("/")));
341
+ }
342
+
343
+ // Reserved sentinel names never mint — they come from amnesia bugs, and
344
+ // minting them loses real identity data forever (the 10.0.9-run "lead"
345
+ // lockout came from exactly this).
346
+ export const RESERVED_SENTINELS = ["unknown", "me", "you"];
347
+
348
+ export function reservedNameReason(agent) {
349
+ const s = String(agent || "").trim().toLowerCase();
350
+ return RESERVED_SENTINELS.includes(s)
351
+ ? `"${agent}" is a reserved sentinel name (amnesia-throwaway) — identity lost? run: crewbus recover, then re-register/claim your real name`
352
+ : null;
353
+ }
354
+
231
355
  // ---------------------------------------------------------------------------
232
356
  // Phase 1b RBAC + per-board ACLs + group-scoped send permissions.
233
357
  //
@@ -329,7 +453,7 @@ export function authorizeCheck(d, agent, action, scope) { // line 537
329
453
  const role = getRole(d, agent);
330
454
  const act = String(action || "");
331
455
  const ADMIN_ONLY = new Set(["prune", "acl-set", "role-grant", "offboard", "group-restrict", "serve-remote", "import", "snapshot-schedule", "quota-set", "hold-place", "hold-lift", "pairing"]);
332
- const LEAD_PLUS = new Set(["spawn", "respawn", "pool", "group-manage", "channel-post", "result-record", "race-close"]);
456
+ const LEAD_PLUS = new Set(["spawn", "respawn", "pool", "group-manage", "result-record", "race-close"]);
333
457
  const WORKER_WRITES = new Set(["send", "ack", "redeliver", "lock", "artifact-write", "lesson-write"]);
334
458
  const EXPORT_ROLES = new Set(["admin", "auditor"]);
335
459
  if (act === "export") {
@@ -340,6 +464,26 @@ export function authorizeCheck(d, agent, action, scope) { // line 537
340
464
  return { ok: false, reason: `role "${role}" cannot ${act} (need admin)` };
341
465
  } else if (LEAD_PLUS.has(act)) {
342
466
  if (role !== "lead") return { ok: false, reason: `role "${role}" cannot ${act} (need lead|admin)` };
467
+ } else if (act === "channel-post") {
468
+ // Member-scoped channel posting (C4, default-on): workers may post to the
469
+ // channels of groups they are a MEMBER of (scope.channelGroup); lead/admin
470
+ // post anywhere (board channels + every group channel). Everyone else,
471
+ // and workers targeting a foreign group's channel or a board channel with
472
+ // no member mapping, are refused.
473
+ if (role === "admin" || role === "lead") {
474
+ // board-wide + group channels
475
+ } else if (role !== "worker") {
476
+ return { ok: false, reason: `role "${role}" cannot ${act} (member-posting is scoped to group members; need lead|admin)` };
477
+ } else {
478
+ const targetGroup = scope && scope.channelGroup ? String(scope.channelGroup) : undefined;
479
+ if (!targetGroup) {
480
+ return { ok: false, reason: `role "worker" may post only to a group channel it belongs to (${targetGroup === undefined ? "board channels are lead|admin" : "need lead|admin"})` };
481
+ }
482
+ const gdoc = readGroup(d, targetGroup);
483
+ if (!gdoc) return { ok: false, reason: `channel group "${targetGroup}" not found (groups register their channels — board channels are lead|admin)` };
484
+ const members = Array.isArray(gdoc.members) ? gdoc.members : [];
485
+ if (!members.includes(agent)) return { ok: false, reason: `group channel "${targetGroup}" — members only (member or lead|admin)` };
486
+ }
343
487
  } else if (act === "spawn-kill") {
344
488
  if (role !== "lead") return { ok: false, reason: `role "${role}" cannot spawn-kill (need lead|admin)` };
345
489
  const targets = (scope && Array.isArray(scope.targets)) ? scope.targets : [];
@@ -405,26 +549,32 @@ export function mergeAgentDoc(prev, patch) {
405
549
  }
406
550
 
407
551
  // Loopback operator auto-provision (desktop plug-and-play):
408
- // `serve`/`web` on 127.0.0.1 auto-creates a `lead` identity on first boot so
552
+ // `serve`/`web` on 127.0.0.1 auto-creates an operator identity on first boot so
409
553
  // the dashboard can launch without any terminal step. First agent on the
410
554
  // board becomes admin (see defaultRoleForNew), so this is the board owner.
411
- // CLI boards are untouched: this only fires when `lead` is missing AND the
555
+ // Under the 3-lane model (boss / lead / peers), fresh boards mint `boss` as the
556
+ // desktop human operator, allowing crew bursts to auto-provision `lead` as the
557
+ // autonomous coordinator. Existing boards that already claimed `lead` (or `boss`)
558
+ // are kept without disruption.
559
+ // CLI boards are untouched: this only fires when operator is missing AND the
412
560
  // bind is loopback. Returns { from, token } or null when not applicable.
413
561
  export function ensureLoopbackOperator(d, host) {
414
562
  const loop = String(host || "127.0.0.1");
415
563
  if (loop !== "127.0.0.1" && loop !== "localhost" && loop !== "::1") return null;
416
- let rec = null;
417
- try { rec = readAgent(d, "lead"); } catch { rec = null; }
418
- if (rec && (rec.tokenHash || rec.token)) return null; // already provisioned
564
+ let recBoss = null, recLead = null;
565
+ try { recBoss = readAgent(d, "boss"); } catch { recBoss = null; }
566
+ try { recLead = readAgent(d, "lead"); } catch { recLead = null; }
567
+ if (recBoss && (recBoss.tokenHash || recBoss.token)) return null; // already provisioned
568
+ if (recLead && (recLead.tokenHash || recLead.token)) return null; // already provisioned (legacy board)
419
569
  if (countAgentRecords(d) > 0) return null; // board already has registered agents
420
570
  const fresh = mintToken();
421
571
  const salt = newSalt();
422
572
  const now = new Date().toISOString();
423
573
  let prev = null;
424
- try { prev = readJson(path.join(d.agents, "lead.json")); } catch { prev = null; }
574
+ try { prev = readJson(path.join(d.agents, "boss.json")); } catch { prev = null; }
425
575
  const { v, hlc } = stampSyncDoc(prev);
426
576
  const doc = mergeAgentDoc(prev, {
427
- name: "lead",
577
+ name: "boss",
428
578
  firstSeen: (prev && prev.firstSeen) || now,
429
579
  lastSeen: now,
430
580
  tokenHash: hashToken(fresh, salt),
@@ -438,9 +588,9 @@ export function ensureLoopbackOperator(d, host) {
438
588
  let won = false;
439
589
  try {
440
590
  if (!prev) {
441
- won = writeExclusiveJson(path.join(d.agents, "lead.json"), doc);
591
+ won = writeExclusiveJson(path.join(d.agents, "boss.json"), doc);
442
592
  } else {
443
- writeAgentFile(d, "lead", doc);
593
+ writeAgentFile(d, "boss", doc);
444
594
  won = true;
445
595
  }
446
596
  } catch { won = false; }
@@ -449,14 +599,14 @@ export function ensureLoopbackOperator(d, host) {
449
599
  return null;
450
600
  }
451
601
  if (won) {
452
- try { chmodAgentFile(path.join(d.agents, "lead.json")); } catch {}
602
+ try { chmodAgentFile(path.join(d.agents, "boss.json")); } catch {}
453
603
  try {
454
604
  fs.mkdirSync(path.join(d.root, "logs"), { recursive: true });
455
- fs.writeFileSync(path.join(d.root, "logs", "lead.token"), fresh + "\n", "utf8");
456
- try { fs.chmodSync(path.join(d.root, "logs", "lead.token"), 0o600); } catch {}
605
+ fs.writeFileSync(path.join(d.root, "logs", "boss.token"), fresh + "\n", "utf8");
606
+ try { fs.chmodSync(path.join(d.root, "logs", "boss.token"), 0o600); } catch {}
457
607
  } catch {}
458
608
  }
459
- return won ? { from: "lead", token: fresh } : null;
609
+ return won ? { from: "boss", token: fresh } : null;
460
610
  }
461
611
 
462
612
  export function touchAgent(d, name, extra) { // line 2647
@@ -0,0 +1,92 @@
1
+ // bin/lib/kidproc.js — shell-mode child processes without DEP0190.
2
+ //
3
+ // Node >=22 deprecates `spawn(exe, args, { shell: true })` when `args` is
4
+ // non-empty (DEP0190) — args are passed through the shell UNESCAPED (the
5
+ // warning exists because the old wire is unsafe: `"arg one"` emitted raw
6
+ // splits into two argv tokens on the receiving process). This module
7
+ // reproduces the intended semantics with CORRECT quoting:
8
+ //
9
+ // Windows old: spawn(exe, args, { shell:true }) (unescaped raw concat)
10
+ // new: spawn("cmd.exe", ["/d","/s","/c", quoted line],
11
+ // { windowsVerbatimArguments: true })
12
+ // POSIX old: spawn(exe, args, { shell:true })
13
+ // new: spawn("/bin/sh", ["-c", quoted line], { shell:false })
14
+ //
15
+ // (On win32 `windowsVerbatimArguments` matters: without it node re-quotes the
16
+ // already-quoted outer string and cmd would double-parse the escapes.)
17
+ //
18
+ // NOTE: this is intentionally NOT bit-identical to the deprecated wire —
19
+ // the old wire mangled args (space splitting, quote eating) and let bare
20
+ // cmd metacharacters (& | ^) inject into the command line. The regression
21
+ // bar here is argv IDENTITY: what the child receives equals what the
22
+ // caller passed. Known cmd limitation documented here: a matched %VAR%
23
+ // pattern inside a quoted token still expands at the cmd layer (no escape
24
+ // exists for cmd quoted context) — unmatched % passes through intact.
25
+ // Standalone by design (see docs/SPLIT.md): zero local imports, cycle-free.
26
+ // Escape hatch for exactly one release: CREWBUS_SHELL_LEGACY=1 restores the
27
+ // pre-refactor `shell: true` behavior at call sites.
28
+
29
+ const WIN_SHELL = "cmd.exe";
30
+ const POSIX_SHELL = "/bin/sh";
31
+
32
+ // MS CRT / CreateProcess argument quoting, plus the cmd.exe pass layer:
33
+ // wrap on whitespace, quotes, AND cmd metacharacters (& | ^ < > %) — bare
34
+ // metachars split commands even inside the overall quoted /c line (probes:
35
+ // "a&b|c^d" quoted argv arrives intact; bare flexes). Inside the wrap:
36
+ // backslashes double before quotes per MS standard, % stays raw (cmd does
37
+ // NOT expand unmatched %; a matched %VAR% *does* expand even inside quotes —
38
+ // a known cmd limitation, no escape hatch exists — see docs note), ^ is
39
+ // literal inside quotes. Bare tokens without any of those pass unwrapped
40
+ // (already valid single argv tokens).
41
+ function msQuote(s) {
42
+ s = String(s);
43
+ if (s === "") return '""';
44
+ if (!/[\s"&|^<>%]/.test(s)) return s;
45
+ let out = '"';
46
+ let backslashes = 0;
47
+ for (const c of s) {
48
+ if (c === "\\") { backslashes++; continue; }
49
+ if (c === '"') {
50
+ out += "\\".repeat(backslashes * 2 + 1) + '"';
51
+ } else {
52
+ out += "\\".repeat(backslashes) + c;
53
+ }
54
+ backslashes = 0;
55
+ }
56
+ // Backslashes before the closing wrap double up too.
57
+ out += "\\".repeat(backslashes * 2);
58
+ return out + '"';
59
+ }
60
+
61
+ // POSIX single-quote joining (' -> '\'').
62
+ function shQuote(s) {
63
+ s = String(s);
64
+ // A bare empty token would vanish outright (two words `a ''` parse to
65
+ // [a, ""] — `a ` parses to [a] only), losing the operand.
66
+ // (note: `;` is deliberately NOT in the safe class — POSIX shells treat a
67
+ // bare `;` as a command separator; cmd tolerates it. cmd metacharacters
68
+ // (& | ^ < > %) never appear here — msQuote owns the win line.)
69
+ if (s === "") return "''";
70
+ return /^[-#%+,.:=?@_a-zA-Z0-9\/]*$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
71
+ }
72
+
73
+ // { exe, args } one should hand to spawn(..., { shell: false }) to keep the
74
+ // old shell:true semantics for (exe, args). Returns null when args is empty
75
+ // — callers keep their existing behavior in that case (empty args never hit
76
+ // DEP0190).
77
+ function shellChildSpec(exe, args, platform = process.platform) {
78
+ const a = (args || []).map(String);
79
+ if (a.length === 0) return null;
80
+ const line = [String(exe), ...a];
81
+ if (platform === "win32") {
82
+ return { exe: WIN_SHELL, args: ["/d", "/s", "/c", `"${line.map(msQuote).join(" ")}"`] };
83
+ }
84
+ return { exe: POSIX_SHELL, args: ["-c", line.map(shQuote).join(" ")] };
85
+ }
86
+
87
+ // Spawn-time options a caller must add when using shellChildSpec output.
88
+ function shellChildOptions(platform = process.platform) {
89
+ return platform === "win32" ? { windowsVerbatimArguments: true } : {};
90
+ }
91
+
92
+ export { msQuote, shQuote, shellChildSpec, shellChildOptions };
package/bin/lib/launch.js CHANGED
@@ -6,6 +6,7 @@
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { execFileSync } from "node:child_process";
9
+ import { shellChildSpec, shellChildOptions } from "./kidproc.js";
9
10
 
10
11
  export const LAUNCH_PERMISSIONS = ["supervised", "autoEdits", "auto", "full"];
11
12
  export const LAUNCH_LIFETIMES = ["oneshot", "persistent"];
@@ -42,14 +43,18 @@ export function launchDrivers() {
42
43
 
43
44
  // Probe one binary for presence + version. Never throws: missing binaries
44
45
  // report { found: false } ("not installed", not failure).
45
- // On Windows, global npm CLIs are batch scripts (.cmd) which require shell: true.
46
+ // On Windows, global npm CLIs are batch scripts (.cmd) which require a shell;
47
+ // the legacy spawn(exe, args, {shell:true}) shape is DEP0190 on modern Node —
48
+ // run cmd.exe as an explicit argv0 with the same wire format (bin/lib/kidproc.js).
46
49
  export function probeBinary(binary, probeArgs) {
47
50
  if (!binary) return { found: false, version: null, detail: "operator-supplied --cmd" };
48
51
  try {
49
52
  const isWin = process.platform === "win32";
50
- const out = execFileSync(binary, probeArgs && probeArgs.length > 0 ? probeArgs : ["--version"], {
51
- stdio: ["ignore", "pipe", "pipe"], timeout: 8000, shell: isWin,
52
- });
53
+ const args = probeArgs && probeArgs.length > 0 ? probeArgs : ["--version"];
54
+ const spec = isWin ? shellChildSpec(binary, args) : { exe: binary, args };
55
+ const opts = { stdio: ["ignore", "pipe", "pipe"], timeout: 8000 };
56
+ if (isWin) Object.assign(opts, shellChildOptions());
57
+ const out = execFileSync(spec.exe, spec.args, opts);
53
58
  const first = String(out || "").split("\n")[0].trim().slice(0, 80);
54
59
  return { found: true, version: first || "installed", detail: null };
55
60
  } catch (e) {
@@ -276,6 +281,9 @@ export function validateLaunchPlan(raw) {
276
281
  const model = r.model === undefined || r.model === null || String(r.model).trim() === "" ? undefined : String(r.model).trim();
277
282
  if (model && model.length > 100) errors.push("model name too long (max 100 chars)");
278
283
 
284
+ const lead = r.lead === undefined || r.lead === null || String(r.lead).trim() === "" ? "auto" : String(r.lead).trim().toLowerCase();
285
+ if (!["auto", "board", "none"].includes(lead)) errors.push(`bad lead mode "${r.lead}" (want auto|board|none)`);
286
+
279
287
  const plan = {
280
288
  harness, harnesses: harnesses.length > 0 ? harnesses : ["generic"],
281
289
  model, body, count: Number.isInteger(count) && count > 0 ? count : 1,
@@ -285,7 +293,7 @@ export function validateLaunchPlan(raw) {
285
293
  priority: r.priority === undefined ? undefined : String(r.priority),
286
294
  maxTurns: r.maxTurns === undefined ? undefined : String(r.maxTurns),
287
295
  allowTools: r.allowTools === undefined ? undefined : String(r.allowTools),
288
- permission, lifetime,
296
+ permission, lifetime, lead,
289
297
  isolate: !!r.isolate, worktree: r.worktree, branch: r.branch,
290
298
  budgetTokens: r.budgetTokens, budgetMinutes: r.budgetMinutes, timeout: r.timeout,
291
299
  target: r.target === undefined ? "local" : r.target,
package/bin/lib/relay.js CHANGED
@@ -42,7 +42,7 @@ import https from "node:https";
42
42
  import { readJson, writeJson, listJson, getFlag, cleanWebName, gitRevForBoard, MAX_BODY_CHARS, MAX_FWD_DEPTH, webErr } from "./store.js";
43
43
  import { readAgent, agentTokenMatches, mintToken, newSalt, hashToken, timingSafeEqualStr, writeAgentFile, isBoardFrozen, defaultRoleForNew, authorizeThrow, authorizeCheck, touchAgent } from "./identity.js";
44
44
  import { httpJson } from "./sync.js";
45
- import { killWorkers, pidAlive, bootWorker, parseAllowEnv } from "./spawn.js";
45
+ import { killWorkers, pidAlive, bootWorker, parseAllowEnv, isPidStale } from "./spawn.js";
46
46
  import { expandGroups, heuristicSenderType } from "./groups.js";
47
47
  import { deliverDMs, findMessageById } from "./mail.js";
48
48
  import { appendChainRecord } from "./export.js";
@@ -176,7 +176,9 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
176
176
  if (recipients.length > maxSpawn) throw webErr(400, `spawn caps at ${maxSpawn} workers per call (got ${recipients.length})`);
177
177
  for (const name of recipients) {
178
178
  const rec = readAgent(d, name);
179
- if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid)) {
179
+ // Stale-pid guard (C2): pid reuse after a reboot is "not live" for spawn
180
+ // purposes — a different process recycled the pid, the worker is gone.
181
+ if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt)) {
180
182
  throw webErr(400, `name "${name}" has a live worker (pid ${rec.spawnedPid})`);
181
183
  }
182
184
  }