crewbus 10.0.7 → 10.0.9

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,14 +42,15 @@ 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, ensureSender, hashToken, isHashRevoked, mergeAgentDoc, mergeSyncedAgent, mintToken, newSalt, readAgent, readBoardAcl, resolveToken, revokedPathForHash, roleOfRecord, sanitizeAgentForSync, stripAgentSecrets, timingSafeEqualStr, touchAgent, writeAgentFile, writeBoardAcl, isBoardFrozen } from "./lib/identity.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
46
  import { saveTokenFile } 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, parseAllowEnv, pidAlive, provisionBranch, provisionWorktree, readWorkerSession, requireAutoConfirm, sandboxPresent, scrubChildEnv, syncWorkerSession, workerStatus, worktreeStamp, defaultMaxTurnsFor, ensureBoardCliShim, installCliToUserPath } from "./lib/spawn.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";
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";
53
+ import { publishArtifact, adoptArtifact, verifyArtifact, readArtifactById, listArtifacts, listLessons, postLesson, selectLessons, renderWorkbenchBlock, workbenchMetrics, cleanArtifactId, cleanLessonScope, parseArtifactDeps } from "./lib/workbench.js";
53
54
  import { appendChannelPost, channelLogPath, groupChannelName, lockAlive, lockPath, mergeChannelText, mirrorToGroupChannels, printChannelPost, readChannelPosts, readLock, summarizePosts, writeChannelCursor, SUMMARY_STOP, channelCursorPath, readChannelCursor, lockHash, acquireLockDoc, releaseLockDoc, tailChannelPosts, listLocks, parseChannelText } from "./lib/channels.js";
54
55
  import { boardSnapshot, cmdWeb, escapeHtml, fleetSnapshot, channelsSnapshot, resultsSnapshot, auditSnapshot, handleApiAck, renderBoardHtml, handleApiKill, handleApiLaunch, handleWebDashboardRoute } from "./lib/web.js";
55
56
  import { LAUNCH_DRIVER_FALLBACK, PAIR_SCOPES, advertiseEnv, buildPairUrl, detectHarnessBinaries, formatHarnessMenu, isBodyFileRef, launchDrivers, parseCountChoice, parseHarnessChoice, parsePermissionChoice, parseYesNo, probeBinary, validateLaunchPlan, HARNESS_MODELS, getDiscoveredModels, refreshDiscoveredModels } from "./lib/launch.js";
@@ -2720,6 +2721,15 @@ function cmdSend(args) {
2720
2721
  const priority = cleanPriority(getFlag(args, "--priority"));
2721
2722
  const checkpoint = args.includes("--checkpoint");
2722
2723
  const alsoChannel = args.includes("--also-channel");
2724
+ // Needs-by (L4 handoff): a deadline the sender stamps on the DM, so a
2725
+ // blocked peer can triage with inbox --overdue instead of re-polling.
2726
+ const needsByRaw = getFlag(args, "--needs-by");
2727
+ let needsBy;
2728
+ if (needsByRaw !== undefined) {
2729
+ const ms = parseDuration(needsByRaw);
2730
+ if (!(ms > 0)) fail("--needs-by must be a positive duration (e.g. 30m, 2h)");
2731
+ needsBy = new Date(Date.now() + ms).toISOString();
2732
+ }
2723
2733
  const toGroupRaw = getFlag(args, "--to-group");
2724
2734
  if (alsoChannel && (!toGroupRaw || !String(toGroupRaw).trim())) fail("--also-channel needs --to-group <g,...> (it mirrors the brief into each group's channel)");
2725
2735
  const groupNames = String(toGroupRaw || "").split(",").map((s) => String(s).trim().toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 40)).filter(Boolean);
@@ -2752,7 +2762,7 @@ function cmdSend(args) {
2752
2762
  const rev = gitRevForBoard(root);
2753
2763
  const at = new Date().toISOString();
2754
2764
  const forceBroadcast = args.includes("--broadcast");
2755
- const res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, artifact, priority, checkpoint, senderType, fwd, rev, at, forceBroadcast });
2765
+ const res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, artifact, priority, checkpoint, senderType, fwd, rev, at, forceBroadcast, needsBy });
2756
2766
  appendChainRecord(d, from, "send", { to: recipients.slice(0, 20), count: recipients.length, batch: res.batch });
2757
2767
  const mirrored = alsoChannel
2758
2768
  ? mirrorToGroupChannels(d, { groups: groupNames, from, body: body.trim(), subject, replyTo, batch: res.batch || (res.items[0] && res.items[0].id), priority, rev, at })
@@ -2921,6 +2931,24 @@ function cmdSpawn(args) {
2921
2931
  if (!(ms > 0)) fail("--timeout must be a positive duration (e.g. 10m)");
2922
2932
  deadlineAt = new Date(Date.now() + ms).toISOString();
2923
2933
  }
2934
+ // Needs-by (L4 handoff): deadline stamped on the brief DMs, so leads can
2935
+ // spot unclaimed/overdue briefs with inbox --overdue --unacked.
2936
+ const needsByRaw = getFlag(args, "--needs-by");
2937
+ let needsBy;
2938
+ if (needsByRaw !== undefined) {
2939
+ const ms = parseDuration(needsByRaw);
2940
+ if (!(ms > 0)) fail("--needs-by must be a positive duration (e.g. 30m, 2h)");
2941
+ needsBy = new Date(Date.now() + ms).toISOString();
2942
+ }
2943
+ // Workbench (L2/L3): lessons scoped to this spawn's groups (+global) and
2944
+ // the newest board artifacts, rendered once per worker so the brief
2945
+ // carries prior output instead of re-deriving it.
2946
+ const wbFor = (to) =>
2947
+ renderWorkbenchBlock({
2948
+ lessons: selectLessons(d, { scopes: groupNames, limit: 8 }),
2949
+ artifacts: listArtifacts(d, { limit: 6 }),
2950
+ me: to,
2951
+ });
2924
2952
  const isolateInfo = maybeIsolate(args, d.root);
