crewbus 10.0.10 → 10.0.12

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/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
  }
@@ -196,7 +198,7 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
196
198
  return s;
197
199
  }).filter(Boolean);
198
200
  if (harnesses.length === 0) harnesses.push("opencode");
199
- const validHarnesses = ["opencode", "claude", "codex", "grok", "antigravity", "cursor", "generic"];
201
+ const validHarnesses = ["opencode", "claude", "codex", "grok", "antigravity", "cursor"];
200
202
  for (const h of harnesses) {
201
203
  if (!validHarnesses.includes(h)) {
202
204
  throw webErr(400, `unknown harness "${h}" (want ${validHarnesses.join("|")})`);
@@ -204,7 +206,6 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
204
206
  }
205
207
  let harness = harnesses.join(",");
206
208
  const cmd = cleanOpt(a.cmd);
207
- if (harnesses.includes("generic") && !cmd) throw webErr(400, 'generic harness needs cmd "..."');
208
209
  const maxTurns = a.maxTurns === undefined || a.maxTurns === null || String(a.maxTurns).trim() === "" ? ((harness === "claude" || harness === "grok") ? 50 : undefined) : Number(a.maxTurns);
209
210
  if (maxTurns !== undefined && !(maxTurns > 0)) throw webErr(400, "maxTurns must be a positive number");
210
211
  if (maxTurns !== undefined && harness !== "claude" && harness !== "grok") throw webErr(400, `maxTurns only applies to claude/grok (got ${harness})`);
@@ -238,17 +239,7 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
238
239
  const wr = path.resolve(String(svc.workdirRoot));
239
240
  if (cwd !== wr && !cwd.startsWith(wr + path.sep)) throw webErr(403, `cwd ${cwd} is outside --workdir-root ${wr}`);
240
241
  }
241
- if (harness === "generic") {
242
- const pattern = svc.allowCmd;
243
- if (!pattern) throw webErr(403, "generic --cmd is refused remotely unless the relay sets --allow-cmd (default harness-only)");
244
- let ok = false;
245
- try {
246
- ok = new RegExp(String(pattern)).test(String(cmd || ""));
247
- } catch {
248
- throw webErr(500, "relay --allow-cmd is not a valid regex");
249
- }
250
- if (!ok) throw webErr(403, "remote --cmd not in relay allowlist (--allow-cmd)");
251
- }
242
+
252
243
  if (auto && !(a.iUnderstandDanger === true || a.i_understand_danger === true)) throw webErr(400, "--auto remotely needs iUnderstandDanger:true plus an isolated relay (see docs/ISOLATION.md)");
253
244
  // Pre-verify: CLI ensureSender calls fail() (process exit) on mismatch,
254
245
  // which must never run inside a request handler. Hashed + legacy accepted.
package/bin/lib/spawn.js CHANGED
@@ -22,17 +22,32 @@ import fs from "node:fs";
22
22
  import path from "node:path";
23
23
  import crypto from "node:crypto";
24
24
  import os from "node:os";
25
+ import { fileURLToPath } from "node:url";
25
26
  import { createRequire } from "node:module";
26
27
  import { execFileSync, spawn } from "node:child_process";
27
28
  import { fail, readJson, writeJson, writeExclusiveJson, cleanBranchPrefix } from "./store.js";
28
29
  import { touchAgent, readAgent, writeAgentFile, assertMintWon, mintToken, newSalt, hashToken } from "./identity.js";
29
30
  import { readVisible, isCheckpoint } from "./mail.js";
30
31
  import { saveTokenFile, loadTokenFile } from "./tokenfile.js";
32
+ import { shellChildSpec, shellChildOptions } from "./kidproc.js";
33
+
34
+ function resolveShellShot(exe, args, shell) {
35
+ // Converts shell-needing targets to an explicit shell argv0 (no DEP0190);
36
+ // shell:false targets (resolved real exes) pass through untouched — their
37
+ // spawned pid IS the harness process (kill semantics depend on it).
38
+ // Returns { exe, args, shell, extraOptions } for spawn().
39
+ if (shell) {
40
+ const spec = shellChildSpec(exe, args);
41
+ if (spec) return { ...spec, shell: false, extraOptions: shellChildOptions() };
42
+ }
43
+ return { exe, args, shell: !!shell, extraOptions: {} };
44
+ }
45
+ export { resolveShellShot };
31
46
 
32
47
  // cleanBranchPrefix lives in store.js (canonical home).
