crewbus 10.0.9 → 10.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/crewbus.js CHANGED
@@ -42,11 +42,11 @@ 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
- import { assertGitCheckout, bootRespawnedWorker, bootWorker, buildCrewContext, buildRespawnBrief, buildRespawnTarget, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, isPidStale, killWorkers, maybeIsolate, opencodeStorageStatus, parseAllowEnv, pidAlive, provisionBranch, provisionWorktree, readWorkerSession, requireAutoConfirm, resolveOpencodeExe, sandboxPresent, scrubChildEnv, syncWorkerSession, workerStatus, worktreeStamp, defaultMaxTurnsFor, ensureBoardCliShim, installCliToUserPath } from "./lib/spawn.js";
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";
50
50
  import { appendChainRecord, auditHmacKey, boardTotalBytes, chainFilePath, countChannels, dirSize, doExportToFile, enforceAgentQuota, enforceBytesQuota, enforceChannelQuota, holdActive, holdDocPath, holdRefusal, parseQuotaBytes, parseQuotaCount, readBackupInner, readBoardQuotas, readChainRecords, readHold, readSnapshotSchedule, resolveBackupKeyMaterial, setAuditForward, snapshotStamp, startAuditForwarder, verifyChainRecords, collectBoardFiles, encryptBackupPayload, decryptBackupPayload, rawKeyFromMaterial, deriveBackupKey, toAuditExport, spoolAuditEvent, postAuditEvent, auditSpoolDir, drainAuditSpool, enqueueAuditForward, signAuditRecord, chainRecordHash, AUDIT_FORWARD_URL, AUDIT_FORWARD_KEY } from "./lib/export.js";
51
51
  import { ackedIds, checkSendRateLimit, deliverDMs, enforceMaxChars, filterDigest, findDuplicateSend, findMessageById, heartbeat, isVerified, loadManifest, manifestPath, msgTimeMs, parseRecipients, printDigest, printMsg, readDMs, readVisible, recordBroadcastManifest, requireFanoutConfirm, resolveFwdDepth, runVerifier, verifyMessageSig, isHigh, signMessage, untrustedEnvelope, relTime, rateFilePath, broadcastTargets, readBroadcastsFor, formatTo, msgHeader, readAckMarker, splitCommand, readRecipientsFile } from "./lib/mail.js";
52
52
  import { batchReplyIds, collectBatch, contributingGroups, expandGroups, expandGroupsOrFail, gatherTelemetry, groupTelemetryData, heuristicSenderType, readGroup, ensureGroupCreatedAt, readResultRecord, writeResultRecord, findFirstVerifiedReply } from "./lib/groups.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
  }
@@ -2893,7 +3037,33 @@ function cmdSpawn(args) {
2893
3037
  rosterGroups.sort((a, b) => String(a.name).localeCompare(String(b.name)));
2894
3038
  const taskGroups = rosterGroups.filter((g) => groupNames.includes(g.name));
2895
3039
  const offTask = rosterGroups.length - taskGroups.length;
2896
- const crewFor = (to) => buildCrewContext({ name: to, from, subject, groups: taskGroups, myGroups: taskGroups.filter((g) => g.members.includes(to)).map((g) => g.name), offTask });
3040
+ 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 });
3041
+ // Lead auto-assignment (§auto-lead): `--lead auto|board|none` (default: auto).
3042
+ // Under `board` (or `auto` with a coding harness), spawn and lead are
3043
+ // separated: workers pin replies to the board's standing 'lead' lane and a
3044
+ // detached persistent coordinator is provisioned after the crew boots; the
3045
+ // spawner stays boss (reads, milestone DMs). `--lead none` (or `auto` with
3046
+ // purely generic harnesses) is the legacy star topology: replies pin to the
3047
+ // spawner, nothing else is provisioned.
3048
+ const leadFlagRaw = getFlag(args, "--lead");
3049
+ const hasCodingHarness = harnesses.some((h) => h !== "generic");
3050
+ let leadMode;
3051
+ if (leadFlagRaw === undefined) {
3052
+ leadMode = hasCodingHarness ? "board" : "none";
3053
+ } else {
3054
+ leadMode = String(leadFlagRaw).trim().toLowerCase();
3055
+ if (leadMode === "auto") {
3056
+ leadMode = hasCodingHarness ? "board" : "none";
3057
+ }
3058
+ }
3059
+ if (!["board", "none"].includes(leadMode)) fail(`invalid --lead "${leadFlagRaw}" (want auto|board|none)`);
3060
+ if (leadMode === "board" && !hasCodingHarness) {
3061
+ fail('--lead board needs a coding harness for the auto-coordinator (add --harness opencode, or pass --lead none under --harness generic)');
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
+ }
3066
+ const leadTarget = leadMode === "board" ? "lead" : from;
2897
3067
  const model = getFlag(args, "--model");