2925
2953
  if ((worktreePrefix !== undefined || branchPrefix !== undefined) && !dry) assertGitCheckout(cwd);
2926
2954
  const minted = ensureSender(d, from, resolveToken(args));
@@ -2939,17 +2967,17 @@ function cmdSpawn(args) {
2939
2967
  const driver = harnesses[i % harnesses.length];
2940
2968
  const itemMaxTurns = maxTurnsNum !== undefined ? maxTurnsNum : ((driver === "claude" || driver === "grok") ? 50 : undefined);
2941
2969
  const itemSpawnOpts = { ...spawnOpts, harness: driver, maxTurns: itemMaxTurns, allowTools: driver === "claude" ? allowTools : undefined };
2942
- const previewPrompt = buildSpawnPrompt({ name: to, from, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(to) });
2970
+ const previewPrompt = buildSpawnPrompt({ name: to, from, subject, body: body.trim(), replyId: previewBatch || "msg-<id>", rev, cwd, root, crew: crewFor(to), workbench: wbFor(to) });
2943
2971
  const t = buildSpawnTarget({ ...itemSpawnOpts, name: to, promptPath: `<logs>/${to}-<stamp>.prompt.md`, prompt: previewPrompt });
2944
2972
  const wtNote = worktreePrefix !== undefined ? ` worktree ../${to}-<stamp> (branch ${worktreePrefix}/${to}-<stamp>)` : branchPrefix !== undefined ? ` branch ${branchPrefix}/${to}-<stamp>` : "";
2945
2973
  console.log(`would spawn ${to} [${driver}] (${lifetime}) cwd ${cwd}${wtNote} cmd: ${formatSpawnCmd(t)} [board ${d.root}]`);
2946
2974
  });
2947
- 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]) })}`);
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]) })}`);
2948
2976
  return;
2949
2977
  }
2950
2978
  // Direct (N-copy) path is forced here (every worker needs its own message
2951
2979
  // id to thread the reply against) — --broadcast is not accepted by spawn.
2952
- const res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, priority, senderType, fwd, rev, at, forceBroadcast: false, forceDirect: true });
2980
+ const res = deliverDMs(d, { from, recipients, body: body.trim(), subject, replyTo, priority, senderType, fwd, rev, at, forceBroadcast: false, forceDirect: true, needsBy });
2953
2981
  if (res.mode !== "direct") fail("spawn: internal error — expected direct delivery");
2954
2982
  appendChainRecord(d, from, "spawn", { to: recipients.slice(), harness, harnesses, auto, cwd, isolate: isolateInfo.isolated || false, budgetTokens, budgetMinutes, deadlineAt });
2955
2983
  if (alsoChannel) {
@@ -2978,7 +3006,7 @@ function cmdSpawn(args) {
2978
3006
  } else if (branchPrefix !== undefined) {
2979
3007
  workerBranch = provisionBranch(cwd, branchPrefix, to).branch;
2980
3008
  }
2981
- 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) });
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) });
2982
3010
  const where = workerWorktree ? ` worktree ${workerWorktree}` : workerBranch ? ` branch ${workerBranch}` : "";
2983
3011
  console.log(`spawned ${to} pid ${r.pid} [${driver}] (${lifetime}) log ${r.logPath} reply ${id}${where} [board ${d.root}]`);