33
48
 
34
49
  // Auto-provisioned lead lane: the board's standing coordinator lane name.
35
- // `spawn --lead board` (the default) mints it once (first claim wins) and
50
+ // `spawn --lead auto` (the default) mints it once (first claim wins) and
36
51
  // boots a detached persistent coordinator that owns the crew for the burst;
37
52
  // the interactive spawner steps back to boss (reads the dashboard, gets
38
53
  // milestone DMs). All worker prompts pin replies to this name.
@@ -172,10 +187,7 @@ export function parseAllowEnv(raw) { // line 4078
172
187
 
173
188
  export function buildSpawnPrompt({ name, from, lead, subject, body, replyId, rev, cwd, root, crew, workbench }) { // line 4090
174
189
  const me = String(name || "you");
175
- // Reply target: the sender by default (legacy star topology), or the
176
- // board's lead lane under --lead board (spawn and lead separated: the
177
- // spawner is boss, the auto-provisioned coordinator is lead).
178
- const replyTo = String(lead || from || LEAD_NAME);
190
+ const replyTo = String(lead || LEAD_NAME);
179
191
  const crewLines = Array.isArray(crew) ? crew.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
180
192
  const wbLines = Array.isArray(workbench) ? workbench.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
181
193
  return [
@@ -190,7 +202,7 @@ export function buildSpawnPrompt({ name, from, lead, subject, body, replyId, rev
190
202
  `Protocol:`,
191
203
  `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.`,
192
204
  `1. Work in ${cwd} (your harness already starts there).`,
193
- `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).`}`,
205
+ `2. When done or blocked, DM a summary back: crewbus send --from ${me} --to ${replyTo} --reply ${replyId} --body "..." (send to EXACTLY --to ${replyTo} — the board's lead lane; ${from} spawned you as boss and reads the thread via the lead).`,
194
206
  `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).`,
195
207
  `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.`,
196
208
  `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.`,
@@ -260,7 +272,7 @@ export function buildCrewContext({ name, from, lead: leadTarget, subject, groups
260
272
  // `workers` is [{ name, id, harness }]; `batch` the batch id ("" when solo).
261
273
  // Pure: unit-tested, no board IO — the caller boots it via bootWorker
262
274
  // (prompt override) and stamps the log file itself.
263
- export function buildCoordinatorPrompt({ name, from, subject, body, batch, workers, crew, cwd, root, auto, workbench }) {
275
+ export function buildCoordinatorPrompt({ name, from, subject, body, batch, workers, crew, cwd, root, auto, workbench, budgetTokens, budgetMinutes }) {
264
276
  const boss = String(from || "boss");
265
277
  const me = String(name || LEAD_NAME);
266
278
  const ws = Array.isArray(workers) ? workers.filter((w) => w && w.name) : [];
@@ -278,6 +290,9 @@ export function buildCoordinatorPrompt({ name, from, subject, body, batch, worke
278
290
  ...(batch ? ["Worker briefs (thread ids, for --reply):", ...ws.map((w) => `- ${w.name}: brief ${w.id}${w.harness ? ` [${w.harness}]` : ""}`), ""] : []),
279
291
  ...(wbLines.length > 0 ? ["Workbench (lessons + artifacts from prior work on this board):", ...wbLines, ""] : []),
280
292
  `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.`,
293
+ ...(budgetTokens !== undefined || budgetMinutes !== undefined
294
+ ? [`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).`, ``]
295
+ : []),
281
296
  ``,
282
297
  `Jobs, in order:`,
283
298
  `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).`,
@@ -319,10 +334,10 @@ export function provisionAutoLead(d, opts) {
319
334
  return { action: "skipped", reason: "the sender IS the lead lane — it bootstraps its own coordinator", leadName };
320
335
  }
321
336
  // Offboarded lead lane = deliberate teardown: refuse to skeleton it back
322
- // up behind the caller's back (re-onboard it or pass --lead none).
337
+ // up behind the caller's back.
323
338
  const existing = readAgent(d, leadName);
324
339
  if (existing && existing.offboarded) {
325
- return { action: "skipped", reason: `lane "${leadName}" is offboarded (re-onboard it, or pass --lead none to pin replies to the spawner)`, leadName };
340
+ return { action: "skipped", reason: `lane "${leadName}" is offboarded (re-onboard it to provision the coordinator)`, leadName };
326
341
  }
327
342
  let token = null;
328
343
  let minted = false;
@@ -358,14 +373,16 @@ export function provisionAutoLead(d, opts) {
358
373
  } else if (again && (again.tokenHash || again.token)) {
359
374
  token = null; // absorbed by a concurrent minter — reuse its identity
360
375
  } else {
361
- return { action: "skipped", reason: `lane "${leadName}" raced a parallel claim that hid the name — retry or pass --lead none`, leadName };
376
+ return { action: "skipped", reason: `lane "${leadName}" raced a parallel claim that hid the name — retry`, leadName };
362
377
  }
363
378
  }
364
379
  }
365
380
  // Always (re)record how this coordinator came to be, without clobbering
366
- // an existing live one.
381
+ // an existing live one. Standing = pid alive AND not stale (reboot + OS
382
+ // pid reuse: a different (unrelated) process recycled the pid — see
383
+ // isPidStale; stale never blocks a fresh boot, it just disqualifies reuse).
367
384
  const rec = readAgent(d, leadName);
368
- const standing = rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid);
385
+ const standing = rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt);
369
386
  if (minted) saveTokenFile(d.root, leadName, token);
370
387
  let booted = null;
371
388
  if (standing) {
@@ -381,9 +398,10 @@ export function provisionAutoLead(d, opts) {
381
398
  batch: o.batch, workers: o.workers, crew: o.crew,
382
399
  cwd: (o.spawnOpts && o.spawnOpts.cwd) || process.cwd(),
383
400
  root: d.root, auto: !!o.auto, workbench: o.workbench,
401
+ budgetTokens: o.budgetTokens, budgetMinutes: o.budgetMinutes,
384
402
  }),
385
403
  spawnedLifetime: "persistent",
386
- budgetTokens: undefined, budgetMinutes: undefined, deadlineAt: undefined,
404
+ budgetTokens: o.budgetTokens, budgetMinutes: o.budgetMinutes, deadlineAt: undefined,
387
405
  });
388
406
  } catch (e) {
389
407
  const detail = String((e && (e.message || e)) || e).slice(0, 160);
@@ -428,10 +446,12 @@ export function provisionAutoLead(d, opts) {
428
446
  // callers fall back to the shim invocation they always used.
429
447
  let _opencodeExe = undefined; // undefined = unresolved; string | null after
430
448
  export function resolveOpencodeExe() {
449
+ if (process.env.OPENCODE_EXE !== undefined) return process.env.OPENCODE_EXE || null;
431
450
  if (_opencodeExe !== undefined) return _opencodeExe;
432
451
  _opencodeExe = null;
433
452
  try {
434
- const out = execFileSync(process.platform === "win32" ? "where" : "which", ["opencode"], { encoding: "utf8", shell: true, stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
453
+ const probe = process.platform === "win32" ? "where" : "which";
454
+ const out = execFileSync(probe, ["opencode"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
435
455
  for (const raw of String(out || "").split(/\r?\n/)) {
436
456
  const shim = raw.trim();
437
457
  if (!shim) continue;
@@ -454,6 +474,59 @@ export function resolveOpencodeExe() {
454
474
  return _opencodeExe;
455
475
  }
456
476
 
477
+ const _harnessExeCache = {};
478
+ export function resolveHarnessExe(harness) {
479
+ const envKey = `${harness.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_EXE`;
480
+ if (process.env[envKey] !== undefined) return process.env[envKey] || null;
481
+ if (harness === "opencode") return resolveOpencodeExe();
482
+ if (_harnessExeCache[harness] !== undefined) return _harnessExeCache[harness];
483
+ _harnessExeCache[harness] = null;
484
+ const binName = harness === "antigravity" ? "agy" : harness;
485
+ try {
486
+ const probe = process.platform === "win32" ? "where" : "which";
487
+ const out = execFileSync(probe, [binName], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
488
+ for (const raw of String(out || "").split(/\r?\n/)) {
489
+ const shim = raw.trim();
490
+ if (!shim) continue;
491
+ if (process.platform === "win32") {
492
+ if (/\.exe$/i.test(shim)) {
493
+ _harnessExeCache[harness] = shim;
494
+ break;
495
+ }
496
+ let txt = "";
497
+ try { txt = fs.readFileSync(shim, "utf8"); } catch { continue; }
498
+ const m = /"([^"\n]*?\.exe)"/i.exec(txt);
499
+ if (m) {
500
+ const target = path.resolve(m[1].replace(/%~?dp0%/gi, path.dirname(shim)).replace(/%dp0%/gi, path.dirname(shim)));
501
+ if (fs.existsSync(target) && fs.statSync(target).isFile()) {
502
+ _harnessExeCache[harness] = target;
503
+ break;
504
+ }
505
+ }
506
+ const mJs = /"([^"\n]*?\.js)"/i.exec(txt);
507
+ if (mJs) {
508
+ const jsPath = path.resolve(mJs[1].replace(/%~?dp0%/gi, path.dirname(shim)).replace(/%dp0%/gi, path.dirname(shim)));
509
+ const pkgDir = path.dirname(path.dirname(jsPath));
510
+ for (const cand of [
511
+ path.join(pkgDir, "node_modules", "@openai", "codex-win32-x64", "vendor", "x86_64-pc-windows-msvc", "bin", "codex.exe"),
512
+ path.join(path.dirname(pkgDir), "codex-win32-x64", "vendor", "x86_64-pc-windows-msvc", "bin", "codex.exe"),
513
+ ]) {
514
+ if (fs.existsSync(cand) && fs.statSync(cand).isFile()) {
515
+ _harnessExeCache[harness] = cand;
516
+ break;
517
+ }
518
+ }
519
+ if (_harnessExeCache[harness]) break;
520
+ }
521
+ } else {
522
+ _harnessExeCache[harness] = shim;
523
+ break;
524
+ }
525
+ }
526
+ } catch {}
527
+ return _harnessExeCache[harness];
528
+ }
529
+
457
530
  export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt, sessionId }) { // line 4114
458
531
  const quoteFree = (s) => String(s).replace(/"/g, "'");
459
532
  if (harness === "opencode") {
@@ -478,7 +551,8 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
478
551
  // --output-format json reports session_id for later resume (same as above).
479
552
  // --session-id pre-assigns it, so even a mid-run kill leaves a resumable
480
553
  // id on record (verified in CLI docs; needs a valid UUID).
481
- const cargs = ["-p", "--output-format", "json", "--allowedTools", allowTools || "Read,Edit,Write,Bash"];
554
+ // Include mcp__crewbus__* in default allowedTools so bus tools can be invoked.
555
+ const cargs = ["-p", "--output-format", "json", "--allowedTools", allowTools || "Read,Edit,Write,Bash,mcp__crewbus__*"];
482
556
  if (sessionId) cargs.push("--session-id", sessionId);
483
557
  if (model) cargs.push("--model", model);
484
558
  if (maxTurns !== undefined) cargs.push("--max-turns", String(maxTurns));
@@ -488,22 +562,30 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
488
562
  if (harness === "codex") {
489
563
  // codex exec has no --file attach: the positional message points at the
490
564
  // brief file and the worker reads it with its own tools. Read-only is
491
- // the exec default, so workspace-write + never makes a worker that can
492
- // actually work unattended; --skip-git-repo-check allows non-repo cwds.
565
+ // the exec default, so workspace-write makes a worker that can work unattended;
566
+ // -c approval_policy="never" avoids unexpected argument '-a' failure in codex exec;
567
+ // --dangerously-bypass-hook-trust allows .codex/hooks.json to execute unattended;
568
+ // --skip-git-repo-check allows non-repo cwds.
493
569
  // --json prints JSONL events: the first is thread.started {thread_id},
494
570
  // which shares the session-id namespace (session_id: ThreadId in core)
495
571
  // and is what `codex exec resume <id>` accepts — captured for respawn.
496
- const cargs = ["exec", "--json", "--sandbox", auto ? "danger-full-access" : "workspace-write", "-a", "never", "--skip-git-repo-check", "-C", cwd];
572
+ const cargs = ["exec", "--json", "--sandbox", auto ? "danger-full-access" : "workspace-write", "-c", "approval_policy=\"never\"", "--dangerously-bypass-hook-trust", "--skip-git-repo-check", "-C", cwd];
573
+ const mcpPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../crewbus-mcp.js");
574
+ if (fs.existsSync(mcpPath)) {
575
+ const normMcp = mcpPath.replace(/\\/g, "/");
576
+ cargs.push("-c", 'mcp_servers.crewbus.command="node"', "-c", `mcp_servers.crewbus.args=["${normMcp}"]`);
577
+ }
497
578
  if (model) cargs.push("--model", model);
579
+ if (auto) cargs.push("--dangerously-bypass-approvals-and-sandbox");
498
580
  cargs.push(quoteFree(`you are '${name}': read the brief at ${promptPath} and follow it`));
499
- return { exe: "codex", args: cargs, shell: true };
581
+ return { exe: "codex", args: cargs, shell: true, stdinPath: promptPath };
500
582
  }
501
583
  if (harness === "grok") {
502
584
  // grok.exe is a real binary: no shell, argv passes verbatim.
503
585
  // --output-format json emits sessionId for later resume (see above).
504
586
  // -s pre-assigns it (create-only UUID): the id is knowable at boot,
505
587
  // before the run emits anything — the mid-run-kill case.
506
- const gargs = ["--prompt-file", promptPath, "--cwd", cwd, "--output-format", "json", "--permission-mode", "auto", "--max-turns", String(maxTurns === undefined ? 50 : maxTurns)];
588
+ const gargs = ["--prompt-file", promptPath, "--cwd", cwd, "--output-format", "json", "--permission-mode", auto ? "bypassPermissions" : "auto", "--max-turns", String(maxTurns === undefined ? 50 : maxTurns)];
507
589
  if (sessionId) gargs.push("-s", sessionId);
508
590
  if (model) gargs.push("-m", model);
509
591
  if (auto) gargs.push("--always-approve");
@@ -532,7 +614,7 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
532
614
  cargs.push(quoteFree(`you are '${name}': read the brief at ${promptPath} and follow it`));
533
615
  return { exe: "cursor-agent", args: cargs, shell: true };
534
616
  }
535
- return { exe: cmd, args: [], shell: true };
617
+ fail(`unknown --harness "${harness}" (want opencode|claude|codex|grok|antigravity|cursor)`);
536
618
  }
537
619
 
538
620
  // Resume targets for `respawn` (slice 2): same worker name, same conversation,
@@ -540,10 +622,9 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
540
622
  // opencode `run --session`, claude `-p --resume` (never --session-id: it
541
623
  // cannot combine with --resume), codex `exec <parent opts> resume <id>`
542
624
  // (parent options precede the subcommand), grok `-r`, agy `--conversation`,
543
- // cursor `--resume`. Generic has no session continuity: plain fresh boot of
544
- // the catch-up brief. File/stdin plumbing mirrors buildSpawnTarget.
625
+ // cursor `--resume`. File/stdin plumbing mirrors buildSpawnTarget.
545
626
  export function buildRespawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt, sessionId }) { // respawn slice 2
546
- // No captured session id (generic, or the respawn --fresh fallback when a
627
+ // No captured session id (the respawn --fresh fallback when a
547
628
  // harness id could not be captured): plain fresh boot of the catch-up
548
629
  // brief — the same command shape as spawn.
549
630
  if (!sessionId) {
@@ -556,9 +637,6 @@ export function buildRespawnTarget({ harness, cmd, model, auto, maxTurns, allowT
556
637
  const positional = String(`you are '${name}': read the catch-up brief at ${promptPath} and follow it`).replace(/"/g, "'");
557
638
  return { ...base, args: [...base.args.slice(0, -1), "resume", sessionId, positional] };
558
639
  }
559
- if (harness === "generic") {
560
- return buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt });
561
- }
562
640
  const t = buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt });
563
641
  const flag = harness === "opencode" ? ["--session", sessionId]
564
642
  : harness === "claude" ? ["--resume", sessionId]
@@ -566,18 +644,16 @@ export function buildRespawnTarget({ harness, cmd, model, auto, maxTurns, allowT
566
644
  : harness === "antigravity" ? ["--conversation", sessionId]
567
645
  : harness === "cursor" ? ["--resume", sessionId]
568
646
  : null;
569
- if (!flag) fail(`unknown --harness "${harness}" (want opencode|claude|codex|grok|antigravity|cursor|generic)`);
647
+ if (!flag) fail(`unknown --harness "${harness}" (want opencode|claude|codex|grok|antigravity|cursor)`);
570
648
  return { ...t, args: [...t.args, ...flag] };
571
649
  }
572
650
 
573
651
  export function buildRespawnBrief({ name, attempt, origPromptPath, briefId, harnessSessionId, harness, lead, extraBody }) { // respawn slice 2
574
- // --fresh respawn (opencode with no captured id) boots fresh like generic;
652
+ // --fresh respawn (opencode with no captured id) boots fresh;
575
653
  // the wording must not claim "prior context intact" when there is none.
576
- const resumed = harness === "generic"
577
- ? "fresh session (generic harness has no session continuity — no prior context)"
578
- : !harnessSessionId && harness === "opencode"
579
- ? "fresh session (opencode session id could not be captured; brief + checkpoints are your memory)"
580
- : `resumed ${harness} session ${harnessSessionId} (prior context intact)`;
654
+ const resumed = !harnessSessionId && harness === "opencode"
655
+ ? "fresh session (opencode session id could not be captured; brief + checkpoints are your memory)"
656
+ : `resumed ${harness} session ${harnessSessionId} (prior context intact)`;
581
657
  const lines = [
582
658
  `You are '${name}': this is restart attempt ${attempt} (${resumed}). Your previous process died.`,
583
659
  ``,
@@ -623,7 +699,7 @@ function cleanSessionId(raw) {
623
699
 
624
700
  // Harness driver allowlist (mirrors packages/contracts/harness.json drivers;
625
701
  // unknown values are omitted, never invented).
626
- export const KNOWN_HARNESS_DRIVERS = ["opencode", "claude", "codex", "grok", "antigravity", "cursor", "generic"];
702
+ export const KNOWN_HARNESS_DRIVERS = ["opencode", "claude", "codex", "grok", "antigravity", "cursor"];
627
703
 
628
704
  export function cleanHarnessDriver(raw) {
629
705
  const s = String(raw === undefined || raw === null ? "" : raw).trim().toLowerCase();
@@ -947,17 +1023,27 @@ export function syncWorkerSession(d, name, logPath, storageProbe) { // respawn s
947
1023
  export function launchWorkerProcess({ exe, args, shell, cwd, env, logPath, stdinPath }) { // respawn slice 2
948
1024
  const logFd = fs.openSync(logPath, "a");
949
1025
  let inFd = null;
950
- let child = null;
951
- try {
952
- // claude reads the brief from stdin; everyone else takes paths/args, so
953
- // the long prompt never travels through shell quoting.
954
- const stdio = ["ignore", logFd, logFd];
955
- if (stdinPath) {
956
- inFd = fs.openSync(stdinPath, "r");
957
- stdio[0] = inFd;
958
- }
959
- child = spawn(exe, args, { cwd, env, detached: true, stdio, shell, windowsHide: true });
960
- } catch (e) {
1026
+ let child = null;
1027
+ try {
1028
+ // claude reads the brief from stdin; everyone else takes paths/args, so
1029
+ // the long prompt never travels through shell quoting. shell:true with
1030
+ // non-empty args is DEP0190 on modern Node — resolveShellShot keeps the
1031
+ // old cmd/sh wire format while spawning the shell as an explicit argv0.
1032
+ const stdio = ["ignore", logFd, logFd];
1033
+ if (stdinPath) {
1034
+ inFd = fs.openSync(stdinPath, "r");
1035
+ stdio[0] = inFd;
1036
+ }
1037
+ const direct = resolveHarnessExe(exe);
1038
+ let targetExe = exe;
1039
+ let targetShell = shell;
1040
+ if (direct) {
1041
+ targetExe = direct;
1042
+ targetShell = false;
1043
+ }
1044
+ const shot = resolveShellShot(targetExe, args || [], targetShell);
1045
+ child = spawn(shot.exe, shot.args, { cwd, env, detached: true, stdio, shell: shot.shell, windowsHide: true, ...shot.extraOptions });
1046
+ } catch (e) {
961
1047
  try { fs.closeSync(logFd); } catch {}
962
1048
  try { if (inFd !== null) fs.closeSync(inFd); } catch {}
963
1049
  throw e;
@@ -1379,6 +1465,12 @@ export async function killWorkers(d, names) { // line 4529
1379
1465
  out.push({ name, result: "already-exited", pid });
1380
1466
  continue;
1381
1467
  }
1468
+ // Safety guard (C2): a live pid that provably postdates the spawn record
1469
+ // belongs to an UNRELATED process (reboot + OS pid reuse). Never kill it.
1470
+ if (isPidStale(pid, doc.spawnedAt)) {
1471
+ out.push({ name, result: "pid-stale", pid, detail: "pid recycled after a reboot — it is not this worker; nothing killed" });
1472
+ continue;
1473
+ }
1382
1474
  try {
1383
1475
  if (process.platform === "win32") {
1384
1476
  // /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");