crewbus 10.0.10 → 10.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/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";
@@ -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)
@@ -1106,23 +1106,85 @@ export const DmWatchPlugin = async ({ client, directory }) => {
1106
1106
  }, POLL_MS);
1107
1107
  poll().catch(() => {});
1108
1108
 
1109
+ // C1 lite recovery (self-contained: no bin/lib imports — the plugin ships
1110
+ // standalone). Same scoring spirit as \`crewbus recover\`, minus the
1111
+ // token-hash cross-check: session binding +4, token file +1, cwd match +1.
1112
+ // Returns [{ name, role, score, proven, why }] best-first.
1113
+ function recoverCandidatesLite(sessionID) {
1114
+ const cands = [];
1115
+ try {
1116
+ const agentsDir = path.join(root, "agents");
1117
+ const logsDir = path.join(root, "logs");
1118
+ const tokenNames = new Set();
1119
+ try {
1120
+ for (const f of fs.readdirSync(logsDir)) if (f.endsWith(".token")) tokenNames.add(f.slice(0, -6).toLowerCase());
1121
+ } catch {}
1122
+ const cwd = String(process.cwd() || "").replace(/\\\\/g, "/").toLowerCase();
1123
+ for (const f of fs.readdirSync(agentsDir)) {
1124
+ if (!f.endsWith(".json")) continue;
1125
+ const doc = readJsonSafe(path.join(agentsDir, f));
1126
+ if (!doc || !doc.name || doc.offboarded) continue;
1127
+ let score = 0;
1128
+ const why = [];
1129
+ if (sessionID && doc.sessionId && String(doc.sessionId) === String(sessionID)) {
1130
+ score += 4;
1131
+ why.push("session id matches register binding");
1132
+ }
1133
+ if (tokenNames.has(String(doc.name).toLowerCase())) {
1134
+ score += 1;
1135
+ why.push("token file exists for this name");
1136
+ }
1137
+ if (doc.lastDir && cwd && String(doc.lastDir).replace(/\\\\/g, "/").toLowerCase() === cwd) {
1138
+ score += 1;
1139
+ why.push("worked from this directory");
1140
+ }
1141
+ if (score <= 0) continue;
1142
+ cands.push({ name: doc.name, role: doc.role || "peer", score, proven: false, why: why.join("; ") });
1143
+ }
1144
+ } catch {}
1145
+ cands.sort((a, b) => b.score - a.score || String(a.name).localeCompare(String(b.name)));
1146
+ return cands;
1147
+ }
1148
+
1109
1149
  return {
1110
1150
  // Compaction rehydration: opencode summarizes this session, so the agent
1111
1151
  // wakes up forgetting its name, board, and token. Push the same identity
1112
- // card \`crewbus-hook compact\` prints into the summary prompt.
1152
+ // card \`crewbus-hook compact\` prints into the summary prompt. When the
1153
+ // session↔agent map misses, try board-side recovery BEFORE calling the
1154
+ // agent "unknown" (post-compaction rehydration: C1):
1155
+ // 1. register --session <id> binding stored on the agent doc
1156
+ // 2. CREWBUS_AGENT env (set when the session boots via launch)
1157
+ // 3. token-file + cwd evidence (agents roster ∩ logs/*.token)
1158
+ // A resolved candidate drives the card; an unresolved one prints the
1159
+ // crewbus recover path instead — never suggest re-registering a thrown
1160
+ // "unknown" (those sentinel names refuse to mint, and for good reason).
1113
1161
  "experimental.session.compacting": async (input, output) => {
1114
1162
  try {
1115
1163
  if (!output || !Array.isArray(output.context)) return;
1116
1164
  refreshAgentMap();
1117
1165
  let agent = null;
1118
1166
  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.\`);
1167
+ let proven = false;
1168
+ if (!agent) agent = (process.env.CREWBUS_AGENT || "").trim() || null;
1169
+ if (!agent) {
1170
+ const cands = recoverCandidatesLite(input && input.sessionID);
1171
+ if (cands[0] && cands[0].score >= 2) {
1172
+ agent = cands[0].name;
1173
+ proven = cands[0].proven || cands[0].score >= 3;
1174
+ }
1175
+ }
1176
+ if (agent) {
1177
+ output.context.push(\`crewbus: context refreshed after compaction. You are '\${agent}' on board \${root}\${proven ? " (identity cross-checked)" : ""}.\`);
1178
+ 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.\`);
1179
+ output.context.push(\`Then: crewbus inbox --from \${agent} --unacked --digest (escalate to full reads on hits).\`);
1180
+ const doc = readJsonSafe(path.join(root, "agents", agent + ".json"));
1181
+ const ws = doc && doc.briefId ? readJsonSafe(path.join(root, "worker-sessions", agent + ".json")) : null;
1182
+ if (ws && (ws.promptPath || ws.origPromptPath)) output.context.push(\`Your brief: re-read \${ws.promptPath || ws.origPromptPath} from worker-sessions if present.\`);
1183
+ } else {
1184
+ output.context.push(\`crewbus: context refreshed after compaction, but THIS session's agent could not be identified on board \${root}.\`);
1185
+ 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.\`);
1186
+ output.context.push(\`NEVER re-register as 'unknown'/'me'/'you' — those sentinel names are reserved and refuse to mint; recover your real identity instead.\`);
1187
+ }
1126
1188
  } catch {}
1127
1189
  },
1128
1190
  dispose: async () => {
@@ -1906,6 +1968,49 @@ function cmdInit(args) {
1906
1968
  // Durations for prune --older-than: 30, 90s, 15m, 24h, 7d, 2w (bare = seconds).
1907
1969
 
1908
1970
 
1971
+ // recover: read-only identity triage after compaction/restart amnesia.
1972
+ // Never writes, never mints — prints candidate identities with evidence and
1973
+ // the exact commands to resume. Read-side: refuses to plant a board.
1974
+ function cmdRecover(args) {
1975
+ const root = boardDir(args);
1976
+ refuseDriveRootBoard(root, args);
1977
+ const d = requireBoard(root);
1978
+ const opts = {
1979
+ sessionID: getFlag(args, "--session"),
1980
+ cwd: getFlag(args, "--cwd") || process.cwd(),
1981
+ hashToken,
1982
+ loadTokenFile,
1983
+ };
1984
+ const cands = recoverIdentity(d, opts);
1985
+ if (cands.length === 0) {
1986
+ 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`);
1987
+ return;
1988
+ }
1989
+ const top = cands[0];
1990
+ for (const c of cands) {
1991
+ const tag = c.proven ? "proven" : "hint";
1992
+ console.log(`${tag.padEnd(6)} ${c.name} (role ${c.role}, score ${c.score}) — ${c.why}`);
1993
+ }
1994
+ const tokPath = path.join(d.root, "logs", `${top.name}.token`);
1995
+ console.log(`\nresume as '${top.name}':`);
1996
+ if (!top.proven) console.log(` 0. cross-check yourself first (the token file may be stale): open ${tokPath} and verify it is YOUR token`);
1997
+ console.log(resumeScriptLines(top, d));
1998
+ console.log(`then: crewbus inbox --from ${top.name} --unacked --digest (escalate to full reads on hits)`);
1999
+ }
2000
+
2001
+ // One shared resume script for the top candidate (recover output only).
2002
+ function resumeScriptLines(top, d) {
2003
+ const tokPath = path.join(d.root, "logs", `${top.name}.token`);
2004
+ const lines = [];
2005
+ lines.push(` 1. set CREWBUS_AGENT=${top.name} (so future hooks/push know you)`);
2006
+ const ps = process.platform === "win32";
2007
+ lines.push(ps
2008
+ ? ` 2. $env:CREWBUS_TOKEN = Get-Content "${tokPath}" (0600 file written at register/mint)`
2009
+ : ` 2. export CREWBUS_TOKEN="$(cat ${tokPath})" (0600 file written at register/mint)`);
2010
+ lines.push(` 3. brief/resume context: worker-sessions/${top.name}.json holds your promptPath (re-read it if you were a spawned worker)`);
2011
+ return lines.join("\n");
2012
+ }
2013
+
1909
2014
  function cmdRegister(args) {
1910
2015
  const root = boardDir(args);
1911
2016
  refuseDriveRootBoard(root, args);
@@ -1943,6 +2048,8 @@ function cmdRegister(args) {
1943
2048
  // (this is register, so --target here means grant). Bare --for without
1944
2049
  // --role just touches/creates the target.
1945
2050
  const target = sanitizeName(forTargetRaw, "agent");
2051
+ const targetSentinel = reservedNameReason(target);
2052
+ if (targetSentinel) fail(targetSentinel);
1946
2053
  const admin = resolveAgent(args, "agent");
1947
2054
  checkToken(d, admin, resolveToken(args));
1948
2055
  authorize(d, admin, "role-grant");
@@ -2018,7 +2125,12 @@ function cmdRegister(args) {
2018
2125
  console.log(`granted ${target} role ${wantRole} [board ${d.root}]`);
2019
2126
  return;
2020
2127
  }
2021
- const doc = touchAgent(d, target, { sessionId: getFlag(args, "--session") || undefined, lastDir: process.cwd() });
2128
+ // NB: touchAgent on an EXISTING grant: --session only when given, else a
2129
+ // sessionless admin touch must not wipe the register-time binding (C1).
2130
+ const iSession = getFlag(args, "--session");
2131
+ const adminTouch = { lastDir: process.cwd() };
2132
+ if (iSession) adminTouch.sessionId = iSession;
2133
+ const doc = touchAgent(d, target, adminTouch);
2022
2134
  if (doc.offboarded !== undefined) { delete doc.offboarded; writeAgentFile(d, target, doc); }
2023
2135
  console.log(`registered ${target} [board ${d.root}]`);
2024
2136
  return;
@@ -2027,8 +2139,15 @@ function cmdRegister(args) {
2027
2139
  const serviceRaw = getFlag(args, "--service");
2028
2140
  const serviceFlag = serviceRaw !== undefined || args.includes("--service");
2029
2141
  const agent = serviceRaw !== undefined && serviceRaw !== "" ? sanitizeName(serviceRaw, "agent") : resolveAgent(args, "agent");
2142
+ const agentSentinel = reservedNameReason(agent);
2143
+ if (agentSentinel) fail(agentSentinel);
2030
2144
  const session = getFlag(args, "--session");
2031
2145
  const token = resolveToken(args);
2146
+ // mergeAgentDoc deletes patch keys whose value is undefined — so the
2147
+ // register binding must be added ONLY when a session is actually given,
2148
+ // else every sessionless re-register would wipe the binding (C1).
2149
+ const extra = { lastDir: process.cwd() };
2150
+ if (session) extra.sessionId = session;
2032
2151
  const expiresRaw = getFlag(args, "--expires-in");
2033
2152
  const expiresAt = expiresRaw !== undefined ? new Date(Date.now() + parseDuration(expiresRaw)).toISOString() : undefined;
2034
2153
  const prev = readAgent(d, agent);
@@ -2092,7 +2211,8 @@ function cmdRegister(args) {
2092
2211
  delete prev.token;
2093
2212
  writeAgentFile(d, agent, prev);
2094
2213
  }
2095
- const extra = { sessionId: session || undefined, lastDir: process.cwd() };
2214
+ // `extra` (built right after --session parsing above) has sessionId only
2215
+ // when given, so sessionless re-registers keep the prior binding.
2096
2216
  if (expiresRaw !== undefined) extra.expiresAt = expiresAt;
2097
2217
  if (serviceFlag) extra.service = true;
2098
2218
  const selfRoleWant = getFlag(args, "--role");
@@ -2467,7 +2587,7 @@ function cmdGroup(args) {
2467
2587
  const running = [];
2468
2588
  for (const m of t.members) {
2469
2589
  const rec = readAgent(d, m);
2470
- if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid)) running.push({ member: m, pid: rec.spawnedPid });
2590
+ if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt)) running.push({ member: m, pid: rec.spawnedPid });
2471
2591
  }
