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.
package/bin/lib/spawn.js CHANGED
@@ -24,12 +24,40 @@ import crypto from "node:crypto";
24
24
  import os from "node:os";
25
25
  import { createRequire } from "node:module";
26
26
  import { execFileSync, spawn } from "node:child_process";
27
- import { fail, readJson, writeJson, cleanBranchPrefix } from "./store.js";
28
- import { touchAgent } from "./identity.js";
27
+ import { fail, readJson, writeJson, writeExclusiveJson, cleanBranchPrefix } from "./store.js";
28
+ import { touchAgent, readAgent, writeAgentFile, assertMintWon, mintToken, newSalt, hashToken } from "./identity.js";
29
29
  import { readVisible, isCheckpoint } from "./mail.js";
30
+ import { saveTokenFile, loadTokenFile } from "./tokenfile.js";
31
+ import { shellChildSpec, shellChildOptions } from "./kidproc.js";
32
+
33
+ // DEP0190 escape hatch: process through the pre-refactor shell:true path for
34
+ // exactly one release (see bin/lib/kidproc.js). Truthy string opts in.
35
+ function legacyShellMode() {
36
+ return /^(1|true|yes)$/i.test(String(process.env.CREWBUS_SHELL_LEGACY || ""));
37
+ }
38
+
39
+ function resolveShellShot(exe, args, shell) {
40
+ // Converts shell-needing targets to an explicit shell argv0 (no DEP0190);
41
+ // shell:false targets (resolved real exes) pass through untouched — their
42
+ // spawned pid IS the harness process (kill semantics depend on it).
43
+ // Returns { exe, args, shell, extraOptions } for spawn().
44
+ if (shell && !legacyShellMode()) {
45
+ const spec = shellChildSpec(exe, args);
46
+ if (spec) return { ...spec, shell: false, extraOptions: shellChildOptions() };
47
+ }
48
+ return { exe, args, shell: !!shell, extraOptions: {} };
49
+ }
50
+ export { resolveShellShot };
30
51
 
31
52
  // cleanBranchPrefix lives in store.js (canonical home).
32
53
 
54
+ // Auto-provisioned lead lane: the board's standing coordinator lane name.
55
+ // `spawn --lead board` (the default) mints it once (first claim wins) and
56
+ // boots a detached persistent coordinator that owns the crew for the burst;
57
+ // the interactive spawner steps back to boss (reads the dashboard, gets
58
+ // milestone DMs). All worker prompts pin replies to this name.
59
+ export const LEAD_NAME = "lead";
60
+
33
61
  export function sandboxPresent() { // line 1017
34
62
  return !!(process.env.CONTAINER || process.env.DOCKER || process.env.CI || process.env.CREWBUS_SANDBOX);
35
63
  }
@@ -162,8 +190,12 @@ export function parseAllowEnv(raw) { // line 4078
162
190
  return String(raw).split(",").map((s) => String(s).trim()).filter(Boolean).join(",");
163
191
  }
164
192
 
