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/crewbus.js CHANGED
@@ -42,8 +42,8 @@ import { execFileSync, spawn } from "node:child_process";
42
42
  // at top level so the import graph (store <- everyone; identity <- sync/spawn/
43
43
  // mail/groups/channels/web/relay/export) has no evaluation-order hazards.
44
44
  import { BOARD_VERSION, BROADCAST_AFTER, MAX_BODY_CHARS, MAX_RECIPIENTS, MAX_SPAWN, VALUE_FLAGS, boardDir, chmodAgentFile, cleanArtifact, cleanBranchPrefix, cleanChannelName, cleanGroupName, cleanPriority, cleanReply, cleanSenderType, cleanSubject, cleanWebName, dirs, ensureBoard, fail, findBoardUpward, getFlag, gitRevForBoard, listJson, newId, optionalAgent, parseDuration, readBoardMeta, readJson, refuseDriveRootBoard, requireBoard, resolveAgent, restArgs, sanitizeName, writeBoardMeta, writeExclusiveJson, writeJson, nextHlc, stampSyncDoc, hlcCompare, SEND_RATE_CAP, SEND_RATE_WINDOW_MS, MAX_FWD_DEPTH, DEDUPE_WINDOW_MS, webErr } from "./lib/store.js";
45
- import { VALID_ROLES, agentTokenMatches, assertMintWon, authorize, authorizeCheck, checkToken, cleanRole, countAgentRecords, defaultRoleForNew, ensureLoopbackOperator, ensureSender, hashToken, isHashRevoked, mergeAgentDoc, mergeSyncedAgent, mintToken, newSalt, readAgent, readBoardAcl, resolveToken, revokedPathForHash, roleOfRecord, sanitizeAgentForSync, stripAgentSecrets, timingSafeEqualStr, touchAgent, writeAgentFile, writeBoardAcl, isBoardFrozen } from "./lib/identity.js";
46
- import { saveTokenFile } from "./lib/tokenfile.js";
45
+ import { VALID_ROLES, agentTokenMatches, assertMintWon, authorize, authorizeCheck, checkToken, cleanRole, countAgentRecords, defaultRoleForNew, ensureLoopbackOperator, ensureSender, hashToken, isHashRevoked, mergeAgentDoc, mergeSyncedAgent, mintToken, newSalt, readAgent, readBoardAcl, recoverIdentity, reservedNameReason, resolveToken, revokedPathForHash, roleOfRecord, sanitizeAgentForSync, stripAgentSecrets, timingSafeEqualStr, touchAgent, writeAgentFile, writeBoardAcl, isBoardFrozen } from "./lib/identity.js";
46
+ import { saveTokenFile, loadTokenFile } from "./lib/tokenfile.js";
47
47
  import { CLIENT_TLS, SYNC_LWW, cleanSyncRel, clientInsecureFromArgs, crewSurvey, httpJson, readPemFlag, readSyncState, readTombstones, relayAuthEntries, relayCredFor, relayCredHeaders, setupClientTls, splitByWeight, syncRound, syncWalk, warnInsecureOnce, writeSyncState, writeTombstone, SYNC_SUBS, SYNC_UNION, RELAY_CAPS, SUB_CAP, SUB_CAP_NOTE, tombstoneIdForRel, readSyncDoc } from "./lib/sync.js";
48
48
  import { devicePath, isLoopbackHost, newDeviceCred, newPairToken, pairingPath, parseDeviceCred, readDevice, readRelayState, relaySecretFromArgs, remoteSpawn, requireRelayClientCert, requireRelaySecret, requireScope, tryAcquireFence, verifyOidcJwt, writeRelayState, relayStatePath, bearerFromReq, getOidcConfig, getOidcJwks, b64urlDecode, b64urlJson, jwsRawToDer, oidcGetJson, OIDC_SKEW_SEC, OIDC_JWKS_TTL_MS, OIDC_ALG_HASH, OIDC_EC_SIZE, deviceFromReq } from "./lib/relay.js";
49
49
  import { assertGitCheckout, bootRespawnedWorker, bootWorker, buildCoordinatorPrompt, buildCrewContext, buildRespawnBrief, buildRespawnTarget, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, isPidStale, killWorkers, LEAD_NAME, maybeIsolate, opencodeStorageStatus, parseAllowEnv, pidAlive, provisionAutoLead, provisionBranch, provisionWorktree, readWorkerSession, requireAutoConfirm, resolveOpencodeExe, sandboxPresent, scrubChildEnv, syncWorkerSession, workerStatus, worktreeStamp, defaultMaxTurnsFor, ensureBoardCliShim, installCliToUserPath } from "./lib/spawn.js";
@@ -52,7 +52,7 @@ import { ackedIds, checkSendRateLimit, deliverDMs, enforceMaxChars, filterDigest
52
52
  import { batchReplyIds, collectBatch, contributingGroups, expandGroups, expandGroupsOrFail, gatherTelemetry, groupTelemetryData, heuristicSenderType, readGroup, ensureGroupCreatedAt, readResultRecord, writeResultRecord, findFirstVerifiedReply } from "./lib/groups.js";
53
53
  import { publishArtifact, adoptArtifact, verifyArtifact, readArtifactById, listArtifacts, listLessons, postLesson, selectLessons, renderWorkbenchBlock, workbenchMetrics, cleanArtifactId, cleanLessonScope, parseArtifactDeps } from "./lib/workbench.js";
54
54
  import { appendChannelPost, channelLogPath, groupChannelName, lockAlive, lockPath, mergeChannelText, mirrorToGroupChannels, printChannelPost, readChannelPosts, readLock, summarizePosts, writeChannelCursor, SUMMARY_STOP, channelCursorPath, readChannelCursor, lockHash, acquireLockDoc, releaseLockDoc, tailChannelPosts, listLocks, parseChannelText } from "./lib/channels.js";
55
- import { boardSnapshot, cmdWeb, escapeHtml, fleetSnapshot, channelsSnapshot, resultsSnapshot, auditSnapshot, handleApiAck, renderBoardHtml, handleApiKill, handleApiLaunch, handleWebDashboardRoute } from "./lib/web.js";
55
+ import { boardSnapshot, cmdWeb, escapeHtml, fleetSnapshot, channelsSnapshot, resultsSnapshot, auditSnapshot, handleApiAck, renderBoardHtml, handleApiKill, handleApiLaunch, handleWebDashboardRoute, renderPairHtml } from "./lib/web.js";
56
56
  import { LAUNCH_DRIVER_FALLBACK, PAIR_SCOPES, advertiseEnv, buildPairUrl, detectHarnessBinaries, formatHarnessMenu, isBodyFileRef, launchDrivers, parseCountChoice, parseHarnessChoice, parsePermissionChoice, parseYesNo, probeBinary, validateLaunchPlan, HARNESS_MODELS, getDiscoveredModels, refreshDiscoveredModels } from "./lib/launch.js";
57
57
  import readline from "node:readline";
58
58
 
@@ -123,7 +123,7 @@ import readline from "node:readline";
123
123
  // reads the same comma/newline-separated list from a file so large fan-outs
124
124
  // don't hit Windows argv limits (~8191 chars).
125
125
  // §4.4 value-taking flags (skipped with their value by restArgs).
126
- for (const _f of ["--sender-type", "--fwd", "--secret", "--device", "--pair-token", "--pair-label", "--label", "--ttl", "--id", "--allow-env", "--allow-cmd", "--workdir-root", "--budget-tokens", "--budget-minutes", "--tls-cert", "--tls-key", "--tls-ca", "--mtls-ca", "--mtls-cert", "--mtls-key", "--oidc-issuer", "--oidc-audience", "--issuer", "--client-id", "--bearer", "--oidc-token", "--expires-in", "--service", "--offboard", "--target", "--reason", "--role", "--for", "--default-role", "--freeze", "--unfreeze", "--out", "--in", "--into", "--key-env", "--key-file", "--every", "--keep", "--out-dir", "--max-bytes", "--max-agents", "--max-channels", "--tenant", "--audit-forward", "--audit-forward-key", "--standby", "--promote-on-miss", "--fence", "--relay-interval", "--relays", "--weights", "--relay-auth", "--via", "--weight"]) VALUE_FLAGS.add(_f);
126
+ for (const _f of ["--sender-type", "--fwd", "--secret", "--device", "--pair-token", "--pair-label", "--label", "--ttl", "--id", "--allow-env", "--allow-cmd", "--workdir-root", "--budget-tokens", "--budget-minutes", "--lead-budget-tokens", "--lead-budget-minutes", "--tls-cert", "--tls-key", "--tls-ca", "--mtls-ca", "--mtls-cert", "--mtls-key", "--oidc-issuer", "--oidc-audience", "--issuer", "--client-id", "--bearer", "--oidc-token", "--expires-in", "--service", "--offboard", "--target", "--reason", "--role", "--for", "--default-role", "--freeze", "--unfreeze", "--out", "--in", "--into", "--key-env", "--key-file", "--every", "--keep", "--out-dir", "--max-bytes", "--max-agents", "--max-channels", "--tenant", "--audit-forward", "--audit-forward-key", "--standby", "--promote-on-miss", "--fence", "--relay-interval", "--relays", "--weights", "--relay-auth", "--via", "--weight"]) VALUE_FLAGS.add(_f);
127
127
 
128
128
  // ---------------------------------------------------------------------------
129
129
  // §4.4 Security and integrity helpers (zero-dep, Windows-tolerant)
@@ -319,7 +319,6 @@ function agentTokenMatches(rec, token) {
319
319
  return false;
320
320
  }
321
321
  }
322
- if (rec.token) return timingSafeEqual(String(token), String(rec.token));
323
322
  return false;
324
323
  }
325
324
 
@@ -345,7 +344,7 @@ function resolveToken(args) {
345
344
  }
346
345
 
347
346
  // First send as a new name mints its record + token (first-claim-wins).