2472
2592
  const out = { ...t, running };
2473
2593
  if (rest.includes("--json")) {
@@ -2631,7 +2751,9 @@ function cmdChannel(args) {
2631
2751
  if (!body || !body.trim()) fail('missing message body (--body "...")');
2632
2752
  if (body.length > MAX_BODY_CHARS) fail(`message body too large (max ${MAX_BODY_CHARS} chars)`);
2633
2753
  const minted = ensureSender(d, from, resolveToken(rest));
2634
- authorize(d, from, "channel-post");
2754
+ // Member-scoped posting (C4): grp-<g> channels admit members of <g>;
2755
+ // board channels + foreign groups stay lead|admin (authorizeCheck).
2756
+ authorize(d, from, "channel-post", { channelGroup: chan.startsWith("grp-") ? chan.slice(4) : undefined });
2635
2757
  enforceBytesQuota(d, Buffer.byteLength(body.trim(), "utf8") + 1500);
2636
2758
  touchAgent(d, from, { lastDir: process.cwd() });
2637
2759
  const tokenHint = minted.created ? ` identity '${from}' claimed, token ${minted.token} (set CREWBUS_TOKEN=${minted.token})` : "";
@@ -2743,7 +2865,11 @@ function cmdSend(args) {
2743
2865
  if (recipients.length === 1 && !replyTo) {
2744
2866
  const dup = findDuplicateSend(d, from, recipients[0], body.trim());
2745
2867
  if (dup) {
2746
- touchAgent(d, from, { sessionId: session || undefined, lastDir: process.cwd() });
2868
+ // NB: sessionId only when given — mergeAgentDoc deletes undefined keys,
2869
+ // so a sessionless send must NOT wipe a register-time session binding.
2870
+ const dupExtra = { lastDir: process.cwd() };
2871
+ if (session) dupExtra.sessionId = session;
2872
+ touchAgent(d, from, dupExtra);
2747
2873
  console.log(`sent ${dup.id} -> ${recipients[0]} [board ${d.root}] (deduped: same body within 10s)`);
2748
2874
  return;
2749
2875
  }
@@ -2757,7 +2883,10 @@ function cmdSend(args) {
2757
2883
  const mirrorExtra = alsoChannel ? groupNames.length * (bodyLen + 1000) : 0;
2758
2884
  enforceBytesQuota(d, nFiles * (bodyLen + 1500) + mirrorExtra);
2759
2885
  }
2760
- touchAgent(d, from, { sessionId: session || undefined, lastDir: process.cwd() });
2886
+ // Same sentinel-wipe guard as above: sessionless sends keep bindings.
2887
+ const touchExtra = { lastDir: process.cwd() };
2888
+ if (session) touchExtra.sessionId = session;
2889
+ touchAgent(d, from, touchExtra);
2761
2890
  const tokenHint = minted.created ? ` identity '${from}' claimed, token ${minted.token} (set CREWBUS_TOKEN=${minted.token})` : "";
2762
2891
  const rev = gitRevForBoard(root);
2763
2892
  const at = new Date().toISOString();
@@ -2766,8 +2895,9 @@ function cmdSend(args) {
2766
2895
  appendChainRecord(d, from, "send", { to: recipients.slice(0, 20), count: recipients.length, batch: res.batch });
2767
2896
  const mirrored = alsoChannel
2768
2897
  ? 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(",")}` : "";
2898
+ : { mirrored: [], skipped: [] };
2899
+ const chanNote = (mirrored.mirrored.length > 0 ? ` +channel ${mirrored.mirrored.map((m) => m.channel).join(",")}` : "")
2900
+ + (mirrored.skipped.length > 0 ? ` [channel mirror skipped, members-only: ${mirrored.skipped.map((s) => s.group).join(",")}]` : "");
2771
2901
  if (res.mode === "broadcast") {
2772
2902
  const who = res.isAll ? "@all" : `${recipients.length} recipients`;
2773
2903
  console.log(`sent ${res.isAll ? "@all" : recipients.length + " messages"} via broadcast ${res.batch} to ${who} [board ${d.root}]${chanNote}${tokenHint}`);
@@ -2822,15 +2952,28 @@ function cmdSpawn(args) {
2822
2952
  const d = ensureBoard(root);
2823
2953
  const from = resolveAgent(args, "sender");
2824
2954
  const countRaw = getFlag(args, "--count");
2955
+ // Lead-revive (C9): `--count 0` boots NOTHING except the auto-coordinator
2956
+ // lane — for when the lead died (crash/reboot) and the crew needs its
2957
+ // coordinator back without re-briefing or re-booting any worker. Rows stay
2958
+ // put: no DMs are delivered, no worker pids are touched. Conflicting
2959
+ // worker selectors are refused (this path has no worker operands).
2960
+ let revive = false;
2825
2961
  let autoNames = [];
2826
2962
  if (countRaw !== undefined) {
2827
2963
  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}`);
2964
+ 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)");
2965
+ if (n === 0) {
2966
+ revive = true;
2967
+ if (getFlag(args, "--to") !== undefined || getFlag(args, "--to-file") !== undefined || getFlag(args, "--to-group") !== undefined) {
2968
+ 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");
2969
+ }
2970
+ } else {
2971
+ const prefix = String(getFlag(args, "--prefix") || "worker").trim().toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 30);
2972
+ if (!prefix) fail("invalid --prefix");
2973
+ for (let i = 1; i <= n; i++) autoNames.push(`${prefix}-${i}`);
2974
+ }
2832
2975
  }