2984
3012
  } catch (e) {
@@ -3302,6 +3330,10 @@ async function cmdRespawn(args) {
3302
3330
  const name = names[0];
3303
3331
  const force = args.includes("--force");
3304
3332
  const dry = args.includes("--dry-run");
3333
+ // --fresh: when the harness session id was never captured (opencode kills
3334
+ // its buffered output before the log scan can read it), skip the resume
3335
+ // requirement and boot the catch-up brief fresh — same as the generic path.
3336
+ const fresh = args.includes("--fresh");
3305
3337
  const extraBody = getFlag(args, "--body");
3306
3338
  if (extraBody !== undefined && String(extraBody).length > MAX_BODY_CHARS) fail(`message body too large (max ${MAX_BODY_CHARS} chars)`);
3307
3339
  const minted = ensureSender(d, from, resolveToken(args));
@@ -3317,7 +3349,7 @@ async function cmdRespawn(args) {
3317
3349
  const harness = prev.harness;
3318
3350
  if (!harness) fail(`no harness recorded for "${name}" (spawned before session capture — re-boot fresh with spawn --to ${name})`);
3319
3351
  const sessionId = prev.harnessSessionId;
3320
- if (!sessionId && harness !== "generic") fail(`no harness session id recorded for "${name}"${prev.idSource ? ` (source: ${prev.idSource})` : ""} — its conversation can't be resumed; re-brief with send --reply ${prev.briefId || "<brief-id>"} or spawn a fresh worker`);
3352
+ if (!sessionId && harness !== "generic" && !fresh) fail(`no harness session id recorded for "${name}"${prev.idSource ? ` (source: ${prev.idSource})` : ""} — its conversation can't be resumed; re-brief with send --reply ${prev.briefId || "<brief-id>"}, respawn with --fresh to reboot it without the old conversation, or spawn a fresh worker`);
3321
3353
  if ((prev.auto || false) && !args.includes("--auto")) fail(`worker "${name}" was spawned --auto (fully-unattended) — pass --auto to confirm the respawn carries the same danger (see docs/ISOLATION.md)`);
3322
3354
  if (args.includes("--auto")) requireAutoConfirm(args);
3323
3355
  if (!prev.promptPath) fail(`no original prompt on record for "${name}" (spawned before prompt capture — re-boot fresh with spawn --to ${name})`);
@@ -3501,13 +3533,136 @@ function cmdGather(args) {
3501
3533
  if (!res) fail(`unknown batch "${batch}" (check send echoes / inbox batch lines)`);
3502
3534
  const groups = contributingGroups(d, res.items);
3503
3535
  const tele = gatherTelemetry(res.items);
3536
+ // Workbench metrics: did any downstream message consume an upstream
3537
+ // artifact (feed-forward edge), and how much of it held up (adopted/
3538
+ // verified). This is the multiplicative-discovery measure — additive
3539
+ // crews score 0 across the board.
3540
+ const wb = workbenchMetrics(res.items, (id) => readArtifactById(d, id));
3504
3541
  if (json) {
3505
- console.log(JSON.stringify({ ...res, contributingGroups: groups, telemetry: tele }, null, 2));
3542
+ console.log(JSON.stringify({ ...res, contributingGroups: groups, telemetry: tele, workbench: wb }, null, 2));
3506
3543
  return;
3507
3544
  }
3508
3545
  console.log(`batch ${batch}: ${res.briefs} brief(s), ${res.replies} replies [board ${d.root}]\n`);
3509
3546
  for (const m of res.items) printMsg(m, true, false);
3510
3547
  console.log(`-- telemetry: ${tele.messages} msgs, ~${tele.tokensEst} tokens (chars/4), contributing groups: ${groups.join(",") || "none"} --`);
3548
+ if (wb.artifactRefs > 0) {
3549
+ console.log(`-- workbench: ${wb.artifactRefs} artifact(s) referenced, ${wb.feedForward} feed-forward edge(s), ${wb.adopted} adopted, ${wb.verified} verified --`);
3550
+ } else {
3551
+ console.log(`-- workbench: no artifacts referenced (additive shape; publish with: crewbus artifact publish --path <p>) --`);
3552
+ }
3553
+ }
3554
+
3555
+ // artifact: board objects for worker output that should outlive the DM
3556
+ // thread (L2). publish|list|show|adopt|verify — adoption + verification
3557
+ // land ON the object, so a later crew can see what was reused and what
3558
+ // held up instead of re-deriving it from prose.
3559
+ function cmdArtifact(args) {
3560
+ const root = boardDir(args);
3561
+ refuseDriveRootBoard(root, args);
3562
+ const d = requireBoard(root);
3563
+ const json = args.includes("--json");
3564
+ const sub = String(args[0] || "").toLowerCase();
3565
+ const rest = args.slice(1);
3566
+ const token = resolveToken(rest);
3567
+ const ensureWriter = () => {
3568
+ const from = resolveAgent(rest, "sender");
3569
+ ensureSender(d, from, token);
3570
+ authorize(d, from, "artifact-write", {});
3571
+ return from;
3572
+ };
3573
+ if (sub === "publish") {
3574
+ const from = ensureWriter();
3575
+ const deps = parseArtifactDeps(getFlag(rest, "--deps"));
3576
+ const doc = publishArtifact(d, { from, ref: getFlag(rest, "--path"), summary: getFlag(rest, "--summary"), deps, at: new Date().toISOString() });
3577
+ appendChainRecord(d, from, "artifact-publish", { id: doc.id });
3578
+ console.log(`published artifact ${doc.id} (${doc.path})${doc.deps.length ? ` deps: ${doc.deps.join(",")}` : ""} [board ${d.root}]`);
3579
+ return;
3580
+ }
3581
+ if (sub === "adopt" || sub === "verify") {
3582
+ const from = ensureWriter();
3583
+ const id = cleanArtifactId(getFlag(rest, "--id"));
3584
+ const at = new Date().toISOString();
3585
+ const note = getFlag(rest, "--note");
3586
+ const doc = sub === "adopt" ? adoptArtifact(d, { id, from, at, note }) : verifyArtifact(d, { id, from, at, note });
3587
+ appendChainRecord(d, from, sub === "adopt" ? "artifact-adopt" : "artifact-verify", { id });
3588
+ const n = sub === "adopt" ? doc.adoptedBy.length : doc.verifiedBy.length;
3589
+ console.log(`${sub === "adopt" ? "adopted" : "verified"} ${id} by ${from} (${n} total) [board ${d.root}]`);
3590
+ return;
3591
+ }
3592
+ if (sub === "show") {
3593
+ const id = cleanArtifactId(getFlag(rest, "--id"));
3594
+ const a = readArtifactById(d, id);
3595
+ if (!a) fail(`unknown artifact ${id} [board ${d.root}]`);
3596
+ if (json) {
3597
+ console.log(JSON.stringify(a, null, 2));
3598
+ return;
3599
+ }
3600
+ console.log(`artifact ${a.id}`);
3601
+ console.log(` path: ${a.path}`);
3602
+ if (a.summary) console.log(` summary: ${a.summary}`);
3603
+ console.log(` producer: ${a.from} @ ${a.at}`);
3604
+ if (a.deps.length) console.log(` deps: ${a.deps.join(", ")}`);
3605
+ console.log(` adopted by: ${a.adoptedBy.map((e) => e.by).join(", ") || "(nobody)"}`);
3606
+ console.log(` verified by: ${a.verifiedBy.map((e) => e.by).join(", ") || "(nobody)"}`);
3607
+ return;
3608
+ }
3609
+ if (sub === "list" || sub === "") {
3610
+ const all = listArtifacts(d);
3611
+ if (json) {
3612
+ console.log(JSON.stringify(all, null, 2));
3613
+ return;
3614
+ }
3615
+ if (all.length === 0) {
3616
+ console.log(`no artifacts [board ${d.root}]`);
3617
+ return;
3618
+ }
3619
+ for (const a of all) {
3620
+ const state = [];
3621
+ if (a.adoptedBy.length) state.push(`adopted x${a.adoptedBy.length}`);
3622
+ if (a.verifiedBy.length) state.push("verified");
3623
+ console.log(`${a.id} ${a.path}${state.length ? ` (${state.join(", ")})` : ""}`);
3624
+ }
3625
+ return;
3626
+ }
3627
+ fail(`unknown artifact subcommand "${sub}" (want publish|list|show|adopt|verify)`);
3628
+ }
3629
+
3630
+ // lesson: one-or-two-line learnings scoped to a group/task; post|list.
3631
+ // New spawn briefs with a matching scope (or global) auto-inject the
3632
+ // latest lessons, so a lesson learned once is paid forward (L3).
3633
+ function cmdLesson(args) {
3634
+ const root = boardDir(args);
3635
+ refuseDriveRootBoard(root, args);
3636
+ const d = requireBoard(root);
3637
+ const json = args.includes("--json");
3638
+ const sub = String(args[0] || "").toLowerCase();
3639
+ const rest = args.slice(1);
3640
+ const token = resolveToken(rest);
3641
+ if (sub === "post") {
3642
+ const from = resolveAgent(rest, "sender");
3643
+ ensureSender(d, from, token);
3644
+ authorize(d, from, "lesson-write", {});
3645
+ const doc = postLesson(d, { from, scope: getFlag(rest, "--scope"), text: getFlag(rest, "--text"), at: new Date().toISOString() });
3646
+ appendChainRecord(d, from, "lesson-post", { id: doc.id, scope: doc.scope });
3647
+ console.log(`lesson ${doc.id} [${doc.scope}] (later spawns in scope ${doc.scope} get it injected) [board ${d.root}]`);
3648
+ return;
3649
+ }
3650
+ if (sub === "list" || sub === "") {
3651
+ const scopeRaw = getFlag(args, "--scope");
3652
+ const scope = scopeRaw !== undefined ? cleanLessonScope(scopeRaw) : undefined;
3653
+ const items = listLessons(d, { scope });
3654
+ if (json) {
3655
+ console.log(JSON.stringify(items, null, 2));
3656
+ return;
3657
+ }
3658
+ if (items.length === 0) {
3659
+ console.log(`no lessons${scope ? ` scoped ${scope}` : ""} [board ${d.root}]`);
3660
+ return;
3661
+ }
3662
+ for (const l of items) console.log(`${l.id} [${l.scope}] ${l.text}`);
3663
+ return;
3664
+ }
3665
+ fail(`unknown lesson subcommand "${sub}" (want post|list)`);
3511
3666
  }
3512
3667
 
3513
3668
  function cmdInbox(args) {
@@ -3520,6 +3675,7 @@ function cmdInbox(args) {
3520
3675
  const json = args.includes("--json");
3521
3676
  let items;
3522
3677
  let showTo = false;
3678
+ let acked = null;
3523
3679
  if (showAll) {
3524
3680
  items = [];
3525
3681
  let subs = [];
@@ -3554,7 +3710,7 @@ function cmdInbox(args) {
3554
3710
  authorize(d, agent, "inbox"); // reads allow all roles (auditor read-ok)
3555
3711
  heartbeat(d, agent, 0); // reading your mail proves you're alive
3556
3712
  items = readVisible(d, agent);
3557
- const acked = ackedIds(d, agent);
3713
+ acked = ackedIds(d, agent);
3558
3714
  if (json) {
3559
3715
  items = items.map((m) => (acked.has(m.id) ? { ...m, acked: true } : m));
3560
3716
  }
@@ -3563,6 +3719,12 @@ function cmdInbox(args) {
3563
3719
  items = items.filter((m) => !acked.has(m.id) && m.checkpoint !== true);
3564
3720
  }
3565
3721
  }
3722
+ // Overdue triage (L4): messages whose --needs-by deadline passed and that
3723
+ // are still open work (not acked, not checkpoints). In --all mode there is
3724
+ // no ack state to consult — deadline alone decides.
3725
+ if (args.includes("--overdue")) {
3726
+ items = items.filter((m) => m.checkpoint !== true && (m.needsBy && !Number.isNaN(Date.parse(m.needsBy)) && Date.parse(m.needsBy) < Date.now()) && (showAll || !acked.has(m.id)));
3727
+ }
3566
3728
  if (after) {
3567
3729
  const idx = items.findIndex((m) => m.id === after);
3568
3730
  if (idx !== -1) items = items.slice(idx + 1);
@@ -4331,6 +4493,7 @@ function cmdDoctor(args) {
4331
4493
  console.log(`FAIL ${label}${hint ? ` — ${hint}` : ""}`);
4332
4494
  };
4333
4495
  const info = (label) => console.log(`info ${label}`);
4496
+ const warn = (label) => console.log(`warn ${label}`);
4334
4497
 
4335
4498
  const nodeMajor = Number(String(process.version).replace(/^v/, "").split(".")[0]);
4336
4499
  if (nodeMajor >= 18) ok(`node ${process.version} (>= 18)`);
@@ -4386,7 +4549,7 @@ function cmdDoctor(args) {
4386
4549
  for (const f of found.slice(0, 5)) info(`dead-man: ${f}`);
4387
4550
  if (found.length > 5) info(`dead-man: …and ${found.length - 5} more — see spawn-status --all`);
4388
4551
  } catch {}
4389
- if (!local) {
4552
+ if (!local) {
4390
4553
  info(`non-local board: skipping project-file checks for ${root}`);
4391
4554
  console.log(bad === 0 ? "doctor: healthy" : `doctor: ${bad} problem(s)`);
4392
4555
  if (bad > 0) process.exitCode = 1;
@@ -4424,6 +4587,41 @@ function cmdDoctor(args) {
4424
4587
  else no("opencode tool .opencode/tools/dm-send.js", "run: crewbus init --harness opencode (then restart opencode)");
4425
4588
  if (fs.existsSync(path.join(cwd, ".opencode", "plugins", "dm-watch.js"))) ok("opencode plugin .opencode/plugins/dm-watch.js");
4426
4589
  else no("opencode plugin .opencode/plugins/dm-watch.js", "run: crewbus init --harness opencode (then restart opencode)");
4590
+ // Binary + schema sanity for the respawn capture path (only when the
4591
+ // harness is actually installed): the log stream the session-id
4592
+ // capture reads (--format json events) and the storage-fallback DB.
4593
+ // --help is captured through a file descriptor, not a pipe —
4594
+ // opencode drops output onto some piped stdios (first-byte quirk).
4595
+ {
4596
+ const exe = resolveOpencodeExe();
4597
+ if (exe) {
4598
+ info(`opencode binary ${exe} (direct spawn, no shim)`);
4599
+ try {
4600
+ const helpFile = path.join(os.tmpdir(), `crewbus-oc-help-${process.pid}.txt`);
4601
+ let fd;
4602
+ try {
4603
+ fd = fs.openSync(helpFile, "w");
4604
+ execFileSync(exe, ["run", "--help"], { stdio: ["ignore", fd, fd], timeout: 15000 });
4605
+ } finally {
4606
+ try { fs.closeSync(fd); } catch {}
4607
+ }
4608
+ let h = "";
4609
+ try { h = fs.readFileSync(helpFile, "utf8"); } catch {}
4610
+ try { fs.rmSync(helpFile, { force: true }); } catch {}
4611
+ if (h.includes("--format") && /\bjson\b/.test(h)) ok("opencode run --help exposes --format json (capture flag present)");
4612
+ else no("opencode run --help flags", `--format json not offered by this opencode build — schema drift; session-id capture may not work (bin ${exe})`);
4613
+ } catch (e) {
4614
+ const detail = String((e && (e.message || e.stderr)) || e).slice(0, 120);
4615
+ no("opencode run --help", `could not run the resolved binary ${exe}: ${detail}`);
4616
+ }
4617
+ const st = opencodeStorageStatus();
4618
+ if (st.status === "ok") ok(`opencode storage DB session table readable ${st.dbPath}`);
4619
+ else if (st.status === "no-db") warn(`opencode storage DB not found (${st.dbPath}) — respawn capture limited to log scan`);
4620
+ else if (st.status === "no-sqlite") warn(`node:sqlite unavailable (needs Node >= 22) — respawn capture limited to log scan`);
4621
+ else if (st.status === "drift") no(`opencode storage DB session table ${st.dbPath}`, "schema drift — storage fallback cannot read session rows; update crewbus");
4622
+ else warn(`opencode storage DB unreadable (${st.detail || "transient lock"}) — respawn capture falls back to log scan`);
4623
+ }
4624
+ }
4427
4625
  break;
4428
4626
  case "claude": {
4429
4627
  if (hasHookRef(path.join(cwd, ".claude", "settings.json"), ["SessionStart", "Stop"])) ok("claude hooks .claude/settings.json");
@@ -4511,7 +4709,7 @@ function cmdDoctor(args) {
4511
4709
  .map((x) => x.name);
4512
4710
  if (stale.length > 0) info(`${stale.length} worker(s) with stale pids (presumed dead after reboot): ${stale.slice(0, 5).join(",")}${stale.length > 5 ? "…" : ""} — see spawn-status --all; respawn to reboot`);
4513
4711
  } catch {}
4514
- if (!process.env.CREWBUS_AGENT) info("CREWBUS_AGENT is unset — hooks need it to know who you are");
4712
+ if (!process.env.CREWBUS_AGENT) info("CREWBUS_AGENT is unset — hooks need it to know who you are");
4515
4713
  if (!process.env.CREWBUS_TOKEN) info("CREWBUS_TOKEN is unset — sends/reads as a claimed name need it");
4516
4714
  try {
4517
4715
  const legacy = fs.readdirSync(path.join(root, "agents")).filter((f) => f.endsWith(".json")).map((f) => {
@@ -4880,8 +5078,14 @@ async function cmdServe(args) {
4880
5078
  ensureBoardCliShim(d);
4881
5079
  const host = getFlag(args, "--host") || "127.0.0.1";
4882
5080
  const port = Number(getFlag(args, "--port") || 0);
4883
- if (!(port >= 0 && port < 65536)) fail("--port must be 0-65535 (0 = random)");
4884
5081
  const relaySecret = relaySecretFromArgs(args);
5082
+ // Desktop plug-and-play: loopback boots auto-provision a `lead` operator
5083
+ // identity (first boot only) so the dashboard launch UI works with zero
5084
+ // terminal steps. Relays with an explicit secret are CLI/fleet boards
5085
+ // and do not auto-provision. Non-loopback binds never auto-provision.
5086
+ if (!relaySecret) {
5087
+ try { ensureLoopbackOperator(d, host); } catch {}
5088
+ }
4885
5089
  const remote = !isLoopbackHost(host);
4886
5090
  const allowRemoteSpawn = args.includes("--allow-remote-spawn");
4887
5091
  // Phase 1b: opening remote spawn/kill is admin-gated when a caller identity
@@ -6344,7 +6548,7 @@ Identity (first claim wins, token after that):
6344
6548
  the CLI, not local file tampering — separate boards per trust zone.)
6345
6549
 
6346
6550
  Messaging (primitive — just a tool call, whenever you want):
6347
- crewbus send --from <you> --to <peer> --body "..." [--subject "..."] [--reply <msg-id>] [--artifact <path-or-url>] [--priority high|normal] [--checkpoint] [--session <id>] [--to-file <path>] [--broadcast] [--also-channel] [--sender-type human|lead|peer] [--fwd <n>] [--yes] [--no-rate-limit]
6551
+ crewbus send --from <you> --to <peer> --body "..." [--subject "..."] [--reply <msg-id>] [--artifact <path-or-url>] [--priority high|normal] [--checkpoint] [--needs-by 30m] [--session <id>] [--to-file <path>] [--broadcast] [--also-channel] [--sender-type human|lead|peer] [--fwd <n>] [--yes] [--no-rate-limit]
6348
6552
  (--to accepts a comma list for broadcast: --to alice,bob,carol — one DM
6349
6553
  each, same brief, shared batch id, up to 10000 recipients; --to-file reads
6350
6554
  the list from a file for large fan-outs; --to @all reaches every
@@ -6354,6 +6558,8 @@ Messaging (primitive — just a tool call, whenever you want):
6354
6558
  addresses named groups (same thing in spawn); unknown groups fail loudly.
6355
6559
  --priority high flags urgent mail (inbox --priority filters it).
6356
6560
  --checkpoint marks a progress note on a thread (labeled in transcripts, skipped by --unacked and spawn-status reply detection — never needs ack).
6561
+ --needs-by stamps a handoff deadline on the DM (inbox --overdue lists
6562
+ it once the deadline passes, so open work is never silently stale).
6357
6563
  --also-channel (with --to-group) also appends the brief to each group's
6358
6564
  channel, stamped with the DM batch id so gather picks it up.)
6359
6565
  crewbus channel create|post|tail|search|summarize|list <name> [--body "..."] [--from <you>] [--limit 20] [--cursor <msg-id>] [--grep <pattern>] [--priority high|normal] [--max-chars <n>] [--digest] [--json]
@@ -6396,13 +6602,29 @@ Messaging (primitive — just a tool call, whenever you want):
6396
6602
  crewbus gather --batch <batch-id> [--json]
6397
6603
  (the reduce step: the brief(s) plus every reply, across inboxes, oldest
6398
6604
  first — one transcript to aggregate, summarize, or feed a reducer agent.
6399
- Footer shows telemetry + contributing groups; attribution is reply→batch→groups.
6605
+ Footer shows telemetry + contributing groups, plus workbench metrics
6606
+ (artifacts referenced, feed-forward edges, adopted/verified counts) —
6607
+ additive crews score 0, feed-forward crews score >0.
6400
6608
  Group-channel mirrors (send --also-channel) carrying the batch join as briefs.)
6401
- crewbus inbox --from <you> [--limit 20] [--after <msg-id>] [--all] [--unacked] [--older-than 10m] [--grep <pattern>] [--priority high|normal] [--max-chars <n>] [--digest] [--verify] [--json]
6609
+ crewbus artifact publish|list|show|adopt|verify [--path <path-or-url>] [--summary "..."] [--deps <id,id>] [--id <artifact-id>] [--note "..."] [--from <you>] [--json]
6610
+ (board objects for worker output that should outlive the DM thread:
6611
+ publish a path/url + one-line summary, chain pieces with --deps,
6612
+ adopt when you reuse one, verify when you checked it holds up.
6613
+ adoption/verification record ON the object; later spawn briefs list
6614
+ the newest artifacts, so prior output compounds instead of being
6615
+ re-derived. publish/adopt/verify need your token; reads are open.)
6616
+ crewbus lesson post|list [--scope <group-or-task>] [--text "..."] [--from <you>] [--json]
6617
+ (scoped one-or-two-line learnings: what happened + what to do
6618
+ differently. Later spawn briefs whose groups (or --scope-less/global)
6619
+ match auto-inject the latest lessons, so a lesson learned once is
6620
+ 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]
6402
6622
  (--older-than keeps only messages older than the window: inbox --unacked
6403
6623
  --older-than 10m lists briefs nobody picked up (retry via redeliver or
6404
- re-send). --grep filters subject+body, --priority filters urgency,
6405
- --max-chars fair-share truncates bodies with [truncated], --digest prints
6624
+ re-send). --overdue lists still-open briefs whose --needs-by deadline
6625
+ passed (skip in --all mode where ack state doesn't apply). --grep
6626
+ filters subject+body, --priority filters urgency, --max-chars
6627
+ fair-share truncates bodies with [truncated], --digest prints
6406
6628
  one line per message.)
6407
6629
  crewbus ack --from <you> (--id <msg-id> | --all) [--verify "<command>"] [--timeout <dur>]
6408
6630
  ("handled it" — orthogonal to delivery; leads ack workers' replies;
@@ -6421,7 +6643,7 @@ Messaging (primitive — just a tool call, whenever you want):
6421
6643
  (recover mail a dead watcher consumed: clears delivered markers and
6422
6644
  rewinds the cursor so the next poll/push treats it as fresh;
6423
6645
  use after re-registering with the live session)
6424
- crewbus spawn --from <you> (--to <workers> | --count <n> [--prefix <p>]) --body "..." [--subject "..."] [--priority high|normal] [--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]
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]
6425
6647
  (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.)
6426
6648
  (brief N workers AND boot them detached: the DM lands first so the brief
6427
6649
  waits even if a launch fails. opencode: \`run\` + brief via --file;
@@ -6429,6 +6651,9 @@ Messaging (primitive — just a tool call, whenever you want):
6429
6651
  file; grok: headless via --prompt-file; antigravity: \`--print\` with the
6430
6652
  brief inline; cursor: headless via \`-p --force --trust\` pointing at the
6431
6653
  brief file; generic: --cmd with CREWBUS_DIR + CREWBUS_AGENT set.
6654
+ Briefs auto-inject the latest scoped lessons + newest board artifacts
6655
+ (the Workbench block) so prior output compounds; --needs-by stamps a
6656
+ handoff deadline on the brief DMs.
6432
6657
  Logs to .crewbus/logs/<name>.log, pid recorded on the agent. Caps at
6433
6658
  20/call by default (--max-spawn overrides, needs the compute) — bigger
6434
6659
  crews get a broadcast DM. --worktree is recommended for write tasks (one
@@ -6448,13 +6673,16 @@ Messaging (primitive — just a tool call, whenever you want):
6448
6673
  crewbus spawn-kill --from <you> (--to <worker,...> | --all)
6449
6674
  (the kill switch: closing the terminal does NOT stop detached workers.
6450
6675
  Terminates by recorded pid, confirms death, reports. Needs your token.)
6451
- crewbus respawn --from <you> --to <worker> [--body "..."] [--force] [--cwd <dir>] [--cmd "..."] [--keep-env] [--allow-env ...] [--dry-run]
6676
+ crewbus respawn --from <you> --to <worker> [--body "..."] [--force] [--fresh] [--cwd <dir>] [--cmd "..."] [--keep-env] [--allow-env ...] [--dry-run]
6452
6677
  (reboot one DEAD worker in its SAME harness conversation: needs the
6453
- captured session id (spawn-status shows it; generic re-boots fresh).
6454
- Refuses live workers unless --force (kills first, own crew only).
6455
- The catch-up brief points at the original prompt file and threads the
6456
- same reply id; --body appends lead instructions. Attempt counted on
6457
- the worker-session record. Lead/admin only.)
6678
+ captured session id (spawn-status shows it; generic re-boots fresh).
6679
+ --fresh skips the resume requirement when the id can't be captured
6680
+ (e.g. an opencode worker died before its log revealed anything) and
6681
+ re-boots the catch-up brief as a fresh session.
6682
+ Refuses live workers unless --force (kills first, own crew only).
6683
+ The catch-up brief points at the original prompt file and threads the
6684
+ same reply id; --body appends lead instructions. Attempt counted on
6685
+ the worker-session record. Lead/admin only.)
6458
6686
  crewbus stop --all --from <you>
6459
6687
  (global stop: kills every spawned worker truly (whole process tree).)
6460
6688
  crewbus token rotate --from <you> [--expires-in <dur>]
@@ -7097,14 +7325,15 @@ async function cmdPool(args) {
7097
7325
  state.active[name] = r.pid;
7098
7326
  state.launched++;
7099
7327
  state.results.push({ to: name, id: idByName.get(name), pid: r.pid, log: r.logPath, promptPath: r.promptPath });
7328
+ saveState();
7100
7329
  console.log(`pool ${poolId}: spawned ${name} pid ${r.pid} [board ${d.root}]`);
7101
7330
  } catch (e) {
7102
7331
  delete state.active[name];
7103
7332
  state.done++;
7104
7333
  state.results.push({ to: name, id: idByName.get(name), error: (e && e.message) || String(e) });
7334
+ saveState();
7105
7335
  console.log(`pool ${poolId}: spawn FAILED ${name}: ${(e && e.message) || e} (brief still waits on the board)`);
7106
7336
  }
7107
- saveState();
7108
7337
  };
7109
7338
  const initial = Math.min(poolSize, queue.length);
7110
7339
  for (; state.cursor < initial; state.cursor++) launchOne(queue[state.cursor]);
@@ -7215,14 +7444,15 @@ async function cmdPoolResume(args) {
7215
7444
  state.active[name] = r.pid;
7216
7445
  state.launched++;
7217
7446
  state.results.push({ to: name, id: state.idByName[name], pid: r.pid, log: r.logPath, promptPath: r.promptPath, resumed: true });
7447
+ saveState();
7218
7448
  console.log(`pool ${state.id}: spawned ${name} pid ${r.pid} [board ${d.root}]`);
7219
7449
  } catch (e) {
7220
7450
  delete state.active[name];
7221
7451
  state.done++;
7222
7452
  state.results.push({ to: name, id: state.idByName[name], error: (e && e.message) || String(e) });
7453
+ saveState();
7223
7454
  console.log(`pool ${state.id}: spawn FAILED ${name}: ${(e && e.message) || e} (brief still waits on the board)`);
7224
7455
  }
7225
- saveState();
7226
7456
  };
7227
7457
  const finish = (completed) => {
7228
7458
  if (completed) state.finishedAt = new Date().toISOString();
@@ -7456,6 +7686,8 @@ async function main() {
7456
7686
  case "agents": return cmdAgents(rest);
7457
7687
  case "send": return cmdSend(rest);
7458
7688
  case "channel": return cmdChannel(rest);
7689
+ case "artifact": return cmdArtifact(rest);
7690
+ case "lesson": return cmdLesson(rest);
7459
7691
  case "lock": return cmdLock(rest);
7460
7692
  case "group": return cmdGroup(rest);
7461
7693
  case "gather": return cmdGather(rest);
@@ -330,7 +330,7 @@ export function authorizeCheck(d, agent, action, scope) { // line 537
330
330
  const act = String(action || "");
331
331
  const ADMIN_ONLY = new Set(["prune", "acl-set", "role-grant", "offboard", "group-restrict", "serve-remote", "import", "snapshot-schedule", "quota-set", "hold-place", "hold-lift", "pairing"]);
332
332
  const LEAD_PLUS = new Set(["spawn", "respawn", "pool", "group-manage", "channel-post", "result-record", "race-close"]);
333
- const WORKER_WRITES = new Set(["send", "ack", "redeliver", "lock"]);
333
+ const WORKER_WRITES = new Set(["send", "ack", "redeliver", "lock", "artifact-write", "lesson-write"]);
334
334
  const EXPORT_ROLES = new Set(["admin", "auditor"]);
335
335
  if (act === "export") {
336
336
  if (!EXPORT_ROLES.has(role)) return { ok: false, reason: `role "${role}" cannot export (need admin|auditor)` };
@@ -404,6 +404,61 @@ export function mergeAgentDoc(prev, patch) {
404
404
  return base;
405
405
  }
406
406
 
407
+ // Loopback operator auto-provision (desktop plug-and-play):
408
+ // `serve`/`web` on 127.0.0.1 auto-creates a `lead` identity on first boot so
409
+ // the dashboard can launch without any terminal step. First agent on the
410
+ // board becomes admin (see defaultRoleForNew), so this is the board owner.
411
+ // CLI boards are untouched: this only fires when `lead` is missing AND the
412
+ // bind is loopback. Returns { from, token } or null when not applicable.
413
+ export function ensureLoopbackOperator(d, host) {
414
+ const loop = String(host || "127.0.0.1");
415
+ if (loop !== "127.0.0.1" && loop !== "localhost" && loop !== "::1") return null;
416
+ let rec = null;
417
+ try { rec = readAgent(d, "lead"); } catch { rec = null; }
418
+ if (rec && (rec.tokenHash || rec.token)) return null; // already provisioned
419
+ if (countAgentRecords(d) > 0) return null; // board already has registered agents
420
+ const fresh = mintToken();
421
+ const salt = newSalt();
422
+ const now = new Date().toISOString();
423
+ let prev = null;
424
+ try { prev = readJson(path.join(d.agents, "lead.json")); } catch { prev = null; }
425
+ const { v, hlc } = stampSyncDoc(prev);
426
+ const doc = mergeAgentDoc(prev, {
427
+ name: "lead",
428
+ firstSeen: (prev && prev.firstSeen) || now,
429
+ lastSeen: now,
430
+ tokenHash: hashToken(fresh, salt),
431
+ salt,
432
+ revokedAt: undefined,
433
+ offboarded: undefined,
434
+ role: "admin",
435
+ v, hlc,
436
+ });
437
+ // Atomic first-claim: exactly one boot may win. Losers re-read below.
438
+ let won = false;
439
+ try {
440
+ if (!prev) {
441
+ won = writeExclusiveJson(path.join(d.agents, "lead.json"), doc);
442
+ } else {
443
+ writeAgentFile(d, "lead", doc);
444
+ won = true;
445
+ }
446
+ } catch { won = false; }
447
+ if (!won && !prev) {
448
+ // Lost the race (parallel boot): read the winner, no token to return.
449
+ return null;
450
+ }
451
+ if (won) {
452
+ try { chmodAgentFile(path.join(d.agents, "lead.json")); } catch {}
453
+ try {
454
+ fs.mkdirSync(path.join(d.root, "logs"), { recursive: true });
455
+ fs.writeFileSync(path.join(d.root, "logs", "lead.token"), fresh + "\n", "utf8");
456
+ try { fs.chmodSync(path.join(d.root, "logs", "lead.token"), 0o600); } catch {}
457
+ } catch {}
458
+ }
459
+ return won ? { from: "lead", token: fresh } : null;
460
+ }
461
+
407
462
  export function touchAgent(d, name, extra) { // line 2647
408
463
  const p = path.join(d.agents, `${name}.json`);
409
464
  const now = new Date().toISOString();
package/bin/lib/mail.js CHANGED
@@ -69,7 +69,7 @@ export function findMessageById(d, id) {
69
69
  return null;
70
70
  }
71
71
 
72
- export function deliverDMs(d, { from, recipients, body, subject, replyTo, artifact, priority, checkpoint, senderType, fwd, rev, at, forceBroadcast, forceDirect }) {
72
+ export function deliverDMs(d, { from, recipients, body, subject, replyTo, artifact, priority, checkpoint, senderType, fwd, rev, at, forceBroadcast, forceDirect, needsBy }) {
73
73
  const isAll = recipients.length === 1 && recipients[0] === "@all";
74
74
  // Large fan-outs (> BROADCAST_AFTER) and @all go to ONE broadcast file;
75
75
  // small fan-outs keep one copy per recipient (unique id each, shared batch).
@@ -84,6 +84,7 @@ export function deliverDMs(d, { from, recipients, body, subject, replyTo, artifa
84
84
  if (checkpoint === true) msg.checkpoint = true;
85
85
  if (senderType) msg.senderType = senderType;
86
86
  if (typeof fwd === "number") msg.fwd = fwd;
87
+ if (needsBy) msg.needsBy = needsBy;
87
88
  if (rev) msg.rev = rev;
88
89
  const sig = signMessage({ ...msg, to: msg.to });
89
90
  if (sig) msg.sig = sig;
@@ -106,6 +107,7 @@ export function deliverDMs(d, { from, recipients, body, subject, replyTo, artifa
106
107
  if (checkpoint === true) msg.checkpoint = true;
107
108
  if (senderType) msg.senderType = senderType;
108
109
  if (typeof fwd === "number") msg.fwd = fwd;
110
+ if (needsBy) msg.needsBy = needsBy;
109
111
  if (batch) msg.batch = batch;
110
112
  if (rev) msg.rev = rev;
111
113
  const sig = signMessage(msg);
@@ -293,6 +295,7 @@ export function printMsg(m, showTo, json) {
293
295
  console.log(` ${untrustedEnvelope(m.from, m.senderType || "peer")}`);
294
296
  if (m.subject) console.log(` subj: ${m.subject}`);
295
297
  if (m.artifact) console.log(` artifact: ${m.artifact}`);
298
+ if (m.needsBy) console.log(` needs-by: ${m.needsBy}${isOverdue(m) ? " (OVERDUE)" : ""}`);
296
299
  if (isHigh(m)) console.log(` priority: high`);
297
300
  if (isCheckpoint(m)) console.log(` checkpoint: progress (not a final summary)`);
298
301
  if (typeof m.fwd === "number") console.log(` fwd: ${m.fwd}/${MAX_FWD_DEPTH}`);
@@ -330,6 +333,15 @@ export function isHigh(m) {
330
333
  return m && String(m.priority || "").toLowerCase() === "high";
331
334
  }
332
335
 
336
+ // Needs-by deadline (L4 handoff): present on messages the sender stamped
337
+ // with --needs-by; overdue once the timestamp passes. Read-only helpers,
338
+ // shared by printMsg / printDigest / inbox --overdue.
339
+ export function isOverdue(m) {
340
+ if (!m || !m.needsBy) return false;
341
+ const t = Date.parse(m.needsBy);
342
+ return !Number.isNaN(t) && t < Date.now();
343
+ }
344
+
333
345
  // Progress checkpoints ride the DM thread (replyTo the brief) but are not
334
346
  // work awaiting acceptance: triage views (--unacked, ack timeout hints,
335
347
  // spawn-status reply detection) skip them; transcripts show them labeled.
@@ -372,7 +384,7 @@ export function enforceMaxChars(items, maxChars) {
372
384
  export function printDigest(items) {
373
385
  for (const m of items) {
374
386
  const head = String(m.body || "").split("\n")[0].slice(0, 140);
375
- console.log(`${m.id} [peer:${m.from}]${isHigh(m) ? " [!HIGH]" : ""}${isCheckpoint(m) ? " [checkpoint]" : ""}${m.subject ? ` subj:${String(m.subject).slice(0, 80)}` : ""} :: ${head}`);
387
+ console.log(`${m.id} [peer:${m.from}]${isHigh(m) ? " [!HIGH]" : ""}${isCheckpoint(m) ? " [checkpoint]" : ""}${isOverdue(m) ? " [OVERDUE]" : m.needsBy ? " [needs-by]" : ""}${m.subject ? ` subj:${String(m.subject).slice(0, 80)}` : ""}${m.needsBy ? ` by:${String(m.needsBy).slice(0, 16)}` : ""} :: ${head}`);
376
388
  }
377
389
  }
378
390