348
- // Stores only a salted hash; legacy plaintext migrates on successful auth.
347
+ // Stores only a salted hash.
349
348
  function ensureSender(root, agent, token) {
350
349
  const rec = readAgent(root, agent);
351
350
  if (!rec) {
@@ -355,7 +354,7 @@ function ensureSender(root, agent, token) {
355
354
  writeAgentHashed(path.join(root, "agents", agent + ".json"), { name: agent, firstSeen: now, lastSeen: now, tokenHash: hashToken(fresh, salt), salt });
356
355
  return { created: true, token: fresh };
357
356
  }
358
- if (!rec.tokenHash && !rec.token) {
357
+ if (!rec.tokenHash) {
359
358
  const fresh = mintToken();
360
359
  const salt = newSalt();
361
360
  rec.tokenHash = hashToken(fresh, salt);
@@ -364,15 +363,7 @@ function ensureSender(root, agent, token) {
364
363
  writeAgentHashed(path.join(root, "agents", agent + ".json"), rec);
365
364
  return { created: true, token: fresh };
366
365
  }
367
- if (rec.token && !rec.tokenHash) {
368
- if (!agentTokenMatches(rec, token)) throw new Error(\`bad token for "\${agent}" (pass token or set CREWBUS_TOKEN)\`);
369
- const salt = newSalt();
370
- rec.tokenHash = hashToken(String(token), salt);
371
- rec.salt = salt;
372
- delete rec.token;
373
- writeAgentHashed(path.join(root, "agents", agent + ".json"), rec);
374
- return { created: false };
375
- }
366
+
376
367
  if (!agentTokenMatches(rec, token)) throw new Error(\`bad token for "\${agent}" (pass token or set CREWBUS_TOKEN)\`);
377
368
  return { created: false };
378
369
  }
@@ -1106,23 +1097,85 @@ export const DmWatchPlugin = async ({ client, directory }) => {
1106
1097
  }, POLL_MS);
1107
1098
  poll().catch(() => {});
1108
1099
 
1100
+ // C1 lite recovery (self-contained: no bin/lib imports — the plugin ships
1101
+ // standalone). Same scoring spirit as \`crewbus recover\`, minus the
1102
+ // token-hash cross-check: session binding +4, token file +1, cwd match +1.
1103
+ // Returns [{ name, role, score, proven, why }] best-first.
1104
+ function recoverCandidatesLite(sessionID) {
1105
+ const cands = [];
1106
+ try {
1107
+ const agentsDir = path.join(root, "agents");
1108
+ const logsDir = path.join(root, "logs");
1109
+ const tokenNames = new Set();
1110
+ try {
1111
+ for (const f of fs.readdirSync(logsDir)) if (f.endsWith(".token")) tokenNames.add(f.slice(0, -6).toLowerCase());
1112
+ } catch {}
1113
+ const cwd = String(process.cwd() || "").replace(/\\\\/g, "/").toLowerCase();
1114
+ for (const f of fs.readdirSync(agentsDir)) {
1115
+ if (!f.endsWith(".json")) continue;
1116
+ const doc = readJsonSafe(path.join(agentsDir, f));
1117
+ if (!doc || !doc.name || doc.offboarded) continue;
1118
+ let score = 0;
1119
+ const why = [];
1120
+ if (sessionID && doc.sessionId && String(doc.sessionId) === String(sessionID)) {
1121
+ score += 4;
1122
+ why.push("session id matches register binding");
1123
+ }
1124
+ if (tokenNames.has(String(doc.name).toLowerCase())) {
1125
+ score += 1;
1126
+ why.push("token file exists for this name");
1127
+ }
1128
+ if (doc.lastDir && cwd && String(doc.lastDir).replace(/\\\\/g, "/").toLowerCase() === cwd) {
1129
+ score += 1;
1130
+ why.push("worked from this directory");
1131
+ }
1132
+ if (score <= 0) continue;
1133
+ cands.push({ name: doc.name, role: doc.role || "peer", score, proven: false, why: why.join("; ") });
1134
+ }
1135
+ } catch {}
1136
+ cands.sort((a, b) => b.score - a.score || String(a.name).localeCompare(String(b.name)));
1137
+ return cands;
1138
+ }
1139
+
1109
1140
  return {
1110
1141
  // Compaction rehydration: opencode summarizes this session, so the agent
1111
1142
  // wakes up forgetting its name, board, and token. Push the same identity
1112
- // card \`crewbus-hook compact\` prints into the summary prompt.
1143
+ // card \`crewbus-hook compact\` prints into the summary prompt. When the
1144
+ // session↔agent map misses, try board-side recovery BEFORE calling the
1145
+ // agent "unknown" (post-compaction rehydration: C1):
1146
+ // 1. register --session <id> binding stored on the agent doc
1147
+ // 2. CREWBUS_AGENT env (set when the session boots via launch)
1148
+ // 3. token-file + cwd evidence (agents roster ∩ logs/*.token)
1149
+ // A resolved candidate drives the card; an unresolved one prints the
1150
+ // crewbus recover path instead — never suggest re-registering a thrown
1151
+ // "unknown" (those sentinel names refuse to mint, and for good reason).
1113
1152
  "experimental.session.compacting": async (input, output) => {
1114
1153
  try {
1115
1154
  if (!output || !Array.isArray(output.context)) return;
1116
1155
  refreshAgentMap();
1117
1156
  let agent = null;
1118
1157
  for (const [name, sid] of agentToSession) if (sid === (input && input.sessionID)) agent = name;
1119
- const who = agent || "unknown";
1120
- output.context.push(\`crewbus: context refreshed after compaction. You are '\${who}' on board \${root}.\`);
1121
- output.context.push(\`Token: read \${path.join(root, "logs", who + ".token")} into CREWBUS_TOKEN (0600 file written at register/mint). Lost it? Ask your lead/admin to revoke it, then re-register for a fresh one.\`);
1122
- output.context.push(\`Then: crewbus inbox --from \${who} --unacked --digest (escalate to full reads on hits).\`);
1123
- const doc = agent ? readJsonSafe(path.join(root, "agents", agent + ".json")) : null;
1124
- const ws = doc && doc.briefId ? readJsonSafe(path.join(root, "worker-sessions", agent + ".json")) : null;
1125
- if (ws && (ws.promptPath || ws.origPromptPath)) output.context.push(\`Your brief: re-read \${ws.promptPath || ws.origPromptPath} from worker-sessions if present.\`);
1158
+ let proven = false;
1159
+ if (!agent) agent = (process.env.CREWBUS_AGENT || "").trim() || null;
1160
+ if (!agent) {
1161
+ const cands = recoverCandidatesLite(input && input.sessionID);
1162
+ if (cands[0] && cands[0].score >= 2) {
1163
+ agent = cands[0].name;
1164
+ proven = cands[0].proven || cands[0].score >= 3;
1165
+ }
1166
+ }
1167
+ if (agent) {
1168
+ output.context.push(\`crewbus: context refreshed after compaction. You are '\${agent}' on board \${root}\${proven ? " (identity cross-checked)" : ""}.\`);
1169
+ output.context.push(\`Token: read \${path.join(root, "logs", agent + ".token")} into CREWBUS_TOKEN (0600 file written at register/mint). Lost it? Ask your lead/admin to revoke it, then re-register for a fresh one.\`);
1170
+ output.context.push(\`Then: crewbus inbox --from \${agent} --unacked --digest (escalate to full reads on hits).\`);
1171
+ const doc = readJsonSafe(path.join(root, "agents", agent + ".json"));
1172
+ const ws = doc && doc.briefId ? readJsonSafe(path.join(root, "worker-sessions", agent + ".json")) : null;
1173
+ if (ws && (ws.promptPath || ws.origPromptPath)) output.context.push(\`Your brief: re-read \${ws.promptPath || ws.origPromptPath} from worker-sessions if present.\`);
1174
+ } else {
1175
+ output.context.push(\`crewbus: context refreshed after compaction, but THIS session's agent could not be identified on board \${root}.\`);
1176
+ output.context.push(\`Recover (read-only, never mints): crewbus recover\${input && input.sessionID ? \` --session \${input.sessionID}\` : ""} — it ranks candidate identities from the board (register session binding, token files, cwd history) and prints exact resume commands.\`);
1177
+ output.context.push(\`NEVER re-register as 'unknown'/'me'/'you' — those sentinel names are reserved and refuse to mint; recover your real identity instead.\`);
1178
+ }
1126
1179
  } catch {}
1127
1180
  },
1128
1181
  dispose: async () => {
@@ -1189,21 +1242,6 @@ function upsertAgentsMd(cwd, snippet) {
1189
1242
  console.log("Updated crewbus section in AGENTS.md");
1190
1243
  return;
1191
1244
  }
1192
- // Remove legacy v1 block if present (it starts with "## Agent board" and mentions the old workflow)
1193
- if (cur.includes("COORDINATOR PRIME DIRECTIVE") || cur.includes("tasks ready")) {
1194
- const lines = cur.split("\n");
1195
- const out = [];
1196
- let skipping = false;
1197
- for (const ln of lines) {
1198
- if (/^## Agent board/.test(ln)) { skipping = true; continue; }
1199
- if (skipping && /^## /.test(ln)) { skipping = false; }
1200
- if (!skipping) out.push(ln);
1201
- }
1202
- cur = out.join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
1203
- fs.writeFileSync(agentsMd, cur);
1204
- console.log("Removed legacy crewbus v1 section from AGENTS.md");
1205
- cur = fs.readFileSync(agentsMd, "utf8");
1206
- }
1207
1245
  if (!cur.includes("crewbus") && !cur.includes("crewbus DM")) {
1208
1246
  fs.appendFileSync(agentsMd, "\n" + snippet);
1209
1247
  console.log("Appended crewbus DM section to AGENTS.md");
@@ -1257,7 +1295,7 @@ function installOpencodeFiles(cwd, force) {
1257
1295
  // marker dirs (.opencode/.claude/.codex/.agents/.grok/.cursor). No markers at all
1258
1296
  // keeps the legacy default (opencode) so existing checkouts don't change.
1259
1297
 
1260
- const HARNESSES = ["opencode", "claude", "codex", "antigravity", "grok", "cursor", "generic"];
1298
+ const HARNESSES = ["opencode", "claude", "codex", "antigravity", "grok", "cursor"];
1261
1299
  const HARNESS_MARKERS = {
1262
1300
  opencode: ".opencode",
1263
1301
  claude: ".claude",
@@ -1541,7 +1579,6 @@ function mergeCursorHooks(file, hookAbs, boardExtra) {
1541
1579
  // `mcp(server/*)`, `command(...)`); .agents/ has no documented
1542
1580
  // project-local permissions allowlist.
1543
1581
  // - copilot: SKIPPED — not an init --harness adapter in this repo.
1544
- // - generic: SKIPPED — no config surface.
1545
1582
  const CLAUDE_BOARD_ALLOW = [
1546
1583
  "mcp__crewbus__*",
1547
1584
  "Bash(node *crewbus* *)",
@@ -1700,8 +1737,6 @@ waiters (PostToolUse/SessionStart \`asyncRewake\`) wake the session when mail la
1700
1737
  cursor: (cli) =>
1701
1738
  `On Cursor use the \`crewbus\` MCP server (\`.cursor/mcp.json\`) for DM tools — approve/enable it in Cursor settings.\n` +
1702
1739
  `SessionStart + stop hooks (\`.cursor/hooks.json\`) inject waiting DMs. Set \`CREWBUS_AGENT=<you>\` once per terminal so hooks know who you are.`,
1703
- generic: (cli) =>
1704
- `On any other harness: send with \`${cli} send\`, read with \`inbox\`, or block with \`listen\`. Poll \`inbox\` at session start and after each task.`,
1705
1740
  };
1706
1741
 
1707
1742
  function upsertHarnessSections(cwd, cli, ids) {
@@ -1874,7 +1909,6 @@ function cmdInit(args) {
1874
1909
  }
1875
1910
  }
1876
1911
  if (noOpencode) ids = ids.filter((h) => h !== "opencode");
1877
- if (ids.includes("generic") && ids.length > 1) ids = ids.filter((h) => h !== "generic");
1878
1912
  const nonLocal = root !== path.join(process.cwd(), ".crewbus");
1879
1913
  const boardExtra = nonLocal ? `--board "${root.split(path.sep).join("/")}"` : "";
1880
1914
  const mcpEnv = nonLocal ? { CREWBUS_DIR: root } : null;
@@ -1883,7 +1917,6 @@ function cmdInit(args) {
1883
1917
  const ctx = { force, hookAbs: binAbs("crewbus-hook.js"), mcpAbs: binAbs("crewbus-mcp.js"), boardExtra, mcpEnv, portable };
1884
1918
  const followUps = [];
1885
1919
  for (const h of ids) {
1886
- if (h === "generic") continue;
1887
1920
  for (const f of applyHarness(process.cwd(), h, ctx)) {
1888
1921
  if (!followUps.includes(f)) followUps.push(f);
1889
1922
  }
@@ -1906,6 +1939,49 @@ function cmdInit(args) {
1906
1939
  // Durations for prune --older-than: 30, 90s, 15m, 24h, 7d, 2w (bare = seconds).
1907
1940
 
1908
1941
 
1942
+ // recover: read-only identity triage after compaction/restart amnesia.
1943
+ // Never writes, never mints — prints candidate identities with evidence and
1944
+ // the exact commands to resume. Read-side: refuses to plant a board.
1945
+ function cmdRecover(args) {
1946
+ const root = boardDir(args);
1947
+ refuseDriveRootBoard(root, args);
1948
+ const d = requireBoard(root);
1949
+ const opts = {
1950
+ sessionID: getFlag(args, "--session"),
1951
+ cwd: getFlag(args, "--cwd") || process.cwd(),
1952
+ hashToken,
1953
+ loadTokenFile,
1954
+ };
1955
+ const cands = recoverIdentity(d, opts);
1956
+ if (cands.length === 0) {
1957
+ console.log(`no identity candidates on [board ${d.root}] — if the name predates tokens, ask an admin: register --from <admin> --for <name>; otherwise re-register your real name`);
1958
+ return;
1959
+ }
1960
+ const top = cands[0];
1961
+ for (const c of cands) {
1962
+ const tag = c.proven ? "proven" : "hint";
1963
+ console.log(`${tag.padEnd(6)} ${c.name} (role ${c.role}, score ${c.score}) — ${c.why}`);
1964
+ }
1965
+ const tokPath = path.join(d.root, "logs", `${top.name}.token`);
1966
+ console.log(`\nresume as '${top.name}':`);
1967
+ if (!top.proven) console.log(` 0. cross-check yourself first (the token file may be stale): open ${tokPath} and verify it is YOUR token`);
1968
+ console.log(resumeScriptLines(top, d));
1969
+ console.log(`then: crewbus inbox --from ${top.name} --unacked --digest (escalate to full reads on hits)`);
1970
+ }
1971
+
1972
+ // One shared resume script for the top candidate (recover output only).
1973
+ function resumeScriptLines(top, d) {
1974
+ const tokPath = path.join(d.root, "logs", `${top.name}.token`);
1975
+ const lines = [];
1976
+ lines.push(` 1. set CREWBUS_AGENT=${top.name} (so future hooks/push know you)`);
1977
+ const ps = process.platform === "win32";
1978
+ lines.push(ps
1979
+ ? ` 2. $env:CREWBUS_TOKEN = Get-Content "${tokPath}" (0600 file written at register/mint)`
1980
+ : ` 2. export CREWBUS_TOKEN="$(cat ${tokPath})" (0600 file written at register/mint)`);
1981
+ lines.push(` 3. brief/resume context: worker-sessions/${top.name}.json holds your promptPath (re-read it if you were a spawned worker)`);
1982
+ return lines.join("\n");
1983
+ }
1984
+
1909
1985
  function cmdRegister(args) {
1910
1986
  const root = boardDir(args);
1911
1987
  refuseDriveRootBoard(root, args);
@@ -1943,6 +2019,8 @@ function cmdRegister(args) {
1943
2019
  // (this is register, so --target here means grant). Bare --for without
1944
2020
  // --role just touches/creates the target.
1945
2021
  const target = sanitizeName(forTargetRaw, "agent");
2022
+ const targetSentinel = reservedNameReason(target);
2023
+ if (targetSentinel) fail(targetSentinel);
1946
2024
  const admin = resolveAgent(args, "agent");
1947
2025
  checkToken(d, admin, resolveToken(args));
1948
2026
  authorize(d, admin, "role-grant");
@@ -2018,7 +2096,12 @@ function cmdRegister(args) {
2018
2096
  console.log(`granted ${target} role ${wantRole} [board ${d.root}]`);
2019
2097
  return;
2020
2098
  }
2021
- const doc = touchAgent(d, target, { sessionId: getFlag(args, "--session") || undefined, lastDir: process.cwd() });
2099
+ // NB: touchAgent on an EXISTING grant: --session only when given, else a
2100
+ // sessionless admin touch must not wipe the register-time binding (C1).
2101
+ const iSession = getFlag(args, "--session");
2102
+ const adminTouch = { lastDir: process.cwd() };
2103
+ if (iSession) adminTouch.sessionId = iSession;
2104
+ const doc = touchAgent(d, target, adminTouch);
2022
2105
  if (doc.offboarded !== undefined) { delete doc.offboarded; writeAgentFile(d, target, doc); }
2023
2106
  console.log(`registered ${target} [board ${d.root}]`);
2024
2107
  return;
@@ -2027,8 +2110,15 @@ function cmdRegister(args) {
2027
2110
  const serviceRaw = getFlag(args, "--service");
2028
2111
  const serviceFlag = serviceRaw !== undefined || args.includes("--service");
2029
2112
  const agent = serviceRaw !== undefined && serviceRaw !== "" ? sanitizeName(serviceRaw, "agent") : resolveAgent(args, "agent");
2113
+ const agentSentinel = reservedNameReason(agent);
2114
+ if (agentSentinel) fail(agentSentinel);
2030
2115
  const session = getFlag(args, "--session");
2031
2116
  const token = resolveToken(args);
2117
+ // mergeAgentDoc deletes patch keys whose value is undefined — so the
2118
+ // register binding must be added ONLY when a session is actually given,
2119
+ // else every sessionless re-register would wipe the binding (C1).
2120
+ const extra = { lastDir: process.cwd() };
2121
+ if (session) extra.sessionId = session;
2032
2122
  const expiresRaw = getFlag(args, "--expires-in");
2033
2123
  const expiresAt = expiresRaw !== undefined ? new Date(Date.now() + parseDuration(expiresRaw)).toISOString() : undefined;
2034
2124
  const prev = readAgent(d, agent);
@@ -2084,15 +2174,8 @@ function cmdRegister(args) {
2084
2174
  return;
2085
2175
  }
2086
2176
  if (!agentTokenMatches(prev, token)) fail(`name "${agent}" is claimed (bad/missing token — pass --token or set CREWBUS_TOKEN)`);
2087
- // Migrate legacy plaintext on successful auth.
2088
- if (prev.token && !prev.tokenHash) {
2089
- const salt = newSalt();
2090
- prev.tokenHash = hashToken(String(token), salt);
2091
- prev.salt = salt;
2092
- delete prev.token;
2093
- writeAgentFile(d, agent, prev);
2094
- }
2095
- const extra = { sessionId: session || undefined, lastDir: process.cwd() };
2177
+ // `extra` (built right after --session parsing above) has sessionId only
2178
+ // when given, so sessionless re-registers keep the prior binding.
2096
2179
  if (expiresRaw !== undefined) extra.expiresAt = expiresAt;
2097
2180
  if (serviceFlag) extra.service = true;
2098
2181
  const selfRoleWant = getFlag(args, "--role");
@@ -2108,10 +2191,6 @@ function cmdRegister(args) {
2108
2191
  }
2109
2192
  process.stderr.write(`crewbus: warning: --role ignored (only an admin can grant roles; current role "${roleOfRecord(prev)}")\n`);
2110
2193
  }
2111
- if (!prev.role) {
2112
- prev.role = "lead"; // backfill legacy records so agents --json exposes roles
2113
- try { writeAgentFile(d, agent, prev); } catch {}
2114
- }
2115
2194
  const doc = touchAgent(d, agent, extra);
2116
2195
  console.log(`registered ${agent}${doc.sessionId ? ` (session ${doc.sessionId})` : ""} [board ${d.root}]`);
2117
2196
  }
@@ -2467,7 +2546,7 @@ function cmdGroup(args) {
2467
2546
  const running = [];
2468
2547
  for (const m of t.members) {
2469
2548
  const rec = readAgent(d, m);
2470
- if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid)) running.push({ member: m, pid: rec.spawnedPid });
2549
+ if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt)) running.push({ member: m, pid: rec.spawnedPid });
2471
2550
  }
2472
2551
  const out = { ...t, running };
2473
2552
  if (rest.includes("--json")) {
@@ -2631,7 +2710,9 @@ function cmdChannel(args) {
2631
2710
  if (!body || !body.trim()) fail('missing message body (--body "...")');
2632
2711
  if (body.length > MAX_BODY_CHARS) fail(`message body too large (max ${MAX_BODY_CHARS} chars)`);
2633
2712
  const minted = ensureSender(d, from, resolveToken(rest));
2634
- authorize(d, from, "channel-post");
2713
+ // Member-scoped posting (C4): grp-<g> channels admit members of <g>;
2714
+ // board channels + foreign groups stay lead|admin (authorizeCheck).
2715
+ authorize(d, from, "channel-post", { channelGroup: chan.startsWith("grp-") ? chan.slice(4) : undefined });
2635
2716
  enforceBytesQuota(d, Buffer.byteLength(body.trim(), "utf8") + 1500);
2636
2717
  touchAgent(d, from, { lastDir: process.cwd() });
2637
2718
  const tokenHint = minted.created ? ` identity '${from}' claimed, token ${minted.token} (set CREWBUS_TOKEN=${minted.token})` : "";
@@ -2743,7 +2824,11 @@ function cmdSend(args) {
2743
2824
  if (recipients.length === 1 && !replyTo) {
2744
2825
  const dup = findDuplicateSend(d, from, recipients[0], body.trim());
2745
2826
  if (dup) {
2746
- touchAgent(d, from, { sessionId: session || undefined, lastDir: process.cwd() });
2827
+ // NB: sessionId only when given — mergeAgentDoc deletes undefined keys,
2828
+ // so a sessionless send must NOT wipe a register-time session binding.
2829
+ const dupExtra = { lastDir: process.cwd() };
2830
+ if (session) dupExtra.sessionId = session;
2831
+ touchAgent(d, from, dupExtra);
2747
2832
  console.log(`sent ${dup.id} -> ${recipients[0]} [board ${d.root}] (deduped: same body within 10s)`);
2748
2833
  return;
2749
2834
  }
@@ -2757,7 +2842,10 @@ function cmdSend(args) {
2757
2842
  const mirrorExtra = alsoChannel ? groupNames.length * (bodyLen + 1000) : 0;
2758
2843
  enforceBytesQuota(d, nFiles * (bodyLen + 1500) + mirrorExtra);
2759
2844
  }
2760
- touchAgent(d, from, { sessionId: session || undefined, lastDir: process.cwd() });
2845
+ // Same sentinel-wipe guard as above: sessionless sends keep bindings.
2846
+ const touchExtra = { lastDir: process.cwd() };
2847
+ if (session) touchExtra.sessionId = session;
2848
+ touchAgent(d, from, touchExtra);
2761
2849
  const tokenHint = minted.created ? ` identity '${from}' claimed, token ${minted.token} (set CREWBUS_TOKEN=${minted.token})` : "";
2762
2850
  const rev = gitRevForBoard(root);
2763
2851
  const at = new Date().toISOString();
@@ -2766,8 +2854,9 @@ function cmdSend(args) {
2766
2854
  appendChainRecord(d, from, "send", { to: recipients.slice(0, 20), count: recipients.length, batch: res.batch });
2767
2855
  const mirrored = alsoChannel
2768
2856
  ? mirrorToGroupChannels(d, { groups: groupNames, from, body: body.trim(), subject, replyTo, batch: res.batch || (res.items[0] && res.items[0].id), priority, rev, at })
2769
- : [];
2770
- const chanNote = mirrored.length > 0 ? ` +channel ${mirrored.map((m) => m.channel).join(",")}` : "";
2857
+ : { mirrored: [], skipped: [] };
2858
+ const chanNote = (mirrored.mirrored.length > 0 ? ` +channel ${mirrored.mirrored.map((m) => m.channel).join(",")}` : "")
2859
+ + (mirrored.skipped.length > 0 ? ` [channel mirror skipped, members-only: ${mirrored.skipped.map((s) => s.group).join(",")}]` : "");
2771
2860
  if (res.mode === "broadcast") {
2772
2861
  const who = res.isAll ? "@all" : `${recipients.length} recipients`;
2773
2862
  console.log(`sent ${res.isAll ? "@all" : recipients.length + " messages"} via broadcast ${res.batch} to ${who} [board ${d.root}]${chanNote}${tokenHint}`);
@@ -2802,7 +2891,7 @@ function cmdSend(args) {
2802
2891
  // fails to launch. Children inherit CREWBUS_DIR + CREWBUS_AGENT, log
2803
2892
  // to .crewbus/logs/<name>-<stamp>.log, and report their pid back here.
2804
2893
  // opencode runs `opencode run` with the brief attached via --file (no shell
2805
- // quoting of the long prompt); generic runs your --cmd string with the same
2894
+ // quoting of the long prompt); each driver runs with the same
2806
2895
  // board env. Spawn caps at MAX_SPAWN — bigger crews get a broadcast DM.
2807
2896
  // ---------------------------------------------------------------------------
2808
2897
 
@@ -2822,15 +2911,28 @@ function cmdSpawn(args) {
2822
2911
  const d = ensureBoard(root);
2823
2912
  const from = resolveAgent(args, "sender");
2824
2913
  const countRaw = getFlag(args, "--count");
2914
+ // Lead-revive (C9): `--count 0` boots NOTHING except the auto-coordinator
2915
+ // lane — for when the lead died (crash/reboot) and the crew needs its
2916
+ // coordinator back without re-briefing or re-booting any worker. Rows stay
2917
+ // put: no DMs are delivered, no worker pids are touched. Conflicting
2918
+ // worker selectors are refused (this path has no worker operands).
2919
+ let revive = false;
2825
2920
  let autoNames = [];
2826
2921
  if (countRaw !== undefined) {
2827
2922
  const n = Number(countRaw);
2828
- if (!Number.isInteger(n) || n <= 0) fail("--count must be a positive integer");
2829
- const prefix = String(getFlag(args, "--prefix") || "worker").trim().toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 30);
2830
- if (!prefix) fail("invalid --prefix");
2831
- for (let i = 1; i <= n; i++) autoNames.push(`${prefix}-${i}`);
2923
+ if (!Number.isInteger(n) || n < 0) fail("--count must be >= 0 (0 = revive ONLY the auto-coordinator lane, no workers; workers want a positive --count)");
2924
+ if (n === 0) {
2925
+ revive = true;
2926
+ if (getFlag(args, "--to") !== undefined || getFlag(args, "--to-file") !== undefined || getFlag(args, "--to-group") !== undefined) {
2927
+ fail("--count 0 revives ONLY the auto-coordinator lane (no workers): drop --to/--to-file/--to-group, or pass a positive --count to spawn workers");
2928
+ }
2929
+ } else {
2930
+ const prefix = String(getFlag(args, "--prefix") || "worker").trim().toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 30);
2931
+ if (!prefix) fail("invalid --prefix");
2932
+ for (let i = 1; i <= n; i++) autoNames.push(`${prefix}-${i}`);
2933
+ }
2832
2934
  }
2833
- const recipients = parseRecipients(getFlag(args, "--to"), getFlag(args, "--to-file"), expandGroupsOrFail(d, getFlag(args, "--to-group")).concat(autoNames));
2935
+ const recipients = revive ? [] : parseRecipients(getFlag(args, "--to"), getFlag(args, "--to-file"), expandGroupsOrFail(d, getFlag(args, "--to-group")).concat(autoNames));
2834
2936
  if (recipients.includes("@all")) fail("spawn --to @all is refused: @all membership is dynamic (late joiners included) — name the workers explicitly");
2835
2937
  const maxSpawnRaw = getFlag(args, "--max-spawn");
2836
2938
  const maxSpawn = maxSpawnRaw === undefined ? MAX_SPAWN : Number(maxSpawnRaw);
@@ -2840,10 +2942,11 @@ function cmdSpawn(args) {
2840
2942
  // the pid record: refuse only names with a live pid, before anything is
2841
2943
  // written or booted. Stale or never-booted names are reusable (spawn
2842
2944
  // overwrites the pid) — so groups whose members already claimed names
2843
- // still boot fine.
2945
+ // still boot fine. A pid-recycled record (reboot + OS pid reuse) counts
2946
+ // as reusable too: the pid belongs to an unrelated process (C2).
2844
2947
  for (const name of recipients) {
2845
2948
  const rec = readAgent(d, name);
2846
- if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid)) {
2949
+ if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt)) {
2847
2950
  fail(`name "${name}" has a live worker (pid ${rec.spawnedPid}) — pick a fresh name via --prefix, or kill it first (spawn-kill --from ${from} --to ${name})`);
2848
2951
  }
2849
2952
  }
@@ -2854,13 +2957,11 @@ function cmdSpawn(args) {
2854
2957
  return s;
2855
2958
  }).filter(Boolean);
2856
2959
  if (harnesses.length === 0) harnesses.push("opencode");
2857
- const validDrivers = ["opencode", "claude", "codex", "grok", "antigravity", "cursor", "generic"];
2960
+ const validDrivers = ["opencode", "claude", "codex", "grok", "antigravity", "cursor"];
2858
2961
  for (const h of harnesses) {
2859
2962
  if (!validDrivers.includes(h)) fail(`unknown --harness "${h}" (want ${validDrivers.join("|")})`);
2860
2963
  }
2861
2964
  const harness = harnesses.join(",");
2862
- const cmd = getFlag(args, "--cmd");
2863
- if (harnesses.includes("generic") && !cmd) fail('generic harness needs --cmd "..." (runs with CREWBUS_DIR + CREWBUS_AGENT set)');
2864
2965
  const maxTurns = getFlag(args, "--max-turns");
2865
2966
  if (maxTurns !== undefined && !(Number(maxTurns) > 0)) fail("--max-turns must be a positive number");
2866
2967
  if (maxTurns !== undefined && !harnesses.some((h) => h === "claude" || h === "grok")) fail(`--max-turns only applies to claude/grok (got --harness ${harness})`);
@@ -2894,29 +2995,16 @@ function cmdSpawn(args) {
2894
2995
  const taskGroups = rosterGroups.filter((g) => groupNames.includes(g.name));
2895
2996
  const offTask = rosterGroups.length - taskGroups.length;
2896
2997
  const crewFor = (to, leadTarget) => buildCrewContext({ name: to, from, lead: leadTarget, subject, groups: taskGroups, myGroups: taskGroups.filter((g) => g.members.includes(to)).map((g) => g.name), offTask });
2897
- // Lead auto-assignment (§auto-lead): `--lead auto|board|none` (default: auto).
2898
- // Under `board` (or `auto` with a coding harness), spawn and lead are
2899
- // separated: workers pin replies to the board's standing 'lead' lane and a
2900
- // detached persistent coordinator is provisioned after the crew boots; the
2901
- // spawner stays boss (reads, milestone DMs). `--lead none` (or `auto` with
2902
- // purely generic harnesses) is the legacy star topology: replies pin to the
2903
- // spawner, nothing else is provisioned.
2998
+ // Lead auto-assignment (§auto-lead): default: auto.
2999
+ // Workers pin replies to the board's standing 'lead' lane and a detached
3000
+ // persistent coordinator is provisioned after the crew boots; the spawner
3001
+ // stays boss (reads, milestone DMs).
2904
3002
  const leadFlagRaw = getFlag(args, "--lead");
2905
- const hasCodingHarness = harnesses.some((h) => h !== "generic");
2906
- let leadMode;
2907
- if (leadFlagRaw === undefined) {
2908
- leadMode = hasCodingHarness ? "board" : "none";
2909
- } else {
2910
- leadMode = String(leadFlagRaw).trim().toLowerCase();
2911
- if (leadMode === "auto") {
2912
- leadMode = hasCodingHarness ? "board" : "none";
2913
- }
3003
+ if (leadFlagRaw !== undefined) {
3004
+ const raw = String(leadFlagRaw).trim().toLowerCase();
3005
+ if (raw !== "auto") fail(`invalid --lead "${leadFlagRaw}" (only --lead auto is supported)`);
2914
3006
  }
2915
- if (!["board", "none"].includes(leadMode)) fail(`invalid --lead "${leadFlagRaw}" (want auto|board|none)`);
2916
- if (leadMode === "board" && !hasCodingHarness) {
2917
- fail('--lead board needs a coding harness for the auto-coordinator (add --harness opencode, or pass --lead none under --harness generic)');
2918
- }
2919
- const leadTarget = leadMode === "board" ? "lead" : from;
3007
+ const leadTarget = "lead";
2920
3008
  const model = getFlag(args, "--model");
2921
3009
  const auto = args.includes("--auto");
2922
3010
  requireAutoConfirm(args);
@@ -2943,10 +3031,19 @@ function cmdSpawn(args) {
2943
3031
  }
2944
3032
  const budgetTokensRaw = getFlag(args, "--budget-tokens");
2945
3033
  const budgetMinutesRaw = getFlag(args, "--budget-minutes");
2946
- const budgetTokens = budgetTokensRaw === undefined ? undefined : Number(budgetTokensRaw);
2947
- const budgetMinutes = budgetMinutesRaw === undefined ? undefined : Number(budgetMinutesRaw);
2948
- if (budgetTokensRaw !== undefined && !(budgetTokens > 0)) fail("--budget-tokens must be a positive number");
2949
- if (budgetMinutesRaw !== undefined && !(budgetMinutes > 0)) fail("--budget-minutes must be a positive number");
3034
+ const budgetTokens = budgetTokensRaw === undefined ? undefined : Number(budgetTokensRaw);
3035
+ const budgetMinutes = budgetMinutesRaw === undefined ? undefined : Number(budgetMinutesRaw);
3036
+ if (budgetTokensRaw !== undefined && !(budgetTokens > 0)) fail("--budget-tokens must be a positive number");
3037
+ if (budgetMinutesRaw !== undefined && !(budgetMinutes > 0)) fail("--budget-minutes must be a positive number");
3038
+ // Coordinator budget (C5): same semantics as worker budgets, on the
3039
+ // auto-provisioned lead lane. Unset (the common case) = persistent boss-supervised
3040
+ // coordinator, same behavior as 10.0.10.
3041
+ const leadBudgetTokensRaw = getFlag(args, "--lead-budget-tokens");
3042
+ const leadBudgetMinutesRaw = getFlag(args, "--lead-budget-minutes");
3043
+ const leadBudgetTokens = leadBudgetTokensRaw === undefined ? undefined : Number(leadBudgetTokensRaw);
3044
+ const leadBudgetMinutes = leadBudgetMinutesRaw === undefined ? undefined : Number(leadBudgetMinutesRaw);
3045
+ if (leadBudgetTokensRaw !== undefined && !(leadBudgetTokens > 0)) fail("--lead-budget-tokens must be a positive number");
3046
+ if (leadBudgetMinutesRaw !== undefined && !(leadBudgetMinutes > 0)) fail("--lead-budget-minutes must be a positive number");
2950
3047
  const timeoutRaw = getFlag(args, "--timeout");
2951
3048
  let deadlineAt = undefined;
2952
3049
  if (timeoutRaw !== undefined) {
@@ -2982,31 +3079,37 @@ function cmdSpawn(args) {
2982
3079
  const at = new Date().toISOString();
2983
3080
  const logDir = path.join(d.root, "logs");
2984
3081
  if (!dry) fs.mkdirSync(logDir, { recursive: true });
2985
- const spawnOpts = { harness, cmd, model, auto, maxTurns: maxTurnsNum, allowTools, cwd, root: d.root, prompt: null, keepEnv: args.includes("--keep-env"), allowEnv: parseAllowEnv(getFlag(args, "--allow-env")) };
3082
+ const spawnOpts = { harness, model, auto, maxTurns: maxTurnsNum, allowTools, cwd, root: d.root, prompt: null, keepEnv: args.includes("--keep-env"), allowEnv: parseAllowEnv(getFlag(args, "--allow-env")) };
2986
3083
  if (dry) {
2987
3084
  // Preview only: nothing touches the board (ids below are illustrative).
2988
- const previewBatch = recipients.length > 1 ? newId("batch") : undefined;
2989
- recipients.forEach((to, i) => {
2990
- const driver = harnesses[i % harnesses.length];
2991
- const itemMaxTurns = maxTurnsNum !== undefined ? maxTurnsNum : ((driver === "claude" || driver === "grok") ? 50 : undefined);
2992
- const itemSpawnOpts = { ...spawnOpts, harness: driver, maxTurns: itemMaxTurns, allowTools: driver === "claude" ? allowTools : undefined };
2993
- const previewPrompt = buildSpawnPrompt({ name: to, from, lead: leadTarget, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(to, leadTarget), workbench: wbFor(to) });
2994
- const t = buildSpawnTarget({ ...itemSpawnOpts, name: to, promptPath: `<logs>/${to}-<stamp>.prompt.md`, prompt: previewPrompt });
2995
- const wtNote = worktreePrefix !== undefined ? ` worktree ../${to}-<stamp> (branch ${worktreePrefix}/${to}-<stamp>)` : branchPrefix !== undefined ? ` branch ${branchPrefix}/${to}-<stamp>` : "";
2996
- console.log(`would spawn ${to} [${driver}] (${lifetime}) cwd ${cwd}${wtNote} cmd: ${formatSpawnCmd(t)} [board ${d.root}]`);
2997
- });
2998
- console.log(`--- prompt (first worker) ---\n${buildSpawnPrompt({ name: recipients[0], from, lead: leadTarget, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(recipients[0], leadTarget), workbench: wbFor(recipients[0]) })}`);
2999
- if (leadMode === "board") {
3085
+ const previewBatch = !revive && recipients.length > 1 ? newId("batch") : undefined;
3086
+ if (!revive) {
3087
+ recipients.forEach((to, i) => {
3088
+ const driver = harnesses[i % harnesses.length];
3089
+ const itemMaxTurns = maxTurnsNum !== undefined ? maxTurnsNum : ((driver === "claude" || driver === "grok") ? 50 : undefined);
3090
+ const itemSpawnOpts = { ...spawnOpts, harness: driver, maxTurns: itemMaxTurns, allowTools: driver === "claude" ? allowTools : undefined };
3091
+ const previewPrompt = buildSpawnPrompt({ name: to, from, lead: leadTarget, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(to, leadTarget), workbench: wbFor(to) });
3092
+ const t = buildSpawnTarget({ ...itemSpawnOpts, name: to, promptPath: `<logs>/${to}-<stamp>.prompt.md`, prompt: previewPrompt });
3093
+ const wtNote = worktreePrefix !== undefined ? ` worktree ../${to}-<stamp> (branch ${worktreePrefix}/${to}-<stamp>)` : branchPrefix !== undefined ? ` branch ${branchPrefix}/${to}-<stamp>` : "";
3094
+ console.log(`would spawn ${to} [${driver}] (${lifetime}) cwd ${cwd}${wtNote} cmd: ${formatSpawnCmd(t)} [board ${d.root}]`);
3095
+ });
3096
+ console.log(`--- prompt (first worker) ---\n${buildSpawnPrompt({ name: recipients[0], from, lead: leadTarget, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(recipients[0], leadTarget), workbench: wbFor(recipients[0]) })}`);
3097
+ } else {
3098
+ console.log(`lead-revive: would ONLY provision/reuse the auto-coordinator on the '${leadTarget}' lane (0 workers, no DMs delivered) [board ${d.root}]`);
3099
+ }
3100
+ if (leadTarget === "lead") {
3000
3101
  const existingLead = readAgent(d, "lead");
3001
- const standing = existingLead && typeof existingLead.spawnedPid === "number" && pidAlive(existingLead.spawnedPid);
3102
+ // Stale-pid guard (C2): preview says "fresh provision" when the pid
3103
+ // record is recycled (reboot + OS pid reuse).
3104
+ const standing = existingLead && typeof existingLead.spawnedPid === "number" && pidAlive(existingLead.spawnedPid) && !isPidStale(existingLead.spawnedPid, existingLead.spawnedAt);
3002
3105
  if (standing) {
3003
3106
  console.log(`--- lead ---\na live coordinator already runs on the 'lead' lane (pid ${existingLead.spawnedPid}) — reused, not duplicated [board ${d.root}]`);
3004
3107
  } else if (existingLead && existingLead.offboarded) {
3005
- console.log(`--- lead ---\nlane "lead" is offboarded: provision would be SKIPPED (re-onboard it, or pass --lead none) [board ${d.root}]`);
3108
+ console.log(`--- lead ---\nlane "lead" is offboarded: provision would be SKIPPED (re-onboard it) [board ${d.root}]`);
3006
3109
  } else {
3007
3110
  const coordPreview = buildCoordinatorPrompt({
3008
3111
  name: "lead", from, subject, body: body.trim(), batch: previewBatch,
3009
- workers: recipients.map((name, i) => ({ name, id: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", harness: harnesses[i % harnesses.length] })),
3112
+ workers: revive ? [] : recipients.map((name, i) => ({ name, id: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", harness: harnesses[i % harnesses.length] })),
3010
3113
  crew: crewFor(recipients[0], leadTarget), cwd, root, auto, workbench: wbFor(recipients[0]),
3011
3114
  });
3012
3115
  console.log(`--- lead ---\nwould spawn lead [${harnesses[0]}] (persistent — auto-provisioned lead, owner of this crew) cwd ${cwd} [board ${d.root}]`);
@@ -3017,11 +3120,21 @@ function cmdSpawn(args) {
3017
3120
  }
3018
3121
  // Direct (N-copy) path is forced here (every worker needs its own message
3019
3122
  // id to thread the reply against) — --broadcast is not accepted by spawn.
3020
- const res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, priority, senderType, fwd, rev, at, forceBroadcast: false, forceDirect: true, needsBy });
3021
- if (res.mode !== "direct") fail("spawn: internal error — expected direct delivery");
3022
- appendChainRecord(d, from, "spawn", { to: recipients.slice(), harness, harnesses, auto, cwd, isolate: isolateInfo.isolated || false, budgetTokens, budgetMinutes, deadlineAt });
3123
+ // Lead-revive (C9) skips all of it: zero workers, zero DMs — the mission
3124
+ // text feeds the coordinator prompt directly.
3125
+ let res = null;
3126
+ if (!revive) {
3127
+ res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, priority, senderType, fwd, rev, at, forceBroadcast: false, forceDirect: true, needsBy });
3128
+ if (res.mode !== "direct") fail("spawn: internal error — expected direct delivery");
3129
+ }
3130
+ appendChainRecord(d, from, "spawn", { to: recipients.slice(), harness, harnesses, auto, cwd, isolate: isolateInfo.isolated || false, budgetTokens, budgetMinutes, deadlineAt, ...(revive ? { revive: true } : {}) });
3131
+ if (!revive) {
3132
+ let chanMirrorNote = "";
3023
3133
  if (alsoChannel) {
3024
- mirrorToGroupChannels(d, { groups: groupNames, from, body: body.trim(), subject, replyTo, batch: res.batch || (res.items[0] && res.items[0].id), priority, rev, at });
3134
+ const m = mirrorToGroupChannels(d, { groups: groupNames, from, body: body.trim(), subject, replyTo, batch: res.batch || (res.items[0] && res.items[0].id), priority, rev, at });
3135
+ chanMirrorNote = (m.mirrored.length > 0 ? ` +channel ${m.mirrored.map((x) => x.channel).join(",")}` : "")
3136
+ + (m.skipped.length > 0 ? ` [channel mirror skipped, members-only: ${m.skipped.map((s) => s.group).join(",")}]` : "");
3137
+ process.stderr.write(`crewbus:${chanMirrorNote}\n`);
3025
3138
  }
3026
3139
  for (let i = 0; i < res.items.length; i++) {
3027
3140
  const { to, id } = res.items[i];
@@ -3052,19 +3165,21 @@ function cmdSpawn(args) {
3052
3165
  } catch (e) {
3053
3166
  console.log(`spawn FAILED ${to}: ${e.message} (brief ${id} still waits on the board) [board ${d.root}]`);
3054
3167
  }
3168
+ }
3055
3169
  }
3056
3170
  // Auto-provisioned lead: runs after the crew boots so the coordinator's
3057
3171
  // roster carries the real brief ids, and so a lead boot failure can never
3058
- // block worker boots.
3059
- if (leadMode === "board") {
3060
- const coordHarness = [ // first coding harness wins; generic is excluded above
3061
- ...harnesses.filter((h) => h !== "generic"),
3062
- ][0] || "opencode";
3172
+ // block worker boots. Lead-revive (C9): also runs here with an EMPTY
3173
+ // roster — the revive mission text becomes the coordinator's reminder of
3174
+ // what the crew was on about (worker threads/scope live on the board).
3175
+ {
3176
+ const coordHarness = harnesses[0] || "opencode";
3063
3177
  const provision = provisionAutoLead(d, {
3064
3178
  spawnOpts: { ...spawnOpts, harness: coordHarness, maxTurns: undefined, allowTools: undefined },
3065
3179
  from, subject, body: body.trim(), rev, logDir,
3066
- workers: res.items.map((it, i) => ({ name: it.to, id: it.id, harness: harnesses[i % harnesses.length] })),
3067
- batch: res.batch, crew: crewFor(recipients[0], leadTarget), workbench: wbFor(recipients[0]), auto,
3180
+ workers: res ? res.items.map((it, i) => ({ name: it.to, id: it.id, harness: harnesses[i % harnesses.length] })) : [],
3181
+ batch: res ? res.batch : undefined, crew: crewFor(recipients[0], leadTarget), workbench: wbFor(recipients[0]), auto,
3182
+ budgetTokens: leadBudgetTokens, budgetMinutes: leadBudgetMinutes,
3068
3183
  });
3069
3184
  if (provision.action === "minted" && provision.pid) {
3070
3185
  console.log(`auto-lead provisioned: minted lane '${provision.leadName}' (role lead — owns this crew), coordinator pid ${provision.pid} (persistent, ${coordHarness}) log ${provision.logPath} [board ${d.root}]`);
@@ -3091,9 +3206,6 @@ function printLaunchDryRun(v, args, from, root, asJson, cmdOpt) {
3091
3206
  const names = p.to ? String(p.to).split(",").map((s) => s.trim()).filter(Boolean)
3092
3207
  : Array.from({ length: p.count }, (_, i) => `${p.prefix || "w"}-${i + 1}`);
3093
3208
  const harnesses = Array.isArray(p.harnesses) && p.harnesses.length > 0 ? p.harnesses : [p.harness || "opencode"];
3094
- if (harnesses.includes("generic") && !cmdOpt) {
3095
- fail("launch --harness generic needs --cmd \"...\" (no command to preview)");
3096
- }
3097
3209
  const rev = gitRevForBoard(root);
3098
3210
  const rows = names.map((to, i) => {
3099
3211
  const driver = harnesses[i % harnesses.length];
@@ -3130,7 +3242,7 @@ async function askLoop(rl, q, parse, hint) {
3130
3242
  }
3131
3243
 
3132
3244
  // Fills raw.harness/raw.to/raw.count/raw.prefix/raw.body/raw.permission
3133
- // (+ cmdOpt for generic) by prompting. Assumes a TTY; pure parse logic
3245
+ // by prompting. Assumes a TTY; pure parse logic
3134
3246
  // lives in bin/lib/launch.js (unit-tested), this only loops.
3135
3247
  async function runLaunchWizard(rl, raw, cmdOpt) {
3136
3248
  const rows = detectHarnessBinaries();
@@ -3170,10 +3282,6 @@ async function runLaunchWizard(rl, raw, cmdOpt) {
3170
3282
  if (i === 2) fail("too many invalid answers — re-run non-interactively with explicit flags");
3171
3283
  }
3172
3284
  raw.permission = await askLoop(rl, "permission [1 supervised (default) | 2 autoEdits | 3 auto | 4 full]: ", (a) => parsePermissionChoice(a, "supervised"), "1-4 or name");
3173
- if (raw.harness === "generic" && !cmdOpt.value) {
3174
- const cmdRaw = await askLoop(rl, 'command to run [--cmd, required for generic]: ', (a) => String(a).trim() || null, "non-empty command");
3175
- cmdOpt.value = cmdRaw;
3176
- }
3177
3285
  return raw;
3178
3286
  }
3179
3287
 
@@ -3314,7 +3422,7 @@ function cmdHarnesses(args) {
3314
3422
  for (const r of rows) {
3315
3423
  const found = r.found ? "yes" : "no";
3316
3424
  const ver = (r.version || r.detail || "").slice(0, 26).padEnd(26);
3317
- console.log(`${r.driver.padEnd(12)} ${(r.binary || "(operator --cmd)").padEnd(14)} ${found.padEnd(6)} ${ver} ${(r.briefDelivery || "").padEnd(7)} ${r.resume ? "yes" : "NO (honest)"}`);
3425
+ console.log(`${r.driver.padEnd(12)} ${(r.binary || "-").padEnd(14)} ${found.padEnd(6)} ${ver} ${(r.briefDelivery || "").padEnd(7)} ${r.resume ? "yes" : "NO (honest)"}`);
3318
3426
  }
3319
3427
  console.log("missing binaries mean not installed — install + authenticate per docs/COMPATIBILITY.md");
3320
3428
  }
@@ -3373,8 +3481,7 @@ async function cmdSpawnKill(args) {
3373
3481
  // crewbus respawn --from <lead> --to <worker> [--body "..."] [--force] [--dry-run]
3374
3482
  // Preconditions: the worker was booted by spawn (worker-sessions record),
3375
3483
  // its process is dead (or --force kills it first), and a harness session id
3376
- // was captured — except generic, which has no session continuity and simply
3377
- // re-boots the catch-up brief fresh. The catch-up brief points at the
3484
+ // was captured. The catch-up brief points at the
3378
3485
  // original prompt file and threads the same reply id, so a resumed worker
3379
3486
  // continues instead of restarting. Lead/admin only (like spawn); --force
3380
3487
  // additionally checks spawn-kill scope (own crew).
@@ -3397,7 +3504,7 @@ async function cmdRespawn(args) {
3397
3504
  const dry = args.includes("--dry-run");
3398
3505
  // --fresh: when the harness session id was never captured (opencode kills
3399
3506
  // its buffered output before the log scan can read it), skip the resume
3400
- // requirement and boot the catch-up brief fresh — same as the generic path.
3507
+ // requirement and boot the catch-up brief fresh.
3401
3508
  const fresh = args.includes("--fresh");
3402
3509
  const extraBody = getFlag(args, "--body");
3403
3510
  if (extraBody !== undefined && String(extraBody).length > MAX_BODY_CHARS) fail(`message body too large (max ${MAX_BODY_CHARS} chars)`);
@@ -3414,7 +3521,7 @@ async function cmdRespawn(args) {
3414
3521
  const harness = prev.harness;
3415
3522
  if (!harness) fail(`no harness recorded for "${name}" (spawned before session capture — re-boot fresh with spawn --to ${name})`);
3416
3523
  const sessionId = prev.harnessSessionId;
3417
- if (!sessionId && harness !== "generic" && !fresh) fail(`no harness session id recorded for "${name}"${prev.idSource ? ` (source: ${prev.idSource})` : ""} — its conversation can't be resumed; re-brief with send --reply ${prev.briefId || "<brief-id>"}, respawn with --fresh to reboot it without the old conversation, or spawn a fresh worker`);
3524
+ if (!sessionId && !fresh) fail(`no harness session id recorded for "${name}"${prev.idSource ? ` (source: ${prev.idSource})` : ""} — its conversation can't be resumed; re-brief with send --reply ${prev.briefId || "<brief-id>"}, respawn with --fresh to reboot it without the old conversation, or spawn a fresh worker`);
3418
3525
  if ((prev.auto || false) && !args.includes("--auto")) fail(`worker "${name}" was spawned --auto (fully-unattended) — pass --auto to confirm the respawn carries the same danger (see docs/ISOLATION.md)`);
3419
3526
  if (args.includes("--auto")) requireAutoConfirm(args);
3420
3527
  if (!prev.promptPath) fail(`no original prompt on record for "${name}" (spawned before prompt capture — re-boot fresh with spawn --to ${name})`);
@@ -3426,19 +3533,16 @@ async function cmdRespawn(args) {
3426
3533
  const briefId = prev.briefId || rec.briefId;
3427
3534
  if (!briefId) fail(`no brief id on record for "${name}" — re-boot fresh with spawn --to ${name}`);
3428
3535
  const cwd = getFlag(args, "--cwd") ? path.resolve(getFlag(args, "--cwd")) : (prev.cwd || path.dirname(root));
3429
- let cmd = prev.cmd;
3430
- if (harness === "generic") {
3431
- const cmdOverride = getFlag(args, "--cmd");
3432
- if (cmdOverride !== undefined) cmd = cmdOverride;
3433
- if (!cmd) fail(`generic respawn needs the original --cmd (not recorded — re-boot fresh with spawn --harness generic --cmd "..." --to ${name})`);
3434
- }
3435
- const spawnOpts = { harness, cmd, model: prev.model, maxTurns: prev.maxTurns, auto: !!prev.auto, allowTools: prev.allowTools, cwd, root: d.root, prompt: null, keepEnv: args.includes("--keep-env"), allowEnv: parseAllowEnv(getFlag(args, "--allow-env")) };
3536
+ const spawnOpts = { harness, model: prev.model, maxTurns: prev.maxTurns, auto: !!prev.auto, allowTools: prev.allowTools, cwd, root: d.root, prompt: null, keepEnv: args.includes("--keep-env"), allowEnv: parseAllowEnv(getFlag(args, "--allow-env")) };
3436
3537
  const attempt = ((prev.respawnCount) || 0) + 1;
3437
- const alive = typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid);
3538
+ // Recycled-pid records read dead for respawn gating too (C2): a live pid
3539
+ // that postdates the spawn belongs to an unrelated process.
3540
+ const alive = typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt);
3541
+ const effectiveSessionId = fresh ? undefined : (sessionId || undefined);
3438
3542
  if (dry) {
3439
- const catchup = buildRespawnBrief({ name, attempt, origPromptPath: prev.promptPath, briefId, harnessSessionId: sessionId || null, harness, lead: from, extraBody });
3440
- const t = buildRespawnTarget({ ...spawnOpts, name, promptPath: `<logs>/${name}-<stamp>.respawn.md`, prompt: catchup, sessionId: sessionId || undefined });
3441
- console.log(`would respawn ${name} [${harness}] attempt ${attempt}${sessionId ? ` session ${sessionId}` : " (fresh boot, no session continuity)"} cmd: ${formatSpawnCmd(t)} [board ${d.root}]`);
3543
+ const catchup = buildRespawnBrief({ name, attempt, origPromptPath: prev.promptPath, briefId, harnessSessionId: effectiveSessionId || null, harness, lead: from, extraBody });
3544
+ const t = buildRespawnTarget({ ...spawnOpts, name, promptPath: `<logs>/${name}-<stamp>.respawn.md`, prompt: catchup, sessionId: effectiveSessionId });
3545
+ console.log(`would respawn ${name} [${harness}] attempt ${attempt}${effectiveSessionId ? ` session ${effectiveSessionId}` : " (fresh boot, no session continuity)"} cmd: ${formatSpawnCmd(t)} [board ${d.root}]`);
3442
3546
  console.log(`--- catch-up brief ---\n${catchup}`);
3443
3547
  return;
3444
3548
  }
@@ -3451,9 +3555,9 @@ async function cmdRespawn(args) {
3451
3555
  }
3452
3556
  const logDir = path.join(d.root, "logs");
3453
3557
  fs.mkdirSync(logDir, { recursive: true });
3454
- const r = bootRespawnedWorker(d, spawnOpts, { to: name, briefId, from, sessionId: sessionId || undefined, attempt, origPromptPath: prev.promptPath, extraBody, logDir });
3455
- appendChainRecord(d, from, "respawn", { to: name, harness, attempt, sessionId: sessionId || null });
3456
- console.log(`respawned ${name} [${harness}] attempt ${attempt} pid ${r.pid}${sessionId ? ` session ${sessionId}` : " (fresh boot)"} [board ${d.root}]`);
3558
+ const r = bootRespawnedWorker(d, spawnOpts, { to: name, briefId, from, sessionId: effectiveSessionId, attempt, origPromptPath: prev.promptPath, extraBody, logDir });
3559
+ appendChainRecord(d, from, "respawn", { to: name, harness, attempt, sessionId: effectiveSessionId || null });
3560
+ console.log(`respawned ${name} [${harness}] attempt ${attempt} pid ${r.pid}${effectiveSessionId ? ` session ${effectiveSessionId}` : " (fresh boot)"} [board ${d.root}]`);
3457
3561
  }
3458
3562
 
3459
3563
  // Global stop: kill every spawned worker truly (whole process tree).
@@ -3730,7 +3834,69 @@ function cmdLesson(args) {
3730
3834
  fail(`unknown lesson subcommand "${sub}" (want post|list)`);
3731
3835
  }
3732
3836
 
3837
+ // inbox archive (C6 lead-lane hygiene): move ACKED direct DMs (and checkpoints,
3838
+ // which are progress-not-work) out of dm/<agent>/ into dm-archive/<agent>/.
3839
+ // Self-scoped bookkeeping (authenticated owner, ack-level authorization):
3840
+ // unacked work NEVER archives implicitly — a scope is mandatory (--all, or
3841
+ // --before <dur> for rows older than the window). Broadcasts are NOT moved
3842
+ // (they are single board-level files shared by all recipients) — pruning
3843
+ // those is an admin `prune` concern. Id collisions (the archive already has
3844
+ // the file) keep the original in place rather than double-mutating.
3845
+ function cmdInboxArchive(args) {
3846
+ const root = boardDir(args);
3847
+ refuseDriveRootBoard(root, args);
3848
+ const d = requireBoard(root);
3849
+ const agent = resolveAgent(args, "reader");
3850
+ checkToken(d, agent, resolveToken(args));
3851
+ authorize(d, agent, "ack"); // own inbox only, never reads others'
3852
+ const wantAll = args.includes("--all");
3853
+ const before = getFlag(args, "--before");
3854
+ if (!wantAll && before === undefined) {
3855
+ fail("inbox archive needs a scope: --all (move everything acked/checkpointed), or --before <dur> (only rows older than the window, e.g. --before 7d); unacked work never archives implicitly");
3856
+ }
3857
+ let cutoff = 0;
3858
+ if (before !== undefined) {
3859
+ const ms = parseDuration(before);
3860
+ if (!(ms > 0)) fail("--before must be a positive duration (e.g. 7d, 30m)");
3861
+ cutoff = Date.now() - ms;
3862
+ }
3863
+ const acked = ackedIds(d, agent);
3864
+ const src = path.join(d.dm, agent);
3865
+ const dst = path.join(path.dirname(d.dm), "dm-archive", agent);
3866
+ let files = [];
3867
+ try { files = fs.readdirSync(src).filter((f) => f.endsWith(".json")); } catch {}
3868
+ let moved = 0;
3869
+ let kept = 0;
3870
+ for (const f of files) {
3871
+ const srcP = path.join(src, f);
3872
+ let m = null;
3873
+ try { m = readJson(srcP); } catch { kept++; continue; }
3874
+ if (!m || !m.id) { kept++; continue; }
3875
+ const isAcked = acked.has(m.id);
3876
+ const isCkpt = m.checkpoint === true;
3877
+ if (!isAcked && !isCkpt) { kept++; continue; }
3878
+ if (!wantAll) {
3879
+ const t = Date.parse(m.at || "");
3880
+ if (Number.isNaN(t) || t >= cutoff) { kept++; continue; }
3881
+ }
3882
+ fs.mkdirSync(dst, { recursive: true });
3883
+ const dstP = path.join(dst, f);
3884
+ if (fs.existsSync(dstP)) { kept++; continue; }
3885
+ fs.renameSync(srcP, dstP);
3886
+ moved++;
3887
+ }
3888
+ if (args.includes("--json")) {
3889
+ console.log(JSON.stringify({ agent, moved, kept, archive: dst }));
3890
+ return;
3891
+ }
3892
+ console.log(`archived ${moved} message(s) for ${agent} -> dm-archive/${agent}/ (kept ${kept}${wantAll ? "" : ", --before window"}) [board ${d.root}]`);
3893
+ if (kept === moved && moved === 0) console.log(`nothing scoped to archive — unacked work stays put (ack it or pass --all)`);
3894
+ }
3895
+
3733
3896
  function cmdInbox(args) {
3897
+ if (args[0] === "archive") return cmdInboxArchive(args.slice(1));
3898
+ const archivedView = args.includes("--archived");
3899
+ args = archivedView ? args.filter((a) => a !== "--archived") : args;
3734
3900
  const root = boardDir(args);
3735
3901
  refuseDriveRootBoard(root, args);
3736
3902
  const d = requireBoard(root);
@@ -3774,7 +3940,16 @@ function cmdInbox(args) {
3774
3940
  checkToken(d, agent, resolveToken(args)); // your inbox is addressed to you — prove it
3775
3941
  authorize(d, agent, "inbox"); // reads allow all roles (auditor read-ok)
3776
3942
  heartbeat(d, agent, 0); // reading your mail proves you're alive
3777
- items = readVisible(d, agent);
3943
+ // --archived (C6): opt-in view of dm-archive/<agent>/ (moved by
3944
+ // `crewbus inbox archive`). Direct DMs only; ack state shown from the
3945
+ // live ack dir. --unacked on an archive is naturally empty.
3946
+ if (archivedView) {
3947
+ const dAr = { ...d, dm: path.join(path.dirname(d.dm), "dm-archive") };
3948
+ items = readDMs(dAr, agent);
3949
+ items.sort((a, b) => String(a.at).localeCompare(String(b.at)) || String(a.id).localeCompare(String(b.id)));
3950
+ } else {
3951
+ items = readVisible(d, agent);
3952
+ }
3778
3953
  acked = ackedIds(d, agent);
3779
3954
  if (json) {
3780
3955
  items = items.map((m) => (acked.has(m.id) ? { ...m, acked: true } : m));
@@ -4582,7 +4757,7 @@ function cmdDoctor(args) {
4582
4757
  if (meta && Array.isArray(meta.harnesses) && meta.harnesses.length > 0) ids = meta.harnesses.filter((h) => HARNESSES.includes(h));
4583
4758
  else {
4584
4759
  ids = detectHarnesses(cwd);
4585
- if (ids.length === 0) ids = ["generic"];
4760
+ if (ids.length === 0) ids = ["opencode"];
4586
4761
  }
4587
4762
  }
4588
4763
  // Dead-man scan (read-only, board-local only — no cwd needed): the
@@ -4760,9 +4935,6 @@ function cmdDoctor(args) {
4760
4935
  else no("cursor MCP .cursor/mcp.json", "run: crewbus init --harness cursor (then approve/enable it in Cursor settings)");
4761
4936
  break;
4762
4937
  }
4763
- default:
4764
- info(`generic harness: CLI pull only (inbox/listen), nothing to validate`);
4765
- break;
4766
4938
  }
4767
4939
  }
4768
4940
  // Reconcile hint (read-only): workers whose pids look recycled since a
@@ -4776,16 +4948,6 @@ function cmdDoctor(args) {
4776
4948
  } catch {}
4777
4949
  if (!process.env.CREWBUS_AGENT) info("CREWBUS_AGENT is unset — hooks need it to know who you are");
4778
4950
  if (!process.env.CREWBUS_TOKEN) info("CREWBUS_TOKEN is unset — sends/reads as a claimed name need it");
4779
- try {
4780
- const legacy = fs.readdirSync(path.join(root, "agents")).filter((f) => f.endsWith(".json")).map((f) => {
4781
- try {
4782
- return readJson(path.join(root, "agents", f));
4783
- } catch {
4784
- return null;
4785
- }
4786
- }).filter((x) => x && x.name && !x.token && !x.tokenHash);
4787
- if (legacy.length > 0) info(`${legacy.length} agent(s) predate tokens (${legacy.slice(0, 5).map((x) => x.name).join(",")}${legacy.length > 5 ? "…" : ""}) — re-register to claim`);
4788
- } catch {}
4789
4951
  console.log(bad === 0 ? "doctor: healthy" : `doctor: ${bad} problem(s)`);
4790
4952
  if (bad > 0) process.exitCode = 1;
4791
4953
  }
@@ -6364,7 +6526,7 @@ async function cmdServe(args) {
6364
6526
  try {
6365
6527
  for (const e of listJson(path.join(d.root, "agents"))) {
6366
6528
  if (!e || !e.data) continue;
6367
- if (typeof e.data.spawnedPid === "number" && pidAlive(e.data.spawnedPid)) workers++;
6529
+ if (typeof e.data.spawnedPid === "number" && pidAlive(e.data.spawnedPid) && !isPidStale(e.data.spawnedPid, e.data.spawnedAt)) workers++;
6368
6530
  }
6369
6531
  } catch {}
6370
6532
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "x-relay-role": role });
@@ -6584,7 +6746,7 @@ const USAGE = `crewbus — DM-only minimal bus for AI agent coordination (v2)
6584
6746
 
6585
6747
  Setup:
6586
6748
  crewbus init [--global] [--board <path>] [--force] [--no-opencode] [--portable]
6587
- [--harness opencode,claude,codex,antigravity,grok,cursor,generic]
6749
+ [--harness opencode,claude,codex,antigravity,grok,cursor]
6588
6750
  create board in ./.crewbus, write AGENTS.md block, install harness
6589
6751
  crewbus install-cli
6590
6752
  install standalone CLI wrapper to user PATH (~/.crewbus/bin)
@@ -6603,6 +6765,12 @@ Setup:
6603
6765
  Identity (first claim wins, token after that):
6604
6766
  crewbus register --from <you> [--session <opencode-session-id>] [--token <t>] [--expires-in <dur>] [--service]
6605
6767
  crewbus register --service <name> | register --offboard <name> --from <admin>
6768
+ crewbus recover [--session <id>] [--cwd <dir>]
6769
+ (compaction/restart amnesia triage: lists candidate identities with
6770
+ evidence (register session binding, token-file↔tokenHash cross-check,
6771
+ cwd history) and prints the exact resume commands. Read-only, never
6772
+ mints. Reserved sentinel names ("unknown", "me", "you") refuse to
6773
+ register/send — they exist only for tools that forget who they are.)
6606
6774
  crewbus agents [--json] [--active] [--window <sec>] [--include-services]
6607
6775
  (--active lists only agents seen within the window, default 300s;
6608
6776
  every inbox/listen/send heartbeats your presence.
@@ -6683,7 +6851,12 @@ Messaging (primitive — just a tool call, whenever you want):
6683
6851
  differently. Later spawn briefs whose groups (or --scope-less/global)
6684
6852
  match auto-inject the latest lessons, so a lesson learned once is
6685
6853
  paid forward. post needs your token; list is open.)
6686
- crewbus inbox --from <you> [--limit 20] [--after <msg-id>] [--all] [--unacked] [--overdue] [--older-than 10m] [--grep <pattern>] [--priority high|normal] [--max-chars <n>] [--digest] [--verify] [--json]
6854
+ crewbus inbox archive --from <you> (--all | --before <dur>) [--json]
6855
+ (inbox hygiene: move acked direct DMs + checkpoints from dm/<you>/ into
6856
+ dm-archive/<you>/ — unacked work NEVER archives implicitly (a scope is
6857
+ mandatory). Broadcasts are board-level files and stay (prune territory:
6858
+ only admin). Read them back with 'crewbus inbox --from <you> --archived'.)
6859
+ crewbus inbox --from <you> [--limit 20] [--after <msg-id>] [--all] [--unacked] [--overdue] [--older-than 10m] [--grep <pattern>] [--priority high|normal] [--max-chars <n>] [--digest] [--verify] [--json] [--archived]
6687
6860
  (--older-than keeps only messages older than the window: inbox --unacked
6688
6861
  --older-than 10m lists briefs nobody picked up (retry via redeliver or
6689
6862
  re-send). --overdue lists still-open briefs whose --needs-by deadline
@@ -6708,14 +6881,15 @@ Messaging (primitive — just a tool call, whenever you want):
6708
6881
  (recover mail a dead watcher consumed: clears delivered markers and
6709
6882
  rewinds the cursor so the next poll/push treats it as fresh;
6710
6883
  use after re-registering with the live session)
6711
- crewbus spawn --from <you> (--to <workers> | --count <n> [--prefix <p>]) --body "..." [--subject "..."] [--priority high|normal] [--needs-by 30m] [--harness opencode|claude|codex|grok|antigravity|cursor|generic] [--cmd "..."] [--cwd <dir>] [--worktree <branch-prefix> | --branch <branch-prefix>] [--oneshot | --persistent] [--model <m>] [--max-turns <n>] [--allow-tools "..."] [--max-spawn <n>] [--auto --i-understand-danger] [--isolate] [--budget-tokens N] [--budget-minutes M] [--timeout 10m] [--keep-env] [--allow-env ANTHROPIC_,GITHUB_] [--workdir-root <dir>] [--sender-type human|lead|peer] [--dry-run]
6884
+ crewbus spawn --from <you> (--to <workers> | --count <n> [--prefix <p>]) --body "..." [--subject "..."] [--priority high|normal] [--needs-by 30m] [--harness opencode|claude|codex|grok|antigravity|cursor] [--cmd "..."] [--cwd <dir>] [--worktree <branch-prefix> | --branch <branch-prefix>] [--oneshot | --persistent] [--model <m>] [--max-turns <n>] [--allow-tools "..."] [--max-spawn <n>] [--auto --i-understand-danger] [--isolate] [--budget-tokens N] [--budget-minutes M] [--lead-budget-tokens N] [--lead-budget-minutes M] [--timeout 10m] [--keep-env] [--allow-env ANTHROPIC_,GITHUB_] [--workdir-root <dir>] [--sender-type human|lead|peer] [--dry-run]
6885
+ (--budget-* cap the WORKERS; --lead-budget-* cap the auto-provisioned coordinator lane — same semantics, e.g. a 400k-token lead that posts its aggregate and exits. Unset = persistent boss-supervised coordinator (default). A standing coordinator keeps its boot-time budget; the flags cannot change it mid-flight.)
6712
6886
  (workers boot with cloud/AI credential vars scrubbed from their environment by default (lead's keys never leak into briefs); pass --keep-env to inherit everything or --allow-env <prefix,...> to keep listed names. CREWBUS_TOKEN is never inherited — workers claim their own identity.)
6713
6887
  (brief N workers AND boot them detached: the DM lands first so the brief
6714
6888
  waits even if a launch fails. opencode: \`run\` + brief via --file;
6715
6889
  claude: \`-p\` + brief on stdin; codex: \`exec\` pointing at the brief
6716
6890
  file; grok: headless via --prompt-file; antigravity: \`--print\` with the
6717
6891
  brief inline; cursor: headless via \`-p --force --trust\` pointing at the
6718
- brief file; generic: --cmd with CREWBUS_DIR + CREWBUS_AGENT set.
6892
+ brief file.
6719
6893
  Briefs auto-inject the latest scoped lessons + newest board artifacts
6720
6894
  (the Workbench block) so prior output compounds; --needs-by stamps a
6721
6895
  handoff deadline on the brief DMs.
@@ -6728,7 +6902,9 @@ Messaging (primitive — just a tool call, whenever you want):
6728
6902
  receive mail — their replies wait on the board for pull (inbox/gather).
6729
6903
  --auto maps to each harness's
6730
6904
  unattended mode (dangerous); --dry-run prints the exact command without
6731
- touching the board.)
6905
+ touching the board. --count 0 is the LEAD REVIVE path: boots nothing
6906
+ except the auto-coordinator lane (no workers, no DMs) — for bringing the
6907
+ coordinator back after a crash/reboot without re-briefing the crew.)
6732
6908
  crewbus spawn-status --to <worker> [--lines 10] [--json] | --all
6733
6909
  (is it running? did the reply land? pid liveness via kill-0 plus process
6734
6910
  start-time validation — reboot-recycled pids read dead (stale pid) instead
@@ -6740,7 +6916,7 @@ Messaging (primitive — just a tool call, whenever you want):
6740
6916
  Terminates by recorded pid, confirms death, reports. Needs your token.)
6741
6917
  crewbus respawn --from <you> --to <worker> [--body "..."] [--force] [--fresh] [--cwd <dir>] [--cmd "..."] [--keep-env] [--allow-env ...] [--dry-run]
6742
6918
  (reboot one DEAD worker in its SAME harness conversation: needs the
6743
- captured session id (spawn-status shows it; generic re-boots fresh).
6919
+ captured session id (spawn-status shows it; respawn --fresh re-boots without prior context).
6744
6920
  --fresh skips the resume requirement when the id can't be captured
6745
6921
  (e.g. an opencode worker died before its log revealed anything) and
6746
6922
  re-boots the catch-up brief as a fresh session.
@@ -6753,7 +6929,6 @@ Messaging (primitive — just a tool call, whenever you want):
6753
6929
  crewbus token rotate --from <you> [--expires-in <dur>]
6754
6930
  (issue a replacement token; the old one dies immediately. New token
6755
6931
  printed once — agent files store only a salted hash, never plaintext.
6756
- Legacy plaintext 'token' files migrate on next successful auth.
6757
6932
  --expires-in 30/90s/15m/24h/7d sets expiry; token status shows it.)
6758
6933
  crewbus token status --from <you> [--json]
6759
6934
  (expiry/rotation state, no secrets.)
@@ -6786,7 +6961,7 @@ Messaging (primitive — just a tool call, whenever you want):
6786
6961
  Surviving markers are kept, so nothing replays. Pruned ids leave
6787
6962
  tombstones/ entries replicated via sync so deletes don't return.
6788
6963
  Refused while a legal hold is active — see hold.)
6789
- crewbus pool --from <you> --count N --pool-size S --body "..." [--harness generic --cmd "..."] [--prefix p] [--queue a,b] [--json]
6964
+ crewbus pool --from <you> --count N --pool-size S --body "..." [--harness opencode] [--prefix p] [--queue a,b] [--json]
6790
6965
  (lean async runner: brief N workers but boot at most S concurrently,
6791
6966
  watch exits and auto-replace until N total. Queue backpressure refuses
6792
6967
  when pending > 4*poolSize. State in pool-state/<id>.json, token-checked;
@@ -6857,12 +7032,10 @@ Messaging (primitive — just a tool call, whenever you want):
6857
7032
  --mtls-ca additionally requires verified client certs on /sync/* (mTLS,
6858
7033
  opt-in; tunnel alternative -- plain http behind your terminator -- stays
6859
7034
  fine). /api/spawn + /api/kill are OPT-IN (default OFF
6860
- → 403) via --allow-remote-spawn. Remote generic --cmd is refused unless
6861
- it matches --allow-cmd (default harness-only); remote cwd must sit under
6862
- --workdir-root when set. Remote spawn/kill append to logs/audit.jsonl.
7035
+ → 403) via --allow-remote-spawn. Remote cwd must sit under --workdir-root when set. Remote spawn/kill append to logs/audit.jsonl.
6863
7036
  Control plane (M1): POST /api/launch validates the launch plan then
6864
7037
  boots via the same core (same OPT-IN + secret gates; --dry-run previews
6865
- without booting); GET /api/harnesses lists the 7 drivers with binary
7038
+ without booting); GET /api/harnesses lists the 6 drivers with binary
6866
7039
  presence; GET /api/routes + /healthz publish --advertise-routes hints;
6867
7040
  --pair-qrcode prints a one-time crewbus://pair URL at boot (needs
6868
7041
  --from <admin>; same mint + audit as relay pair).
@@ -7347,9 +7520,7 @@ async function cmdPool(args) {
7347
7520
  if (queue.length > 4 * poolSize) fail(`pool queue full (${queue.length} > 4*poolSize ${4 * poolSize}) — raise --pool-size or shrink --count`);
7348
7521
  let harness = String(getFlag(args, "--harness") || "opencode").toLowerCase();
7349
7522
  if (harness === "agy") harness = "antigravity";
7350
- if (!["opencode", "claude", "codex", "grok", "antigravity", "cursor", "generic"].includes(harness)) fail(`unknown --harness "${harness}"`);
7351
- const cmd = getFlag(args, "--cmd");
7352
- if (harness === "generic" && !cmd) fail('generic harness needs --cmd "..."');
7523
+ if (!HARNESSES.includes(harness)) fail(`unknown --harness "${harness}"`);
7353
7524
  const maxTurnsFlag = getFlag(args, "--max-turns");
7354
7525
  if (maxTurnsFlag !== undefined && !(Number(maxTurnsFlag) > 0)) fail("--max-turns must be a positive number");
7355
7526
  if (maxTurnsFlag !== undefined && harness !== "claude" && harness !== "grok") fail(`--max-turns only applies to claude/grok (got --harness ${harness})`);
@@ -7366,11 +7537,11 @@ async function cmdPool(args) {
7366
7537
  fs.mkdirSync(logDir, { recursive: true });
7367
7538
  const poolId = newId("pool");
7368
7539
  const statePath = path.join(d.root, "pool-state", `${poolId}.json`);
7369
- const spawnOpts = { harness, cmd, model, auto, maxTurns: maxTurnsNum, allowTools: getFlag(args, "--allow-tools"), cwd, root: d.root, prompt: null, keepEnv: args.includes("--keep-env"), allowEnv: parseAllowEnv(getFlag(args, "--allow-env")) };
7540
+ const spawnOpts = { harness, model, auto, maxTurns: maxTurnsNum, allowTools: getFlag(args, "--allow-tools"), cwd, root: d.root, prompt: null, keepEnv: args.includes("--keep-env"), allowEnv: parseAllowEnv(getFlag(args, "--allow-env")) };
7370
7541
  // Resumable state: queue/cursor/idByName let a later `pool resume` pick up
7371
7542
  // supervision; spawnOpts/body/subject/rev reproduce relaunches exactly.
7372
7543
  // `pending` stays a frozen full-queue snapshot for old readers.
7373
- const state = { id: poolId, from, total: queue.length, poolSize, harness, createdAt: at, launched: 0, done: 0, active: {}, pending: queue.slice(), results: [], body: body.trim(), subject, queue: queue.slice(), cursor: 0, idByName: {}, spawnOpts: { harness, cmd, model, auto, maxTurns: maxTurnsNum, allowTools: getFlag(args, "--allow-tools"), cwd }, rev };
7544
+ const state = { id: poolId, from, total: queue.length, poolSize, harness, createdAt: at, launched: 0, done: 0, active: {}, pending: queue.slice(), results: [], body: body.trim(), subject, queue: queue.slice(), cursor: 0, idByName: {}, spawnOpts: { harness, model, auto, maxTurns: maxTurnsNum, allowTools: getFlag(args, "--allow-tools"), cwd }, rev };
7374
7545
  const saveState = () => {
7375
7546
  try {
7376
7547
  const { v, hlc } = stampSyncDoc(null);
@@ -7401,8 +7572,10 @@ async function cmdPool(args) {
7401
7572
  }
7402
7573
  };
7403
7574
  const initial = Math.min(poolSize, queue.length);
7404
- for (; state.cursor < initial; state.cursor++) launchOne(queue[state.cursor]);
7405
- saveState(); // persist the post-launch cursor (launchOne saves pre-increment)
7575
+ while (state.cursor < initial) {
7576
+ const next = queue[state.cursor++];
7577
+ launchOne(next);
7578
+ }
7406
7579
  const deadline = Date.now() + POOL_SUPERVISE_MS;
7407
7580
  while (state.done < queue.length && Date.now() < deadline) {
7408
7581
  await new Promise((r) => setTimeout(r, 500));
@@ -7747,6 +7920,7 @@ async function main() {
7747
7920
  case "install-cli": return cmdInstallCli();
7748
7921
  case "update": return cmdUpdate(rest);
7749
7922
  case "register": return cmdRegister(rest);
7923
+ case "recover": return cmdRecover(rest);
7750
7924
  case "acl": return cmdAcl(rest);
7751
7925
  case "agents": return cmdAgents(rest);
7752
7926
  case "send": return cmdSend(rest);