2833
- const recipients = parseRecipients(getFlag(args, "--to"), getFlag(args, "--to-file"), expandGroupsOrFail(d, getFlag(args, "--to-group")).concat(autoNames));
2976
+ const recipients = revive ? [] : parseRecipients(getFlag(args, "--to"), getFlag(args, "--to-file"), expandGroupsOrFail(d, getFlag(args, "--to-group")).concat(autoNames));
2834
2977
  if (recipients.includes("@all")) fail("spawn --to @all is refused: @all membership is dynamic (late joiners included) — name the workers explicitly");
2835
2978
  const maxSpawnRaw = getFlag(args, "--max-spawn");
2836
2979
  const maxSpawn = maxSpawnRaw === undefined ? MAX_SPAWN : Number(maxSpawnRaw);
@@ -2840,10 +2983,11 @@ function cmdSpawn(args) {
2840
2983
  // the pid record: refuse only names with a live pid, before anything is
2841
2984
  // written or booted. Stale or never-booted names are reusable (spawn
2842
2985
  // overwrites the pid) — so groups whose members already claimed names
2843
- // still boot fine.
2986
+ // still boot fine. A pid-recycled record (reboot + OS pid reuse) counts
2987
+ // as reusable too: the pid belongs to an unrelated process (C2).
2844
2988
  for (const name of recipients) {
2845
2989
  const rec = readAgent(d, name);
2846
- if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid)) {
2990
+ if (rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt)) {
2847
2991
  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
2992
  }