2898
3068
  const auto = args.includes("--auto");
2899
3069
  requireAutoConfirm(args);
@@ -2920,10 +3090,19 @@ function cmdSpawn(args) {
2920
3090
  }
2921
3091
  const budgetTokensRaw = getFlag(args, "--budget-tokens");
2922
3092
  const budgetMinutesRaw = getFlag(args, "--budget-minutes");
2923
- const budgetTokens = budgetTokensRaw === undefined ? undefined : Number(budgetTokensRaw);
2924
- const budgetMinutes = budgetMinutesRaw === undefined ? undefined : Number(budgetMinutesRaw);
2925
- if (budgetTokensRaw !== undefined && !(budgetTokens > 0)) fail("--budget-tokens must be a positive number");
2926
- 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");
2927
3106
  const timeoutRaw = getFlag(args, "--timeout");
2928
3107
  let deadlineAt = undefined;
2929
3108
  if (timeoutRaw !== undefined) {
@@ -2962,26 +3141,59 @@ function cmdSpawn(args) {
2962
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")) };
2963
3142
  if (dry) {
2964
3143
  // Preview only: nothing touches the board (ids below are illustrative).
2965
- const previewBatch = recipients.length > 1 ? newId("batch") : undefined;
2966
- recipients.forEach((to, i) => {
2967
- const driver = harnesses[i % harnesses.length];
2968
- const itemMaxTurns = maxTurnsNum !== undefined ? maxTurnsNum : ((driver === "claude" || driver === "grok") ? 50 : undefined);
2969
- const itemSpawnOpts = { ...spawnOpts, harness: driver, maxTurns: itemMaxTurns, allowTools: driver === "claude" ? allowTools : undefined };
2970
- const previewPrompt = buildSpawnPrompt({ name: to, from, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(to), workbench: wbFor(to) });
2971
- const t = buildSpawnTarget({ ...itemSpawnOpts, name: to, promptPath: `<logs>/${to}-<stamp>.prompt.md`, prompt: previewPrompt });
2972
- const wtNote = worktreePrefix !== undefined ? ` worktree ../${to}-<stamp> (branch ${worktreePrefix}/${to}-<stamp>)` : branchPrefix !== undefined ? ` branch ${branchPrefix}/${to}-<stamp>` : "";
2973
- console.log(`would spawn ${to} [${driver}] (${lifetime}) cwd ${cwd}${wtNote} cmd: ${formatSpawnCmd(t)} [board ${d.root}]`);
2974
- });
2975
- console.log(`--- prompt (first worker) ---\n${buildSpawnPrompt({ name: recipients[0], from, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(recipients[0]), 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
+ }
3159
+ if (leadMode === "board") {
3160
+ const existingLead = readAgent(d, "lead");
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);
3164
+ if (standing) {
3165
+ console.log(`--- lead ---\na live coordinator already runs on the 'lead' lane (pid ${existingLead.spawnedPid}) — reused, not duplicated [board ${d.root}]`);
3166
+ } else if (existingLead && existingLead.offboarded) {
3167
+ console.log(`--- lead ---\nlane "lead" is offboarded: provision would be SKIPPED (re-onboard it, or pass --lead none) [board ${d.root}]`);
3168
+ } else {
3169
+ const coordPreview = buildCoordinatorPrompt({
3170
+ name: "lead", from, subject, body: body.trim(), batch: previewBatch,
3171
+ workers: revive ? [] : recipients.map((name, i) => ({ name, id: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", harness: harnesses[i % harnesses.length] })),
3172
+ crew: crewFor(recipients[0], leadTarget), cwd, root, auto, workbench: wbFor(recipients[0]),
3173
+ });
3174
+ console.log(`--- lead ---\nwould spawn lead [${harnesses[0]}] (persistent — auto-provisioned lead, owner of this crew) cwd ${cwd} [board ${d.root}]`);
3175
+ console.log(`--- coordinator prompt (preview) ---\n${coordPreview}`);
3176
+ }
3177
+ }
2976
3178
  return;
2977
3179
  }
2978
3180
  // Direct (N-copy) path is forced here (every worker needs its own message
2979
3181
  // id to thread the reply against) — --broadcast is not accepted by spawn.
2980
- const res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, priority, senderType, fwd, rev, at, forceBroadcast: false, forceDirect: true, needsBy });
2981
- if (res.mode !== "direct") fail("spawn: internal error — expected direct delivery");
2982
- 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 = "";
2983
3192
  if (alsoChannel) {
2984
- 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`);
2985
3197
  }
2986
3198
  for (let i = 0; i < res.items.length; i++) {
2987
3199
  const { to, id } = res.items[i];
@@ -3006,12 +3218,41 @@ function cmdSpawn(args) {
3006
3218
  } else if (branchPrefix !== undefined) {
3007
3219
  workerBranch = provisionBranch(cwd, branchPrefix, to).branch;
3008
3220
  }
3009
- const r = bootWorker(d, { ...itemSpawnOpts, cwd: workerCwd }, { to, id, from, subject, body: body.trim(), rev, logDir, budgetTokens, budgetMinutes, deadlineAt, spawnedWorktree: workerWorktree, spawnedBranch: workerBranch, spawnedLifetime: lifetime, crew: crewFor(to), workbench: wbFor(to) });
3221
+ const r = bootWorker(d, { ...itemSpawnOpts, cwd: workerCwd }, { to, id, from, lead: leadTarget, subject, body: body.trim(), rev, logDir, budgetTokens, budgetMinutes, deadlineAt, spawnedWorktree: workerWorktree, spawnedBranch: workerBranch, spawnedLifetime: lifetime, crew: crewFor(to, leadTarget), workbench: wbFor(to) });
3010
3222
  const where = workerWorktree ? ` worktree ${workerWorktree}` : workerBranch ? ` branch ${workerBranch}` : "";
3011
3223
  console.log(`spawned ${to} pid ${r.pid} [${driver}] (${lifetime}) log ${r.logPath} reply ${id}${where} [board ${d.root}]`);
3012
3224
  } catch (e) {
3013
3225
  console.log(`spawn FAILED ${to}: ${e.message} (brief ${id} still waits on the board) [board ${d.root}]`);
3014
3226
  }
3227
+ }
3228
+ }
3229
+ // Auto-provisioned lead: runs after the crew boots so the coordinator's
3230
+ // roster carries the real brief ids, and so a lead boot failure can never
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).
3234
+ if (leadMode === "board") {
3235
+ const coordHarness = [ // first coding harness wins; generic is excluded above
3236
+ ...harnesses.filter((h) => h !== "generic"),
3237
+ ][0] || "opencode";
3238
+ const provision = provisionAutoLead(d, {
3239
+ spawnOpts: { ...spawnOpts, harness: coordHarness, maxTurns: undefined, allowTools: undefined },
3240
+ from, subject, body: body.trim(), rev, logDir,
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,
3244
+ });
3245
+ if (provision.action === "minted" && provision.pid) {
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}]`);
3247
+ if (provision.token) console.log(`lead token (set CREWBUS_TOKEN=${provision.token} to act as '${provision.leadName}'): also saved to logs/lead.token`);
3248
+ } else if (provision.action === "minted") {
3249
+ console.log(`auto-lead provisioned with a caveat: ${provision.reason} [board ${d.root}]`);
3250
+ } else if (provision.action === "reused") {
3251
+ const standing = provision.pid ? `coordinator pid ${provision.pid} (standing)` : `claimed, no live coordinator — boot with: spawn --from ${from} --to ${provision.leadName} --persistent --body "you are the lead, read your crew"`;
3252
+ console.log(`auto-lead reused: '${provision.leadName}' lane (${standing}); this crew transferred to it (${provision.transferred} worker(s)) [board ${d.root}]`);
3253
+ } else {
3254
+ console.log(`auto-lead SKIPPED: ${provision.reason || "no reason recorded"} [board ${d.root}]`);
3255
+ }
3015
3256
  }
3016
3257
  }
3017
3258
 
@@ -3369,7 +3610,9 @@ async function cmdRespawn(args) {
3369
3610
  }
3370
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")) };
3371
3612
  const attempt = ((prev.respawnCount) || 0) + 1;
3372
- 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);
3373
3616
  if (dry) {
3374
3617
  const catchup = buildRespawnBrief({ name, attempt, origPromptPath: prev.promptPath, briefId, harnessSessionId: sessionId || null, harness, lead: from, extraBody });
3375
3618
  const t = buildRespawnTarget({ ...spawnOpts, name, promptPath: `<logs>/${name}-<stamp>.respawn.md`, prompt: catchup, sessionId: sessionId || undefined });
@@ -3665,7 +3908,69 @@ function cmdLesson(args) {
3665
3908
  fail(`unknown lesson subcommand "${sub}" (want post|list)`);
3666
3909
  }
3667
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
+
3668
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;
3669
3974
  const root = boardDir(args);
3670
3975
  refuseDriveRootBoard(root, args);
3671
3976
  const d = requireBoard(root);
@@ -3709,7 +4014,16 @@ function cmdInbox(args) {
3709
4014
  checkToken(d, agent, resolveToken(args)); // your inbox is addressed to you — prove it
3710
4015
  authorize(d, agent, "inbox"); // reads allow all roles (auditor read-ok)
3711
4016
  heartbeat(d, agent, 0); // reading your mail proves you're alive
3712
- 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
+ }
3713
4027
  acked = ackedIds(d, agent);
3714
4028
  if (json) {
3715
4029
  items = items.map((m) => (acked.has(m.id) ? { ...m, acked: true } : m));
@@ -6299,7 +6613,7 @@ async function cmdServe(args) {
6299
6613
  try {
6300
6614
  for (const e of listJson(path.join(d.root, "agents"))) {
6301
6615
  if (!e || !e.data) continue;
6302
- 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++;
6303
6617
  }
6304
6618
  } catch {}
6305
6619
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "x-relay-role": role });
@@ -6538,6 +6852,12 @@ Setup:
6538
6852
  Identity (first claim wins, token after that):
6539
6853
  crewbus register --from <you> [--session <opencode-session-id>] [--token <t>] [--expires-in <dur>] [--service]
6540
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.)
6541
6861
  crewbus agents [--json] [--active] [--window <sec>] [--include-services]
6542
6862
  (--active lists only agents seen within the window, default 300s;
6543
6863
  every inbox/listen/send heartbeats your presence.
@@ -6618,7 +6938,12 @@ Messaging (primitive — just a tool call, whenever you want):
6618
6938
  differently. Later spawn briefs whose groups (or --scope-less/global)
6619
6939
  match auto-inject the latest lessons, so a lesson learned once is
6620
6940
  paid forward. post needs your token; list is open.)
6621
- 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]
6622
6947
  (--older-than keeps only messages older than the window: inbox --unacked
6623
6948
  --older-than 10m lists briefs nobody picked up (retry via redeliver or
6624
6949
  re-send). --overdue lists still-open briefs whose --needs-by deadline
@@ -6643,7 +6968,8 @@ Messaging (primitive — just a tool call, whenever you want):
6643
6968
  (recover mail a dead watcher consumed: clears delivered markers and
6644
6969
  rewinds the cursor so the next poll/push treats it as fresh;
6645
6970
  use after re-registering with the live session)
6646
- 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.)
6647
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.)
6648
6974
  (brief N workers AND boot them detached: the DM lands first so the brief
6649
6975
  waits even if a launch fails. opencode: \`run\` + brief via --file;
@@ -6663,7 +6989,9 @@ Messaging (primitive — just a tool call, whenever you want):
6663
6989
  receive mail — their replies wait on the board for pull (inbox/gather).
6664
6990
  --auto maps to each harness's
6665
6991
  unattended mode (dangerous); --dry-run prints the exact command without
6666
- 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.)
6667
6995
  crewbus spawn-status --to <worker> [--lines 10] [--json] | --all
6668
6996
  (is it running? did the reply land? pid liveness via kill-0 plus process
6669
6997
  start-time validation — reboot-recycled pids read dead (stale pid) instead
@@ -7682,6 +8010,7 @@ async function main() {
7682
8010
  case "install-cli": return cmdInstallCli();
7683
8011
  case "update": return cmdUpdate(rest);
7684
8012
  case "register": return cmdRegister(rest);
8013
+ case "recover": return cmdRecover(rest);
7685
8014
  case "acl": return cmdAcl(rest);
7686
8015
  case "agents": return cmdAgents(rest);
7687
8016
  case "send": return cmdSend(rest);