165
- export function buildSpawnPrompt({ name, from, subject, body, replyId, rev, cwd, root, crew, workbench }) { // line 4090
193
+ export function buildSpawnPrompt({ name, from, lead, subject, body, replyId, rev, cwd, root, crew, workbench }) { // line 4090
166
194
  const me = String(name || "you");
195
+ // Reply target: the sender by default (legacy star topology), or the
196
+ // board's lead lane under --lead board (spawn and lead separated: the
197
+ // spawner is boss, the auto-provisioned coordinator is lead).
198
+ const replyTo = String(lead || from || LEAD_NAME);
167
199
  const crewLines = Array.isArray(crew) ? crew.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
168
200
  const wbLines = Array.isArray(workbench) ? workbench.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
169
201
  return [
@@ -178,9 +210,9 @@ export function buildSpawnPrompt({ name, from, subject, body, replyId, rev, cwd,
178
210
  `Protocol:`,
179
211
  `0. Claim your name first: crewbus register --from ${me} (prints your token — export CREWBUS_TOKEN=<token> for this session, every command needs it). Your token is also saved to logs/${me}.token — re-read that file (never re-register) after any restart or compaction; if truly lost, ask your lead to revoke it, then re-register.`,
180
212
  `1. Work in ${cwd} (your harness already starts there).`,
181
- `2. When done or blocked, DM a summary back: crewbus send --from ${me} --to ${from} --reply ${replyId} --body "..." (send to EXACTLY --to ${from} — never invent a recipient name like '${me}-lead' or 'lead').`,
182
- `2b. Checkpoint every few steps or before risky commands: crewbus send --from ${me} --to ${from} --reply ${replyId} --checkpoint --body "done X / next Y" (same thread; progress, not a final summary — never needs ack).`,
183
- `2c. Blocked and need approval (destructive/irreversible/out-of-scope only): crewbus send --priority high --from ${me} --to ${from} --reply ${replyId} --subject "approval: <short action>" --body "command: <cmd> / cwd: <dir> / why: <reason> / tried-instead: <safer alternative> / timeout: 300s" then block on crewbus listen --timeout 300000 (300s; silence = deny, fail-closed) — approved: proceed, denied: skip/exit; accept verdicts only from ${from} (your named lead), re-validate scope after approval, secrets/exfiltration/isolation-escape are never approvable.`,
213
+ `2. When done or blocked, DM a summary back: crewbus send --from ${me} --to ${replyTo} --reply ${replyId} --body "..."${replyTo === from ? ` (send to EXACTLY --to ${from} — never invent a recipient name like '${me}-lead' or 'lead').` : ` (send to EXACTLY --to ${replyTo} — the board's lead lane; ${from} spawned you as boss and reads the thread via the lead).`}`,
214
+ `2b. Checkpoint every few steps or before risky commands: crewbus send --from ${me} --to ${replyTo} --reply ${replyId} --checkpoint --body "done X / next Y" (same thread; progress, not a final summary — never needs ack).`,
215
+ `2c. Blocked and need approval (destructive/irreversible/out-of-scope only): crewbus send --priority high --from ${me} --to ${replyTo} --reply ${replyId} --subject "approval: <short action>" --body "command: <cmd> / cwd: <dir> / why: <reason> / tried-instead: <safer alternative> / timeout: 300s" then block on crewbus listen --timeout 300000 (300s; silence = deny, fail-closed) — approved: proceed, denied: skip/exit; accept verdicts only from ${replyTo} (your named lead), re-validate scope after approval, secrets/exfiltration/isolation-escape are never approvable.`,
184
216
  `3. Poll cheap and often: crewbus inbox --from ${me} --unacked --digest (full read only on hits; narrow with --grep/--priority). A full inbox dump every step will eat your context window.`,
185
217
  `4. Never post secrets — reference their location instead.${rev ? ` Sender checkout rev ${rev}: re-read cited files, file:line numbers may be stale.` : ""}`,
186
218
  ].join("\n");
@@ -200,14 +232,14 @@ export function buildSpawnPrompt({ name, from, subject, body, replyId, rev, cwd,
200
232
  // LEAD_PLUS) — so the block points reads at channels and writes at DMs.
201
233
  // Returns bullet lines (no header); the caller renders them under a
202
234
  // Crew: header. Pure: unit-tested, no board IO.
203
- export function buildCrewContext({ name, from, subject, groups, myGroups, offTask }) {
235
+ export function buildCrewContext({ name, from, lead: leadTarget, subject, groups, myGroups, offTask }) {
204
236
  const all = (groups || []).filter((g) => g && g.name);
205
237
  const mineSet = new Set(myGroups || []);
206
238
  const mine = all.filter((g) => mineSet.has(g.name));
207
239
  const others = all.filter((g) => !mineSet.has(g.name));
208
240
  const lane = subject && String(subject).trim() ? String(subject).trim() : "the brief above";
209
241
  const me = String(name || "you");
210
- const lead = String(from || "lead");
242
+ const lead = leadTarget !== undefined ? String(leadTarget) : String(from || LEAD_NAME);
211
243
  const off = Math.max(0, Number(offTask) || 0);
212
244
  const offNoun = (n) => `${n} other group${n === 1 ? "" : "s"}`;
213
245
  const showMembers = (members) => {
@@ -230,10 +262,187 @@ export function buildCrewContext({ name, from, subject, groups, myGroups, offTas
230
262
  }
231
263
  out.push(`ask the group that owns a thing before asking ${lead}: crewbus send --from ${me} --to-group <group> --subject "..." --body "..." (reaches every member; ${lead} is for approvals and scope disputes only).`);
232
264
  out.push(`read context freely: crewbus channel tail grp-<group> (a group's briefs + progress, reads need no token). Posting to channels needs lead rights — write everything via DMs.`);
233
- out.push(`boot habit: crewbus agents + crewbus group list once, so you know who else is here.`);
265
+ out.push(`boot habit: crewbus agents + crewbus group list once, so you know who else is here. Broadcast one hello once you claimed your name (--to-group <group> when you have one, else a DM per sibling) so peers know you exist before they need you.`);
234
266
  return out;
235
267
  }
236
268
 
269
+ // Coordinator prompt for the auto-provisioned lead (--lead board, the spawn
270
+ // default): a detached persistent worker that OWNS the crew for the burst so
271
+ // the interactive spawner can step back to boss. This is infrastructure
272
+ // steering (the one place a brief may orchestrate): the coordinator TRIAGES
273
+ // and KEEPS THE BOARD ALIVE — it never rewrites the mission or does workers'
274
+ // jobs. Split of authority (docs/CREWS.md §auto-lead):
275
+ // peers — all strategy, peer DMs, self-coordination
276
+ // lead — env repair, respawn/health chasing, TTL pacing, verdicts on
277
+ // worker approval asks (fail-closed), verification of claims
278
+ // boss — the spawner identity (may poll at its own cadence): mission
279
+ // changes, scope disputes; receives milestone + final DMs
280
+ // `workers` is [{ name, id, harness }]; `batch` the batch id ("" when solo).
281
+ // Pure: unit-tested, no board IO — the caller boots it via bootWorker
282
+ // (prompt override) and stamps the log file itself.
283
+ export function buildCoordinatorPrompt({ name, from, subject, body, batch, workers, crew, cwd, root, auto, workbench, budgetTokens, budgetMinutes }) {
284
+ const boss = String(from || "boss");
285
+ const me = String(name || LEAD_NAME);
286
+ const ws = Array.isArray(workers) ? workers.filter((w) => w && w.name) : [];
287
+ const crewLines = Array.isArray(crew) ? crew.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
288
+ const wbLines = Array.isArray(workbench) ? workbench.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
289
+ const today = new Date().toISOString().slice(0, 10);
290
+ return [
291
+ `You are '${me}' on crewbus (board: ${root}) — the auto-provisioned lead for this crew${batch ? ` (batch ${batch})` : ""}.`,
292
+ `${boss} spawned the crew as boss and left the acting lead seat to you from here on. This is an infrastructure/coordinator role, not a do-the-task role.`,
293
+ ``,
294
+ `Mission the crew is working (from ${boss}${subject ? ` — ${subject}` : ""}):`,
295
+ String(body || "(original brief; see each worker's prompt file under logs/)"),
296
+ ``,
297
+ ...(crewLines.length > 0 ? ["Crew:", ...crewLines.map((l) => `- ${l}`), ""] : []),
298
+ ...(batch ? ["Worker briefs (thread ids, for --reply):", ...ws.map((w) => `- ${w.name}: brief ${w.id}${w.harness ? ` [${w.harness}]` : ""}`), ""] : []),
299
+ ...(wbLines.length > 0 ? ["Workbench (lessons + artifacts from prior work on this board):", ...wbLines, ""] : []),
300
+ `Your identity: token saved at logs/${me}.token — read it into CREWBUS_TOKEN at the top of each shell that sends (PowerShell: \$env:CREWBUS_TOKEN = Get-Content .crewbus/logs/${me}.token). All sends run as --from ${me}. Never re-register over your own name — re-read the token file after any restart or compaction.`,
301
+ ...(budgetTokens !== undefined || budgetMinutes !== undefined
302
+ ? [`Budget mandate:${budgetTokens !== undefined ? ` ~${budgetTokens} est. tokens total${budgetMinutes !== undefined ? " and" : ""}` : ""}${budgetMinutes !== undefined ? ` ${budgetMinutes} wall-clock minutes total` : ""} — coordinate within it: batch your polls (listen --timeout 120000), digest-read first, and post the aggregate to ${boss} BEFORE the budget runs out (a budgeted coordinator gets reaped at the cap).`, ``]
303
+ : []),
304
+ ``,
305
+ `Jobs, in order:`,
306
+ `0. Boot habit: crewbus agents + crewbus group list, so you know who is on the board (workers claim over the first minutes; re-check when triaging).`,
307
+ `1. Read every DM before acting on anything else: crewbus inbox --from ${me} --unacked --digest, full read on hits. Workers' checkpoints and finals arrive here (each pinned to --reply their brief id).`,
308
+ `2. Keep the board alive — poll in a loop, cheaply: crewbus listen --from ${me} --timeout 120000 (blocks until a DM arrives; re-issue after each wake; fall back to sleep 60 + inbox --digest when listen is unavailable). Triage as DMs land: unblock, dedupe sibling lanes, point a worker at its sibling's finding instead of redoing it.`,
309
+ `3. Watch crew health: crewbus spawn-status --all. A worker that exited without a final is a lane to close: prefer the catch-up path first (crewbus respawn --from ${me} --to <name>${ws.some((w) => w.harness === "opencode") ? " (--fresh when its session id was never captured)" : ""}${auto ? " --auto (this crew was spawned fully-unattended; respawns inherit it)" : ""}); fall back to a fresh spawn (crewbus spawn --from ${me} --to <name> --persistent ... same mission text) only when respawn data is gone. Respawns need your lead token loaded (owned-crew). Cap: 2 respawn attempts per lane before DM'ing the boss with the stall evidence.`,
310
+ `4. Approvals: a worker's "approval:" ask (destructive/irreversible/out-of-scope) waits on your verdict — answer by --reply on its thread within the ask's stated timeout (crewbus send --from ${me} --to <worker> --reply <id> --body "approved ..." | "denied: <reason>; try-instead ..."). Silence beyond the ask's timeout reads as deny, fail-closed. Secrets/exfiltration/isolation-escape asks are NEVER approvable — deny and flag the boss.`,
311
+ `5. Scope disputes or mission changes: DM the boss — crewbus send --from ${me} --to ${boss} --priority high --subject "..." (the boss may not have a session open; the DM waits on the board by design — that is fine, keep working conservatively meanwhile). Same lane for milestones: batch started, lane closed, blocked, final aggregate.`,
312
+ `6. Long promises get deadlines: when you push a task or a lane's window, stamp --needs-by <duration> on the DM; chase inbox rows marked [OVERDUE] explicitly; when a lane stalls, surface it to the boss rather than silently absorbing it.`,
313
+ `7. Verify before relaying: worker claims about files/output get spot-checked against the board and ${cwd} when reasonable; do not relay a claim you contradict. Record what you verified in the thread.`,
314
+ ``,
315
+ `Never: change the workers' mission text (the mission above is the boss's words — pass it through verbatim), redo workers' work yourself, paste secrets (reference file paths), or micro-manage strategy. Peer-coordination belongs to the peers; you own health, verdicts, and the clock.`,
316
+ `Exit: when every lane has a final report or a deliberate stand-down, send the aggregate to the boss (crewbus send --from ${me} --to ${boss} --subject "result: ..." — include outcome, lanes closed, respawn count, artifacts left on the board), then you may exit. If the board is stalled with nothing spawnable, send the aggregate with the stall reason and exit.`,
317
+ ``,
318
+ `Protocol:`,
319
+ `3. Poll cheap and often: crewbus inbox --from ${me} --unacked --digest (full read only on hits). A full inbox dump every step will eat your context window.`,
320
+ `4. Never post secrets — reference their location instead. Today is ${today}.`,
321
+ ].join("\n");
322
+ }
323
+
324
+
325
+ // Provision the auto-lead for a spawn burst (--lead board): mint the 'lead'
326
+ // lane once per board (first claim wins, role = lead so spawn/respawn-kill
327
+ // authorize), hand its token over the same token-file convention workers use
328
+ // (logs/lead.token), boot a detached persistent coordinator with the prompt
329
+ // from buildCoordinatorPrompt, then TRANSFER crew ownership (workers'
330
+ // spawnedBy -> lead) so respawn/spawn-kill own-crew checks pass.
331
+ // opts: { d, spawnOpts, from, subject, body, rev, logDir, workers, batch,
332
+ // crew, workbench, auto }
333
+ // Returns { action: "minted"|"reused"|"skipped", reason?, leadName, pid?,
334
+ // logPath?, promptPath?, token?, transferred? } — token only on
335
+ // mint (printed once, then saved to the token file); a standing live
336
+ // coordinator is reused, never duplicated.
337
+ export function provisionAutoLead(d, opts) {
338
+ const leadName = LEAD_NAME;
339
+ const o = opts || {};
340
+ const boss = String(o.from || "boss");
341
+ if (boss === leadName) {
342
+ return { action: "skipped", reason: "the sender IS the lead lane — it bootstraps its own coordinator", leadName };
343
+ }
344
+ // Offboarded lead lane = deliberate teardown: refuse to skeleton it back
345
+ // up behind the caller's back (re-onboard it or pass --lead none).
346
+ const existing = readAgent(d, leadName);
347
+ if (existing && existing.offboarded) {
348
+ return { action: "skipped", reason: `lane "${leadName}" is offboarded (re-onboard it, or pass --lead none to pin replies to the spawner)`, leadName };
349
+ }
350
+ let token = null;
351
+ let minted = false;
352
+ if (existing && (existing.tokenHash || existing.token)) {
353
+ // Identity reuse — a lead lane already claims this name.
354
+ } else {
355
+ token = mintToken();
356
+ const salt = newSalt();
357
+ const tokenHash = hashToken(token, salt);
358
+ const doc = {
359
+ name: leadName, firstSeen: new Date().toISOString(), lastSeen: new Date().toISOString(),
360
+ lastDir: (o.spawnOpts && o.spawnOpts.cwd) || process.cwd(),
361
+ tokenHash, salt, role: "lead",
362
+ provisionedBy: boss, provisionedAt: new Date().toISOString(),
363
+ };
364
+ const claimed = writeExclusiveJson(path.join(d.agents, `${leadName}.json`), doc);
365
+ if (claimed) {
366
+ minted = true;
367
+ } else {
368
+ // Lost the exclusive create: either a concurrent minter won, or a
369
+ // legacy tokenless record holds the name (mint into it — this is the
370
+ // ensureSender post-revoke path, minus the token authentication step
371
+ // the caller already performed as board admin).
372
+ const again = readAgent(d, leadName);
373
+ if (again && !again.offboarded && !again.tokenHash && !again.token) {
374
+ const salt2 = newSalt();
375
+ again.tokenHash = hashToken(token, salt2);
376
+ again.salt = salt2;
377
+ if (!again.role) again.role = "lead";
378
+ writeAgentFile(d, leadName, again);
379
+ assertMintWon(d, leadName, again.tokenHash);
380
+ minted = true;
381
+ } else if (again && (again.tokenHash || again.token)) {
382
+ token = null; // absorbed by a concurrent minter — reuse its identity
383
+ } else {
384
+ return { action: "skipped", reason: `lane "${leadName}" raced a parallel claim that hid the name — retry or pass --lead none`, leadName };
385
+ }
386
+ }
387
+ }
388
+ // Always (re)record how this coordinator came to be, without clobbering
389
+ // an existing live one. Standing = pid alive AND not stale (reboot + OS
390
+ // pid reuse: a different (unrelated) process recycled the pid — see
391
+ // isPidStale; stale never blocks a fresh boot, it just disqualifies reuse).
392
+ const rec = readAgent(d, leadName);
393
+ const standing = rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt);
394
+ if (minted) saveTokenFile(d.root, leadName, token);
395
+ let booted = null;
396
+ if (standing) {
397
+ // A live coordinator is already running on the lead lane (previous
398
+ // burst): never duplicate it — DMs land in the same lane by name.
399
+ } else {
400
+ try {
401
+ booted = bootWorker(d, o.spawnOpts, {
402
+ to: leadName, id: o.batch || "coord", from: boss, subject: o.subject,
403
+ body: o.body, rev: o.rev, logDir: o.logDir, crew: o.crew,
404
+ workbench: o.workbench, prompt: buildCoordinatorPrompt({
405
+ name: leadName, from: boss, subject: o.subject, body: o.body,
406
+ batch: o.batch, workers: o.workers, crew: o.crew,
407
+ cwd: (o.spawnOpts && o.spawnOpts.cwd) || process.cwd(),
408
+ root: d.root, auto: !!o.auto, workbench: o.workbench,
409
+ budgetTokens: o.budgetTokens, budgetMinutes: o.budgetMinutes,
410
+ }),
411
+ spawnedLifetime: "persistent",
412
+ budgetTokens: o.budgetTokens, budgetMinutes: o.budgetMinutes, deadlineAt: undefined,
413
+ });
414
+ } catch (e) {
415
+ const detail = String((e && (e.message || e)) || e).slice(0, 160);
416
+ if (minted) {
417
+ saveTokenFile(d.root, leadName, token);
418
+ try { touchAgent(d, leadName, { lastDir: (o.spawnOpts && o.spawnOpts.cwd) || undefined, provisionedBy: boss }); } catch {}
419
+ return { action: "minted", reason: `coordinator boot failed (${detail}) — lane minted; token at logs/${leadName}.token; boot it by hand (spawn --from ${boss} --to ${leadName} --persistent) or DM workers manually`, leadName, token, boss };
420
+ }
421
+ return { action: "skipped", reason: `coordinator boot failed (${detail}) — workers stay owned by ${boss}`, leadName };
422
+ }
423
+ }
424
+ try { touchAgent(d, leadName, { lastDir: (o.spawnOpts && o.spawnOpts.cwd) || undefined, spawnedBy: boss ?? undefined }); } catch {}
425
+ // Crew ownership transfer: workers now belong to the lead lane, which is
426
+ // what respawn/spawn-kill own-crew checks demand (docs/RBAC.md). The
427
+ // spawner's audit trail (appendChainRecord) preserves the original actor.
428
+ let transferred = 0;
429
+ for (const w of (Array.isArray(o.workers) ? o.workers : [])) {
430
+ if (!w || !w.name) continue;
431
+ try { touchAgent(d, w.name, { spawnedBy: leadName }); transferred += 1; } catch {}
432
+ }
433
+ return {
434
+ action: minted ? "minted" : "reused",
435
+ leadName,
436
+ pid: booted ? booted.pid : (rec && rec.spawnedPid),
437
+ logPath: booted ? booted.logPath : undefined,
438
+ promptPath: booted ? booted.promptPath : undefined,
439
+ token,
440
+ transferred,
441
+ boss,
442
+ stoodDown: !!standing,
443
+ };
444
+ }
445
+
237
446
  // Resolve the real opencode binary from PATH, once per process. npm installs
238
447
  // expose cmd/bash/ps1 shims that shell out to the real exe; running through
239
448
  // them (the old `shell: true` path) drags the Bun binary into cmd.exe, which
@@ -248,7 +457,10 @@ export function resolveOpencodeExe() {
248
457
  if (_opencodeExe !== undefined) return _opencodeExe;
249
458
  _opencodeExe = null;
250
459
  try {
251
- const out = execFileSync(process.platform === "win32" ? "where" : "which", ["opencode"], { encoding: "utf8", shell: true, stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
460
+ // where/which are real binaries — no shell was ever needed for this
461
+ // probe (execFileSync + args + shell:true was DEP0190 on modern Node).
462
+ const probe = process.platform === "win32" ? "where" : "which";
463
+ const out = execFileSync(probe, ["opencode"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
252
464
  for (const raw of String(out || "").split(/\r?\n/)) {
253
465
  const shim = raw.trim();
254
466
  if (!shim) continue;
@@ -764,17 +976,20 @@ export function syncWorkerSession(d, name, logPath, storageProbe) { // respawn s
764
976
  export function launchWorkerProcess({ exe, args, shell, cwd, env, logPath, stdinPath }) { // respawn slice 2
765
977
  const logFd = fs.openSync(logPath, "a");
766
978
  let inFd = null;
767
- let child = null;
768
- try {
769
- // claude reads the brief from stdin; everyone else takes paths/args, so
770
- // the long prompt never travels through shell quoting.
771
- const stdio = ["ignore", logFd, logFd];
772
- if (stdinPath) {
773
- inFd = fs.openSync(stdinPath, "r");
774
- stdio[0] = inFd;
775
- }
776
- child = spawn(exe, args, { cwd, env, detached: true, stdio, shell, windowsHide: true });
777
- } catch (e) {
979
+ let child = null;
980
+ try {
981
+ // claude reads the brief from stdin; everyone else takes paths/args, so
982
+ // the long prompt never travels through shell quoting. shell:true with
983
+ // non-empty args is DEP0190 on modern Node — resolveShellShot keeps the
984
+ // old cmd/sh wire format while spawning the shell as an explicit argv0.
985
+ const stdio = ["ignore", logFd, logFd];
986
+ if (stdinPath) {
987
+ inFd = fs.openSync(stdinPath, "r");
988
+ stdio[0] = inFd;
989
+ }
990
+ const shot = resolveShellShot(exe, args || [], shell);
991
+ child = spawn(shot.exe, shot.args, { cwd, env, detached: true, stdio, shell: shot.shell, windowsHide: true, ...shot.extraOptions });
992
+ } catch (e) {
778
993
  try { fs.closeSync(logFd); } catch {}
779
994
  try { if (inFd !== null) fs.closeSync(inFd); } catch {}
780
995
  throw e;
@@ -891,12 +1106,14 @@ export function installCliToUserPath() {
891
1106
  return { ok: true, binDir: userBinDir, addedToPath, detail };
892
1107
  }
893
1108
 
894
- export function bootWorker(d, spawnOpts, { to, id, from, subject, body, rev, logDir, budgetTokens, budgetMinutes, deadlineAt, spawnedWorktree, spawnedBranch, spawnedLifetime, sessionId, crew, workbench }) { // line 4338
1109
+ export function bootWorker(d, spawnOpts, { to, id, from, lead, subject, body, rev, logDir, budgetTokens, budgetMinutes, deadlineAt, spawnedWorktree, spawnedBranch, spawnedLifetime, sessionId, crew, workbench, prompt }) { // line 4338
895
1110
  const { cwd, root } = spawnOpts;
896
1111
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
897
- const prompt = buildSpawnPrompt({ name: to, from, subject, body, replyId: id, rev, cwd, root, crew, workbench });
898
- const promptPath = path.join(logDir, `${to}-${stamp}.prompt.md`);
899
- fs.writeFileSync(promptPath, prompt + "\n");
1112
+ // Prompt override: the auto-lead coordinator passes its own brief
1113
+ // (buildCoordinatorPrompt); everything else uses the worker template.
1114
+ const finalPrompt = (typeof prompt === "string" && prompt.trim()) ? prompt : buildSpawnPrompt({ name: to, from, lead, subject, body, replyId: id, rev, cwd, root, crew, workbench });
1115
+ const promptPath = path.join(logDir, `${to}-${stamp}.prompt.md`);
1116
+ fs.writeFileSync(promptPath, finalPrompt + "\n");
900
1117
  const logPath = path.join(logDir, `${to}-${stamp}.log`);
901
1118
  // Boot metadata first: child stdout is often block-buffered (or never
902
1119
  // flushed at all on some harnesses), so the log must carry proof of
@@ -934,7 +1151,7 @@ export function bootWorker(d, spawnOpts, { to, id, from, subject, body, rev, log
934
1151
  preId = undefined;
935
1152
  }
936
1153
  }
937
- const target = buildSpawnTarget({ ...spawnOpts, name: to, promptPath, prompt, sessionId: preId });
1154
+ const target = buildSpawnTarget({ ...spawnOpts, name: to, promptPath, prompt: finalPrompt, sessionId: preId });
938
1155
  const { pid } = launchWorkerProcess({ exe: target.exe, args: target.args, shell: target.shell, cwd, env: childEnv, logPath, stdinPath: target.stdinPath });
939
1156
  touchAgent(d, to, { spawnedPid: pid, spawnedAt: new Date().toISOString(), spawnedBy: from, briefId: id, lastDir: cwd, budgetTokens, budgetMinutes, budgetSince: (budgetTokens !== undefined || budgetMinutes !== undefined) ? new Date().toISOString() : undefined, deadlineAt, spawnedWorktree, spawnedBranch, spawnedLifetime, spawnedHarness: cleanHarnessDriver(spawnOpts.harness), spawnedEnvScrubbed: scrub.kept ? 0 : scrub.scrubbed.length });
940
1157
  // Binding doc for the later respawn step (preassigned id lands here
@@ -1194,6 +1411,12 @@ export async function killWorkers(d, names) { // line 4529
1194
1411
  out.push({ name, result: "already-exited", pid });
1195
1412
  continue;
1196
1413
  }
1414
+ // Safety guard (C2): a live pid that provably postdates the spawn record
1415
+ // belongs to an UNRELATED process (reboot + OS pid reuse). Never kill it.
1416
+ if (isPidStale(pid, doc.spawnedAt)) {
1417
+ out.push({ name, result: "pid-stale", pid, detail: "pid recycled after a reboot — it is not this worker; nothing killed" });
1418
+ continue;
1419
+ }
1197
1420
  try {
1198
1421
  if (process.platform === "win32") {
1199
1422
  // /T takes the whole tree: shell shims (cmd) outlive nothing.
package/bin/lib/store.js CHANGED
@@ -120,12 +120,13 @@ export function dirs(root) { // line 122
120
120
  holds: path.join(root, "holds"),
121
121
  artifacts: path.join(root, "artifacts"),
122
122
  lessons: path.join(root, "lessons"),
123
+ dmArchive: path.join(root, "dm-archive"),
123
124
  };
124
125
  }
125
126
 
126
127
  export function ensureBoard(root) { // line 142
127
128
  const d = dirs(root);
128
- for (const p of [d.root, d.agents, d.dm, d.delivered, d.broadcast, d.groups, d.channels, d.locks, d.results, d.tombstones, d.poolState, d.workerSessions, d.index, d.cursors, d.revoked, d.holds, d.artifacts, d.lessons, path.join(root, "logs")]) {
129
+ for (const p of [d.root, d.agents, d.dm, d.dmArchive, d.delivered, d.broadcast, d.groups, d.channels, d.locks, d.results, d.tombstones, d.poolState, d.workerSessions, d.index, d.cursors, d.revoked, d.holds, d.artifacts, d.lessons, path.join(root, "logs")]) {
129
130
  fs.mkdirSync(p, { recursive: true });
130
131
  }
131
132
  const metaPath = path.join(d.root, "board.json");