2849
2993
  }
@@ -2916,6 +3060,9 @@ function cmdSpawn(args) {
2916
3060
  if (leadMode === "board" && !hasCodingHarness) {
2917
3061
  fail('--lead board needs a coding harness for the auto-coordinator (add --harness opencode, or pass --lead none under --harness generic)');
2918
3062
  }
3063
+ if (revive && leadMode !== "board") {
3064
+ fail("--count 0 is the lead-revive path: it needs the auto-coordinator (--lead board — the default when a coding harness is present)");
3065
+ }
2919
3066
  const leadTarget = leadMode === "board" ? "lead" : from;
2920
3067
  const model = getFlag(args, "--model");
2921
3068
  const auto = args.includes("--auto");
@@ -2943,10 +3090,19 @@ function cmdSpawn(args) {
2943
3090
  }
2944
3091
  const budgetTokensRaw = getFlag(args, "--budget-tokens");
2945
3092
  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");
3093
+ const budgetTokens = budgetTokensRaw === undefined ? undefined : Number(budgetTokensRaw);
3094
+ const budgetMinutes = budgetMinutesRaw === undefined ? undefined : Number(budgetMinutesRaw);
3095
+ if (budgetTokensRaw !== undefined && !(budgetTokens > 0)) fail("--budget-tokens must be a positive number");
3096
+ if (budgetMinutesRaw !== undefined && !(budgetMinutes > 0)) fail("--budget-minutes must be a positive number");
3097
+ // Coordinator budget (C5): same semantics as worker budgets, on the
3098
+ // auto-provisioned lead lane. Unset (the common case) = persistent boss-supervised
3099
+ // coordinator, same behavior as 10.0.10.
3100
+ const leadBudgetTokensRaw = getFlag(args, "--lead-budget-tokens");
3101
+ const leadBudgetMinutesRaw = getFlag(args, "--lead-budget-minutes");
3102
+ const leadBudgetTokens = leadBudgetTokensRaw === undefined ? undefined : Number(leadBudgetTokensRaw);
3103
+ const leadBudgetMinutes = leadBudgetMinutesRaw === undefined ? undefined : Number(leadBudgetMinutesRaw);
3104
+ if (leadBudgetTokensRaw !== undefined && !(leadBudgetTokens > 0)) fail("--lead-budget-tokens must be a positive number");
3105
+ if (leadBudgetMinutesRaw !== undefined && !(leadBudgetMinutes > 0)) fail("--lead-budget-minutes must be a positive number");
2950
3106
  const timeoutRaw = getFlag(args, "--timeout");
2951
3107
  let deadlineAt = undefined;
2952
3108
  if (timeoutRaw !== undefined) {
@@ -2985,20 +3141,26 @@ function cmdSpawn(args) {
2985
3141
  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")) };
2986
3142
  if (dry) {
2987
3143
  // 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]) })}`);
3144
+ const previewBatch = !revive && recipients.length > 1 ? newId("batch") : undefined;
3145
+ if (!revive) {
3146
+ recipients.forEach((to, i) => {
3147
+ const driver = harnesses[i % harnesses.length];
3148
+ const itemMaxTurns = maxTurnsNum !== undefined ? maxTurnsNum : ((driver === "claude" || driver === "grok") ? 50 : undefined);
3149
+ const itemSpawnOpts = { ...spawnOpts, harness: driver, maxTurns: itemMaxTurns, allowTools: driver === "claude" ? allowTools : undefined };
3150
+ 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) });
3151
+ const t = buildSpawnTarget({ ...itemSpawnOpts, name: to, promptPath: `<logs>/${to}-<stamp>.prompt.md`, prompt: previewPrompt });
3152
+ const wtNote = worktreePrefix !== undefined ? ` worktree ../${to}-<stamp> (branch ${worktreePrefix}/${to}-<stamp>)` : branchPrefix !== undefined ? ` branch ${branchPrefix}/${to}-<stamp>` : "";
3153
+ console.log(`would spawn ${to} [${driver}] (${lifetime}) cwd ${cwd}${wtNote} cmd: ${formatSpawnCmd(t)} [board ${d.root}]`);
3154
+ });
3155
+ 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]) })}`);
3156
+ } else {
3157
+ console.log(`lead-revive: would ONLY provision/reuse the auto-coordinator on the '${leadTarget}' lane (0 workers, no DMs delivered) [board ${d.root}]`);
3158
+ }
2999
3159
  if (leadMode === "board") {
3000
3160
  const existingLead = readAgent(d, "lead");
3001
- const standing = existingLead && typeof existingLead.spawnedPid === "number" && pidAlive(existingLead.spawnedPid);
3161
+ // Stale-pid guard (C2): preview says "fresh provision" when the pid
3162
+ // record is recycled (reboot + OS pid reuse).
3163
+ const standing = existingLead && typeof existingLead.spawnedPid === "number" && pidAlive(existingLead.spawnedPid) && !isPidStale(existingLead.spawnedPid, existingLead.spawnedAt);
3002
3164
  if (standing) {
3003
3165
  console.log(`--- lead ---\na live coordinator already runs on the 'lead' lane (pid ${existingLead.spawnedPid}) — reused, not duplicated [board ${d.root}]`);
3004
3166
  } else if (existingLead && existingLead.offboarded) {
@@ -3006,7 +3168,7 @@ function cmdSpawn(args) {
3006
3168
  } else {
3007
3169
  const coordPreview = buildCoordinatorPrompt({
3008
3170
  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] })),
3171
+ workers: revive ? [] : recipients.map((name, i) => ({ name, id: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", harness: harnesses[i % harnesses.length] })),
3010
3172
  crew: crewFor(recipients[0], leadTarget), cwd, root, auto, workbench: wbFor(recipients[0]),
3011
3173
  });
3012
3174
  console.log(`--- lead ---\nwould spawn lead [${harnesses[0]}] (persistent — auto-provisioned lead, owner of this crew) cwd ${cwd} [board ${d.root}]`);
@@ -3017,11 +3179,21 @@ function cmdSpawn(args) {
3017
3179
  }
3018
3180
  // Direct (N-copy) path is forced here (every worker needs its own message
3019
3181
  // 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 });
3182
+ // Lead-revive (C9) skips all of it: zero workers, zero DMs — the mission
3183
+ // text feeds the coordinator prompt directly.
3184
+ let res = null;
3185
+ if (!revive) {
3186
+ res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, priority, senderType, fwd, rev, at, forceBroadcast: false, forceDirect: true, needsBy });
3187
+ if (res.mode !== "direct") fail("spawn: internal error — expected direct delivery");
3188
+ }
3189
+ appendChainRecord(d, from, "spawn", { to: recipients.slice(), harness, harnesses, auto, cwd, isolate: isolateInfo.isolated || false, budgetTokens, budgetMinutes, deadlineAt, ...(revive ? { revive: true } : {}) });
3190
+ if (!revive) {
3191
+ let chanMirrorNote = "";
3023
3192
  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 });
3193
+ 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 });
3194
+ chanMirrorNote = (m.mirrored.length > 0 ? ` +channel ${m.mirrored.map((x) => x.channel).join(",")}` : "")
3195
+ + (m.skipped.length > 0 ? ` [channel mirror skipped, members-only: ${m.skipped.map((s) => s.group).join(",")}]` : "");
3196
+ process.stderr.write(`crewbus:${chanMirrorNote}\n`);
3025
3197
  }
3026
3198
  for (let i = 0; i < res.items.length; i++) {
3027
3199
  const { to, id } = res.items[i];
@@ -3052,10 +3224,13 @@ function cmdSpawn(args) {
3052
3224
  } catch (e) {
3053
3225
  console.log(`spawn FAILED ${to}: ${e.message} (brief ${id} still waits on the board) [board ${d.root}]`);
3054
3226
  }
3227
+ }
3055
3228
  }
3056
- // Auto-provisioned lead: runs after the crew boots so the coordinator's
3229
+ // Auto-provisioned lead: runs after the crew boots so the coordinator's
3057
3230
  // roster carries the real brief ids, and so a lead boot failure can never
3058
- // block worker boots.
3231
+ // block worker boots. Lead-revive (C9): also runs here with an EMPTY
3232
+ // roster — the revive mission text becomes the coordinator's reminder of
3233
+ // what the crew was on about (worker threads/scope live on the board).
3059
3234
  if (leadMode === "board") {
3060
3235
  const coordHarness = [ // first coding harness wins; generic is excluded above
3061
3236
  ...harnesses.filter((h) => h !== "generic"),
@@ -3063,8 +3238,9 @@ function cmdSpawn(args) {
3063
3238
  const provision = provisionAutoLead(d, {
3064
3239
  spawnOpts: { ...spawnOpts, harness: coordHarness, maxTurns: undefined, allowTools: undefined },
3065
3240
  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,
3241
+ workers: res ? res.items.map((it, i) => ({ name: it.to, id: it.id, harness: harnesses[i % harnesses.length] })) : [],
3242
+ batch: res ? res.batch : undefined, crew: crewFor(recipients[0], leadTarget), workbench: wbFor(recipients[0]), auto,
3243
+ budgetTokens: leadBudgetTokens, budgetMinutes: leadBudgetMinutes,
3068
3244
  });
3069
3245
  if (provision.action === "minted" && provision.pid) {
3070
3246
  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}]`);
@@ -3434,7 +3610,9 @@ async function cmdRespawn(args) {
3434
3610
  }
3435
3611
  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")) };
3436
3612
  const attempt = ((prev.respawnCount) || 0) + 1;
3437
- const alive = typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid);
3613
+ // Recycled-pid records read dead for respawn gating too (C2): a live pid
3614
+ // that postdates the spawn belongs to an unrelated process.
3615
+ const alive = typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt);
3438
3616
  if (dry) {
3439
3617
  const catchup = buildRespawnBrief({ name, attempt, origPromptPath: prev.promptPath, briefId, harnessSessionId: sessionId || null, harness, lead: from, extraBody });
3440
3618
  const t = buildRespawnTarget({ ...spawnOpts, name, promptPath: `<logs>/${name}-<stamp>.respawn.md`, prompt: catchup, sessionId: sessionId || undefined });
@@ -3730,7 +3908,69 @@ function cmdLesson(args) {
3730
3908
  fail(`unknown lesson subcommand "${sub}" (want post|list)`);
3731
3909
  }
3732
3910
 
3911
+ // inbox archive (C6 lead-lane hygiene): move ACKED direct DMs (and checkpoints,
3912
+ // which are progress-not-work) out of dm/<agent>/ into dm-archive/<agent>/.
3913
+ // Self-scoped bookkeeping (authenticated owner, ack-level authorization):
3914
+ // unacked work NEVER archives implicitly — a scope is mandatory (--all, or
3915
+ // --before <dur> for rows older than the window). Broadcasts are NOT moved
3916
+ // (they are single board-level files shared by all recipients) — pruning
3917
+ // those is an admin `prune` concern. Id collisions (the archive already has
3918
+ // the file) keep the original in place rather than double-mutating.
3919
+ function cmdInboxArchive(args) {
3920
+ const root = boardDir(args);
3921
+ refuseDriveRootBoard(root, args);
3922
+ const d = requireBoard(root);
3923
+ const agent = resolveAgent(args, "reader");
3924
+ checkToken(d, agent, resolveToken(args));
3925
+ authorize(d, agent, "ack"); // own inbox only, never reads others'
3926
+ const wantAll = args.includes("--all");
3927
+ const before = getFlag(args, "--before");
3928
+ if (!wantAll && before === undefined) {
3929
+ 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");
3930
+ }
3931
+ let cutoff = 0;
3932
+ if (before !== undefined) {
3933
+ const ms = parseDuration(before);
3934
+ if (!(ms > 0)) fail("--before must be a positive duration (e.g. 7d, 30m)");
3935
+ cutoff = Date.now() - ms;
3936
+ }
3937
+ const acked = ackedIds(d, agent);
3938
+ const src = path.join(d.dm, agent);
3939
+ const dst = path.join(path.dirname(d.dm), "dm-archive", agent);
3940
+ let files = [];
3941
+ try { files = fs.readdirSync(src).filter((f) => f.endsWith(".json")); } catch {}
3942
+ let moved = 0;
3943
+ let kept = 0;
3944
+ for (const f of files) {
3945
+ const srcP = path.join(src, f);
3946
+ let m = null;
3947
+ try { m = readJson(srcP); } catch { kept++; continue; }
3948
+ if (!m || !m.id) { kept++; continue; }
3949
+ const isAcked = acked.has(m.id);
3950
+ const isCkpt = m.checkpoint === true;
3951
+ if (!isAcked && !isCkpt) { kept++; continue; }
3952
+ if (!wantAll) {
3953
+ const t = Date.parse(m.at || "");
3954
+ if (Number.isNaN(t) || t >= cutoff) { kept++; continue; }
3955
+ }
3956
+ fs.mkdirSync(dst, { recursive: true });
3957
+ const dstP = path.join(dst, f);
3958
+ if (fs.existsSync(dstP)) { kept++; continue; }
3959
+ fs.renameSync(srcP, dstP);
3960
+ moved++;
3961
+ }
3962
+ if (args.includes("--json")) {
3963
+ console.log(JSON.stringify({ agent, moved, kept, archive: dst }));
3964
+ return;
3965
+ }
3966
+ console.log(`archived ${moved} message(s) for ${agent} -> dm-archive/${agent}/ (kept ${kept}${wantAll ? "" : ", --before window"}) [board ${d.root}]`);
3967
+ if (kept === moved && moved === 0) console.log(`nothing scoped to archive — unacked work stays put (ack it or pass --all)`);
3968
+ }
3969
+
3733
3970
  function cmdInbox(args) {
3971
+ if (args[0] === "archive") return cmdInboxArchive(args.slice(1));
3972
+ const archivedView = args.includes("--archived");
3973
+ args = archivedView ? args.filter((a) => a !== "--archived") : args;
3734
3974
  const root = boardDir(args);
3735
3975
  refuseDriveRootBoard(root, args);
3736
3976
  const d = requireBoard(root);
@@ -3774,7 +4014,16 @@ function cmdInbox(args) {
3774
4014
  checkToken(d, agent, resolveToken(args)); // your inbox is addressed to you — prove it
3775
4015
  authorize(d, agent, "inbox"); // reads allow all roles (auditor read-ok)
3776
4016
  heartbeat(d, agent, 0); // reading your mail proves you're alive
3777
- items = readVisible(d, agent);
4017
+ // --archived (C6): opt-in view of dm-archive/<agent>/ (moved by
4018
+ // `crewbus inbox archive`). Direct DMs only; ack state shown from the
4019
+ // live ack dir. --unacked on an archive is naturally empty.
4020
+ if (archivedView) {
4021
+ const dAr = { ...d, dm: path.join(path.dirname(d.dm), "dm-archive") };
4022
+ items = readDMs(dAr, agent);
4023
+ items.sort((a, b) => String(a.at).localeCompare(String(b.at)) || String(a.id).localeCompare(String(b.id)));
4024
+ } else {
4025
+ items = readVisible(d, agent);
4026
+ }
3778
4027
  acked = ackedIds(d, agent);
3779
4028
  if (json) {
3780
4029
  items = items.map((m) => (acked.has(m.id) ? { ...m, acked: true } : m));
@@ -6364,7 +6613,7 @@ async function cmdServe(args) {
6364
6613
  try {
6365
6614
  for (const e of listJson(path.join(d.root, "agents"))) {
6366
6615
  if (!e || !e.data) continue;
6367
- if (typeof e.data.spawnedPid === "number" && pidAlive(e.data.spawnedPid)) workers++;
6616
+ if (typeof e.data.spawnedPid === "number" && pidAlive(e.data.spawnedPid) && !isPidStale(e.data.spawnedPid, e.data.spawnedAt)) workers++;
6368
6617
  }
6369
6618
  } catch {}
6370
6619
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "x-relay-role": role });
@@ -6603,6 +6852,12 @@ Setup:
6603
6852
  Identity (first claim wins, token after that):
6604
6853
  crewbus register --from <you> [--session <opencode-session-id>] [--token <t>] [--expires-in <dur>] [--service]
6605
6854
  crewbus register --service <name> | register --offboard <name> --from <admin>
6855
+ crewbus recover [--session <id>] [--cwd <dir>]
6856
+ (compaction/restart amnesia triage: lists candidate identities with
6857
+ evidence (register session binding, token-file↔tokenHash cross-check,
6858
+ cwd history) and prints the exact resume commands. Read-only, never
6859
+ mints. Reserved sentinel names ("unknown", "me", "you") refuse to
6860
+ register/send — they exist only for tools that forget who they are.)
6606
6861
  crewbus agents [--json] [--active] [--window <sec>] [--include-services]
6607
6862
  (--active lists only agents seen within the window, default 300s;
6608
6863
  every inbox/listen/send heartbeats your presence.
@@ -6683,7 +6938,12 @@ Messaging (primitive — just a tool call, whenever you want):
6683
6938
  differently. Later spawn briefs whose groups (or --scope-less/global)
6684
6939
  match auto-inject the latest lessons, so a lesson learned once is
6685
6940
  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]
6941
+ crewbus inbox archive --from <you> (--all | --before <dur>) [--json]
6942
+ (inbox hygiene: move acked direct DMs + checkpoints from dm/<you>/ into
6943
+ dm-archive/<you>/ — unacked work NEVER archives implicitly (a scope is
6944
+ mandatory). Broadcasts are board-level files and stay (prune territory:
6945
+ only admin). Read them back with 'crewbus inbox --from <you> --archived'.)
6946
+ 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
6947
  (--older-than keeps only messages older than the window: inbox --unacked
6688
6948
  --older-than 10m lists briefs nobody picked up (retry via redeliver or
6689
6949
  re-send). --overdue lists still-open briefs whose --needs-by deadline
@@ -6708,7 +6968,8 @@ Messaging (primitive — just a tool call, whenever you want):
6708
6968
  (recover mail a dead watcher consumed: clears delivered markers and
6709
6969
  rewinds the cursor so the next poll/push treats it as fresh;
6710
6970
  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]
6971
+ 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] [--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]
6972
+ (--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
6973
  (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
6974
  (brief N workers AND boot them detached: the DM lands first so the brief
6714
6975
  waits even if a launch fails. opencode: \`run\` + brief via --file;
@@ -6728,7 +6989,9 @@ Messaging (primitive — just a tool call, whenever you want):
6728
6989
  receive mail — their replies wait on the board for pull (inbox/gather).
6729
6990
  --auto maps to each harness's
6730
6991
  unattended mode (dangerous); --dry-run prints the exact command without
6731
- touching the board.)
6992
+ touching the board. --count 0 is the LEAD REVIVE path: boots nothing
6993
+ except the auto-coordinator lane (no workers, no DMs) — for bringing the
6994
+ coordinator back after a crash/reboot without re-briefing the crew.)
6732
6995
  crewbus spawn-status --to <worker> [--lines 10] [--json] | --all
6733
6996
  (is it running? did the reply land? pid liveness via kill-0 plus process
6734
6997
  start-time validation — reboot-recycled pids read dead (stale pid) instead
@@ -7747,6 +8010,7 @@ async function main() {
7747
8010
  case "install-cli": return cmdInstallCli();
7748
8011
  case "update": return cmdUpdate(rest);
7749
8012
  case "register": return cmdRegister(rest);
8013
+ case "recover": return cmdRecover(rest);
7750
8014
  case "acl": return cmdAcl(rest);
7751
8015
  case "agents": return cmdAgents(rest);
7752
8016
  case "send": return cmdSend(rest);