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/lib/web.js CHANGED
@@ -19,7 +19,7 @@ import { fileURLToPath } from "node:url";
19
19
  import { boardDir, requireBoard, getFlag, fail, writeJson, listJson, cleanWebName, readJson, readBoardMeta, writeBoardMeta, gitRevForBoard, newId, MAX_SPAWN, MAX_BODY_CHARS } from "./store.js";
20
20
  import { readAgent, agentTokenMatches, authorizeCheck, ensureLoopbackOperator, mintToken, newSalt, hashToken, touchAgent } from "./identity.js";
21
21
  import { readDMs, readVisible, ackedIds, ackedIdSet, findMessageById, deliverDMs, parseRecipients } from "./mail.js";
22
- import { workerStatus, pidAlive, killWorkers, bootWorker, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, installCliToUserPath, ensureBoardCliShim } from "./spawn.js";
22
+ import { workerStatus, pidAlive, killWorkers, bootWorker, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, installCliToUserPath, ensureBoardCliShim, buildCoordinatorPrompt, provisionAutoLead, LEAD_NAME, isPidStale } from "./spawn.js";
23
23
  import { groupTelemetryData, collectBatch, gatherTelemetry, listBatches } from "./groups.js";
24
24
  import { httpJson } from "./sync.js";
25
25
  import { readChainRecords, verifyChainRecords, appendChainRecord, readHold, readBoardQuotas } from "./export.js";
@@ -261,7 +261,8 @@ export function resultsSnapshot(d) {
261
261
  const a = e && e.data;
262
262
  if (a && a.name && typeof a.spawnedPid === "number") {
263
263
  try {
264
- aliveByName[a.name] = pidAlive(a.spawnedPid);
264
+ // Stale-pid guard (C2): pid-recycled records read dead.
265
+ aliveByName[a.name] = pidAlive(a.spawnedPid) && !isPidStale(a.spawnedPid, a.spawnedAt);
265
266
  } catch {
266
267
  aliveByName[a.name] = false;
267
268
  }
@@ -782,7 +783,12 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
782
783
  <button type="button" data-perm="auto">auto</button>
783
784
  <button type="button" data-perm="full">full</button>
784
785
  </span>
785
- <label class="dim" style="cursor:pointer"><input id="launch-dry" type="checkbox" checked> Dry-run</label>
786
+ <span class="dim" style="margin-left:8px">Coordinator:</span>
787
+ <select id="launch-lead" style="background:var(--panel);color:var(--ink);border:1px solid var(--line);border-radius:4px;padding:3px 8px;font-size:12px" title="Observer coordinator lane: auto provisions a persistent background coordinator (lead) to triage workers and report to you">
788
+ <option value="auto">auto (Observer coordinator)</option>
789
+ <option value="none">none (direct to me)</option>
790
+ </select>
791
+ <label class="dim" style="cursor:pointer;margin-left:6px"><input id="launch-dry" type="checkbox" checked> Dry-run</label>
786
792
  </div>
787
793
 
788
794
  <div class="composer-cwd-row" style="display:flex;align-items:center;gap:6px;margin-bottom:8px;font-size:12px">
@@ -801,7 +807,7 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
801
807
 
802
808
  <div class="composer-bottom">
803
809
  <div class="launch-identity" title="Desktop launches as the board owner (auto-provisioned) — no token step needed">
804
- <span class="dim">launching as <b id="launch-as">lead</b> (auto)</span>
810
+ <span class="dim">launching as <b id="launch-as">boss</b> (auto)</span>
805
811
  <input id="launch-from" type="hidden" value="">
806
812
  <input id="launch-token" type="password" style="display:none" value="">
807
813
  </div>
@@ -1152,7 +1158,8 @@ async function refresh(){
1152
1158
  }).join('')||'<tr><td colspan="7" class="dim">no spawned workers</td></tr>';
1153
1159
  Array.prototype.forEach.call(document.querySelectorAll('[data-kill]'),function(b){b.onclick=function(){kill([b.getAttribute('data-kill')]);};});
1154
1160
  document.getElementById('agents').innerHTML=s.agents.map(function(a){
1155
- return '<tr><td><b>'+esc(a.name)+'</b></td><td>'+(a.active?DOT_SVG+' active':RING_SVG+' stale')+'</td><td title="'+esc(a.lastSeen||'?')+'">'+esc(ago(a.lastSeen))+'</td><td>'+esc(a.sessionId||'—')+'</td><td>'+a.dmCount+'</td><td>'+a.unacked+'</td></tr>';
1161
+ var roleBadge = a.role ? ' <span class="dim" style="font-size:11px">['+esc(a.role)+']</span>' : '';
1162
+ return '<tr><td><b>'+esc(a.name)+'</b>'+roleBadge+'</td><td>'+(a.active?DOT_SVG+' active':RING_SVG+' stale')+'</td><td title="'+esc(a.lastSeen||'?')+'">'+esc(ago(a.lastSeen))+'</td><td>'+esc(a.sessionId||'—')+'</td><td>'+a.dmCount+'</td><td>'+a.unacked+'</td></tr>';
1156
1163
  }).join('')||'<tr><td colspan="6" class="dim">no agents yet</td></tr>';
1157
1164
  document.getElementById('bcast').innerHTML=s.broadcasts.map(function(b){
1158
1165
  var to=Array.isArray(b.to)?b.to.join(','):String(b.to||'');
@@ -1204,8 +1211,22 @@ async function refresh(){
1204
1211
  return '<tr><td>'+esc(m.id)+'</td><td>'+esc(m.from)+'</td><td>'+(m.subject?'<b>'+esc(m.subject)+'</b><br>':'')+esc(m.head)+'</td><td><button data-ack="'+esc(m.id)+'">ack</button></td></tr>';
1205
1212
  }).join('')||'<tr><td colspan="4" class="dim">inbox zero for '+esc(c.from)+'</td></tr>';
1206
1213
  var ap=(tj.items||[]).filter(function(m){return m.subject&&m.subject.indexOf('approval: ')===0;});
1214
+ if(c.from!=='lead'){
1215
+ try{
1216
+ var lr=await fetch('/api/inbox?agent=lead&unacked=1&limit=50',{cache:'no-store'});
1217
+ if(lr.ok){
1218
+ var lj=await lr.json();
1219
+ var lap=(lj.items||[]).filter(function(m){return m.subject&&m.subject.indexOf('approval: ')===0;});
1220
+ for(var k=0;k<lap.length;k++){
1221
+ lap[k]._forLead=true;
1222
+ if(!ap.some(function(x){return x.id===lap[k].id;})) ap.push(lap[k]);
1223
+ }
1224
+ }
1225
+ }catch(_){}
1226
+ }
1207
1227
  document.getElementById('approvals').innerHTML=ap.map(function(m){
1208
- return '<tr><td>'+esc(m.id)+'</td><td>'+esc(m.from)+'</td><td>'+(m.subject?'<b>'+esc(m.subject)+'</b><br>':'')+esc(m.head)+'</td><td><input data-reason="'+esc(m.id)+'" maxlength="500" size="18" placeholder="optional reason"></td><td><button data-approve="'+esc(m.id)+'">approve</button> <button class="danger" data-deny="'+esc(m.id)+'">deny</button></td></tr>';
1228
+ var tag=m._forLead?' <span class="badge" style="font-size:10px;background:var(--panel);border:1px solid var(--line);padding:1px 4px;border-radius:3px">to lead</span>':'';
1229
+ return '<tr><td>'+esc(m.id)+tag+'</td><td>'+esc(m.from)+'</td><td>'+(m.subject?'<b>'+esc(m.subject)+'</b><br>':'')+esc(m.head)+'</td><td><input data-reason="'+esc(m.id)+'" maxlength="500" size="18" placeholder="optional reason"></td><td><button data-approve="'+esc(m.id)+'">approve</button> <button class="danger" data-deny="'+esc(m.id)+'">deny</button></td></tr>';
1209
1230
  }).join('')||'<tr><td colspan="5" class="dim">no approval requests for '+esc(c.from)+'</td></tr>';
1210
1231
  }else{
1211
1232
  document.getElementById('triage').innerHTML='<tr><td colspan="4" class="dim">set identity above to triage</td></tr>';
@@ -1466,12 +1487,15 @@ async function doLaunch(dry){
1466
1487
  }
1467
1488
  var cwdEl=document.getElementById('launch-cwd');
1468
1489
  var cwdVal=cwdEl?cwdEl.value.trim():'';
1490
+ var leadEl=document.getElementById('launch-lead');
1491
+ var leadVal=leadEl?leadEl.value.trim():'auto';
1469
1492
  var payload={
1470
1493
  from:lf, token:lt,
1471
1494
  harness:selectedHarnesses.join(','),
1472
1495
  harnesses:selectedHarnesses,
1473
1496
  body:document.getElementById('launch-brief').value,
1474
1497
  permission:document.getElementById('launch-permission').value,
1498
+ lead:leadVal,
1475
1499
  dryRun:dry
1476
1500
  };
1477
1501
  if(cwdVal){
@@ -1488,11 +1512,22 @@ async function doLaunch(dry){
1488
1512
  if(j.dryRun){
1489
1513
  var warn=(j.warnings||[]).length?('warnings: '+j.warnings.join('; ')+'\\n'):'';
1490
1514
  var cwdNotice=j.cwd?('target directory (cwd): '+j.cwd+'\\n'):'';
1491
- try{renderLaunchDiff(j);}catch(_){}out.textContent=warn+cwdNotice+(j.commands||[]).map(function(c){return c.to+' ['+(c.harness||'')+']: '+c.command;}).join('\\n')+'\\n(dry-run — booted nothing)';
1515
+ var coordNotice=j.coordinator?('\\ncoordinator ('+j.coordinator.name+'): '+(j.coordinator.action==='reused'?('reused standing pid '+j.coordinator.pid):(j.coordinator.action==='minted'?'would auto-provision':'skipped ('+(j.coordinator.reason||'')+')'))):'';
1516
+ try{renderLaunchDiff(j);}catch(_){}out.textContent=warn+cwdNotice+(j.commands||[]).map(function(c){return c.to+' ['+(c.harness||'')+']: '+c.command;}).join('\\n')+coordNotice+'\\n(dry-run — booted nothing)';
1492
1517
  }else{
1493
1518
  try{showUndoToast((j.workers||[]).map(function(w){return w.name;}));}catch(_){}
1494
1519
  var cwdNotice=j.cwd?(' [cwd: '+j.cwd+']'):'';
1495
- out.textContent='launched: '+(j.workers||[]).map(function(w){return w.name+' ['+(w.driver||'')+']'+(w.pid?(' (pid '+w.pid+')'):'')+(w.error?(' ERROR '+w.error):'');}).join(', ')+cwdNotice;
1520
+ var coordNotice='';
1521
+ if(j.coordinator){
1522
+ if(j.coordinator.action==='minted'&&j.coordinator.pid){
1523
+ coordNotice=' · coordinator: lead (pid '+j.coordinator.pid+')';
1524
+ }else if(j.coordinator.action==='reused'){
1525
+ coordNotice=' · coordinator: lead (reused'+(j.coordinator.pid?' pid '+j.coordinator.pid:'')+')';
1526
+ }else if(j.coordinator.reason){
1527
+ coordNotice=' · coordinator: skipped ('+j.coordinator.reason+')';
1528
+ }
1529
+ }
1530
+ out.textContent='launched: '+(j.workers||[]).map(function(w){return w.name+' ['+(w.driver||'')+']'+(w.pid?(' (pid '+w.pid+')'):'')+(w.error?(' ERROR '+w.error):'');}).join(', ')+coordNotice+cwdNotice;
1496
1531
  }
1497
1532
  }catch(e){out.textContent='launch failed: '+e.message;}
1498
1533
  refresh();
@@ -2220,23 +2255,25 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2220
2255
  res.end(JSON.stringify({ error: "loopback only" }));
2221
2256
  return true;
2222
2257
  }
2223
- const tokenFile = path.join(d.root, "logs", "lead.token");
2224
- let tok = "";
2225
- try { tok = fs.readFileSync(tokenFile, "utf8").trim(); } catch {}
2226
- // Verify the file token still matches the agent record: a stale file
2227
- // (revoked/rotated lead) must not prefill a dead token.
2228
- if (tok) {
2229
- try {
2230
- const rec = readAgent(d, "lead");
2231
- if (rec && agentTokenMatches(rec, tok)) {
2232
- res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2233
- res.end(JSON.stringify({ ok: true, from: "lead", token: tok }));
2234
- return true;
2235
- }
2236
- } catch {}
2258
+ for (const name of ["boss", "lead"]) {
2259
+ const tokenFile = path.join(d.root, "logs", `${name}.token`);
2260
+ let tok = "";
2261
+ try { tok = fs.readFileSync(tokenFile, "utf8").trim(); } catch {}
2262
+ // Verify the file token still matches the agent record: a stale file
2263
+ // (revoked/rotated operator) must not prefill a dead token.
2264
+ if (tok) {
2265
+ try {
2266
+ const rec = readAgent(d, name);
2267
+ if (rec && agentTokenMatches(rec, tok)) {
2268
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2269
+ res.end(JSON.stringify({ ok: true, from: name, token: tok }));
2270
+ return true;
2271
+ }
2272
+ } catch {}
2273
+ }
2237
2274
  }
2238
2275
  res.writeHead(404, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2239
- res.end(JSON.stringify({ ok: false, error: "no lead.token found" }));
2276
+ res.end(JSON.stringify({ ok: false, error: "no operator token found" }));
2240
2277
  return true;
2241
2278
  }
2242
2279
  // Workspace memory (server-side, survives the random-port origin wipe):
@@ -2525,6 +2562,15 @@ export async function handleApiLaunch(d, body) {
2525
2562
  if (!v.ok) return { status: 400, payload: { error: "launch plan invalid", errors: v.errors, warnings: v.warnings } };
2526
2563
  const p = v.plan;
2527
2564
  const harnesses = Array.isArray(p.harnesses) && p.harnesses.length > 0 ? p.harnesses : [p.harness || "opencode"];
2565
+ const hasCodingHarness = harnesses.some((h) => h !== "generic");
2566
+ let leadMode = p.lead || "auto";
2567
+ if (leadMode === "auto") {
2568
+ leadMode = hasCodingHarness ? "board" : "none";
2569
+ }
2570
+ if (leadMode === "board" && !hasCodingHarness) {
2571
+ return { status: 400, payload: { error: 'lead "board" needs a coding harness for the auto-coordinator (add a harness like opencode, or use lead "none")' } };
2572
+ }
2573
+ const leadTarget = leadMode === "board" ? LEAD_NAME : from;
2528
2574
  const names = p.to ? String(p.to).split(",").map((s) => cleanWebName(s)).filter(Boolean)
2529
2575
  : Array.from({ length: p.count }, (_, i) => `${cleanWebName(p.prefix || "w") || "w"}-${i + 1}`);
2530
2576
  if (names.length === 0) return { status: 400, payload: { error: "no worker names (pass to or count)" } };
@@ -2537,9 +2583,10 @@ export async function handleApiLaunch(d, body) {
2537
2583
  return { status: 400, payload: { error: 'generic harness needs cmd "..."' } };
2538
2584
  }
2539
2585
  if (v.plan.dryRun) {
2586
+ const previewBatch = names.length > 1 ? newId("batch") : undefined;
2540
2587
  const rows = names.map((to, i) => {
2541
2588
  const driver = harnesses[i % harnesses.length];
2542
- const previewPrompt = buildSpawnPrompt({ name: to, from, subject: p.subject, body: p.body.trim(), replyId: "msg-<id>", rev, cwd, root: d.root });
2589
+ const previewPrompt = buildSpawnPrompt({ name: to, from, lead: leadTarget, subject: p.subject, body: p.body.trim(), replyId: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", rev, cwd, root: d.root });
2543
2590
  const t = buildSpawnTarget({
2544
2591
  harness: driver, cmd: body && body.cmd ? String(body.cmd) : undefined, model: p.model,
2545
2592
  auto: p.permission === "auto" || p.permission === "full" ? true : undefined,
@@ -2548,7 +2595,30 @@ export async function handleApiLaunch(d, body) {
2548
2595
  });
2549
2596
  return { to, harness: driver, command: formatSpawnCmd(t) };
2550
2597
  });
2551
- return { status: 200, payload: { ok: true, dryRun: true, plan: p, cwd, warnings: v.warnings, commands: rows } };
2598
+ let coordinator = undefined;
2599
+ if (leadMode === "board") {
2600
+ const existingLead = readAgent(d, LEAD_NAME);
2601
+ // Stale-pid guard (C2): reuse only a live, non-stale coordinator; a
2602
+ // pid-recycled after reboot record gets the fresh-provision branch.
2603
+ const standing = existingLead && typeof existingLead.spawnedPid === "number" && pidAlive(existingLead.spawnedPid) && !isPidStale(existingLead.spawnedPid, existingLead.spawnedAt);
2604
+ if (standing) {
2605
+ coordinator = { name: LEAD_NAME, action: "reused", pid: existingLead.spawnedPid, note: "live coordinator already running" };
2606
+ } else if (existingLead && existingLead.offboarded) {
2607
+ coordinator = { name: LEAD_NAME, action: "skipped", reason: "lane is offboarded" };
2608
+ } else {
2609
+ const coordDriver = harnesses.find((h) => h !== "generic") || "opencode";
2610
+ const previewCoordPrompt = buildCoordinatorPrompt({
2611
+ name: LEAD_NAME, from, subject: p.subject, body: p.body.trim(), batch: previewBatch,
2612
+ workers: names.map((name, i) => ({ name, id: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", harness: harnesses[i % harnesses.length] })),
2613
+ cwd, root: d.root, auto: p.permission === "auto" || p.permission === "full",
2614
+ });
2615
+ coordinator = {
2616
+ name: LEAD_NAME, action: "minted", harness: coordDriver, wouldProvision: true,
2617
+ promptPreview: previewCoordPrompt.slice(0, 400),
2618
+ };
2619
+ }
2620
+ }
2621
+ return { status: 200, payload: { ok: true, dryRun: true, plan: p, cwd, warnings: v.warnings, commands: rows, coordinator } };
2552
2622
  }
2553
2623
  const auto = p.permission === "auto" || p.permission === "full" ? true : undefined;
2554
2624
  const at = new Date().toISOString();
@@ -2567,11 +2637,26 @@ export async function handleApiLaunch(d, body) {
2567
2637
  const driver = harnesses[i % harnesses.length];
2568
2638
  const spawnOpts = { harness: driver, cmd: body && body.cmd ? String(body.cmd) : undefined, model: p.model, auto, maxTurns: p.maxTurns, allowTools: p.allowTools, cwd, root: d.root, prompt: null };
2569
2639
  try {
2570
- const r = bootWorker(d, spawnOpts, { to, id, from, subject: p.subject, body: p.body.trim(), rev, logDir });
2640
+ const r = bootWorker(d, spawnOpts, { to, id, from, lead: leadTarget, subject: p.subject, body: p.body.trim(), rev, logDir });
2571
2641
  workers.push({ name: to, pid: r.pid, replyId: id, log: r.logPath, driver });
2572
2642
  } catch (e) {
2573
2643
  workers.push({ name: to, replyId: id, driver, error: String((e && e.message) || e) });
2574
2644
  }
2575
2645
  }
2576
- return { status: 200, payload: { ok: true, cwd, workers, warnings: v.warnings } };
2646
+ let coordinator = undefined;
2647
+ if (leadMode === "board") {
2648
+ const coordHarness = harnesses.find((h) => h !== "generic") || "opencode";
2649
+ const coordSpawnOpts = { harness: coordHarness, cmd: body && body.cmd ? String(body.cmd) : undefined, model: p.model, auto, cwd, root: d.root, prompt: null };
2650
+ try {
2651
+ coordinator = provisionAutoLead(d, {
2652
+ spawnOpts: coordSpawnOpts,
2653
+ from, subject: p.subject, body: p.body.trim(), rev, logDir,
2654
+ workers: res.items.map((it, i) => ({ name: it.to, id: it.id, harness: harnesses[i % harnesses.length] })),
2655
+ batch: res.batch, auto,
2656
+ });
2657
+ } catch (e) {
2658
+ coordinator = { action: "skipped", reason: `coordinator boot error: ${String((e && e.message) || e)}`, leadName: LEAD_NAME };
2659
+ }
2660
+ }
2661
+ return { status: 200, payload: { ok: true, cwd, workers, coordinator, warnings: v.warnings } };
2577
2662
  }
package/docs/GROUPS.md CHANGED
@@ -95,8 +95,10 @@ block assumes:
95
95
  for approvals (`--priority high`) and scope disputes only.
96
96
  - **Channels are the shared read surface.** `crewbus channel tail
97
97
  grp-<group>` shows a group's briefs + mirrored progress; reads need
98
- no token. Channel *posting* is lead|admin-only, so workers write
99
- via DMs, never via `channel post`.
98
+ no token. Channel *posting* is member-scoped (default-on, no flag):
99
+ a worker may post to `grp-<group>` only when it is a MEMBER of that
100
+ group — board channels and foreign groups stay lead|admin-only
101
+ (see docs/RBAC.md).
100
102
  - **Boot habit.** `crewbus agents` + `crewbus group list` once at
101
103
  start, so a worker knows who else is here. A worker that never runs
102
104
  a discovery command will work star-topology through the lead — that
package/docs/IDENTITY.md CHANGED
@@ -128,3 +128,39 @@ long-running agent persists its token to a file it can re-read.
128
128
  `.crewbus/logs/<name>.token`), then `CREWBUS_TOKEN` env. Re-register
129
129
  is **impossible** for claimed names (first-claim-wins rejects it), so there
130
130
  is no third option — protect the file.
131
+
132
+ ## Post-compaction identity recovery (`crewbus recover`)
133
+
134
+ Compaction amnesia used to mint throwaway identities (`unknown` on the board,
135
+ `logs/unknown.token` nobody owns). Two layers now stop that:
136
+
137
+ - **Sentinel names never mint:** `unknown`, `me`, `you` are reserved —
138
+ `register` and `send` refuse them loudly (`ensureSender` guards them, so
139
+ every write path is covered). They exist only for tools that forgot who
140
+ they are, to force the recovery path instead of a silent identity loss.
141
+ - **Read-only candidate ranking:** `crewbus recover [--session <id>]
142
+ [--cwd <dir>]` scans `agents/*.json` ∩ `logs/*.token` and prints scored
143
+ candidates (best first): session-id register binding +4, token-file
144
+ cross-check against the stored `tokenHash`/`salt` +3 (proof), token file
145
+ exists +1, `lastDir` cwd match +1. It never writes or mints; it prints the
146
+ exact resume commands (CREWBUS_AGENT, token-file path, `inbox --unacked
147
+ --digest`). Offboarded agents are excluded for privacy-critical boards.
148
+
149
+ ```
150
+ crewbus: triage on [board …/sandbox-1/.crewbus]
151
+ proven pilg (role worker, score 9) — session id matches register binding;
152
+ token file cross-checks the stored hash; worked from this directory
153
+ resume as 'pilg': …
154
+ ```
155
+
156
+ - **Rehydrators resolve before naming "unknown":** the compaction card
157
+ (opencode plugin + `crewbus-hook compact`) first checks its session↔agent
158
+ map, then `CREWBUS_AGENT`, then a lite board-side score (binding + token
159
+ file + cwd, no hash cross-check in the standalone copies). Only when all
160
+ miss does it print the `crewbus recover` instruction — never a "you are
161
+ unknown" blessing.
162
+ - **Bindings survive daily traffic:** register stores `sessionId`; later
163
+ sessionless sends/re-registers/admin touches must NOT wipe it
164
+ (`mergeAgentDoc` deletes undefined patch keys — callers add `sessionId`
165
+ to the patch only when given). Heartbeats merge field-by-field and never
166
+ touch unrelated fields.
@@ -0,0 +1,85 @@
1
+ # Auto-assigned Lead & Observer Lane Model
2
+
3
+ Crewbus separates **spawning** from **leading**. Instead of the interactive spawner remaining the central router for all worker communications (sub-agent hub pattern), Crewbus defaults to an autonomous **lead** lane provisioned on the board, while workers collaborate peer-to-peer.
4
+
5
+ This architecture is modeled after decentralized multi-agent coordination patterns (e.g. Minecraft multi-agent peer collaboration):
6
+ - **Peers** communicate directly, self-organize strategy, and write findings to shared ambient memory (the board / Workbench).
7
+ - An **Observer** (`lead`) monitors health, chases failures/timeouts, fail-closes approvals, and verifies claims against actual artifacts.
8
+ - The **Boss** sets the objective and monitors milestones asynchronously without micromanaging execution.
9
+
10
+ ---
11
+
12
+ ## 1. The Lane Model
13
+
14
+ | Lane | Actor | Authority & Responsibilities |
15
+ |---|---|---|
16
+ | **Boss** | User / Calling Session | • Sets the objective and mission parameters.<br>• Reads progress via dashboard, status commands, or milestone DMs.<br>• Resolves out-of-scope mission changes or irreconcilable disputes.<br>• Never routes routine peer messages. |
17
+ | **Lead** | Autonomous Board Coordinator (`lead`) | • **Observer Role**: Environment repairs, TTL chasing, respawn health (`spawn-status --all`, `respawn`).<br>• **Approvals**: Decides on irreversible/high-risk actions (`fail-closed`).<br>• **Verification**: Audits worker claims against actual files/logs before aggregating.<br>• **Milestones**: Relays aggregate outcomes back to the boss.<br>• *Never* settles peer strategy disputes or does workers' implementation tasks. |
18
+ | **Peers** | Worker Agents (`sec-1`, `sec-2`, ...) | • Own task strategy, execution, and local decisions.<br>• Direct peer-to-peer DMs for targeted cooperation and rescue calls.<br>• Post lessons and artifacts directly to the board Workbench.<br>• Checkpoint progress along threads.<br>• Consult groups first; escalate to lead only for scope/approvals. |
19
+
20
+ ---
21
+
22
+ ## 2. CLI Control: `--lead auto|board|none`
23
+
24
+ When spawning workers with `crewbus spawn`:
25
+
26
+ ```sh
27
+ # Default: auto-assigns lead if a coding harness is present
28
+ crewbus spawn --from boss --count 3 --harness opencode --body "Implement feature X"
29
+
30
+ # Explicit board coordinator
31
+ crewbus spawn --from boss --count 3 --harness opencode --lead board --body "Implement feature X"
32
+
33
+ # Legacy star topology (replies pin directly to boss)
34
+ crewbus spawn --from boss --count 3 --harness generic --lead none --body "Run test suite"
35
+ ```
36
+
37
+ ### Modes:
38
+ - **`auto` (default)**:
39
+ - If any coding harness (`opencode`, `claude`, `codex`, `grok`, `antigravity`, `cursor`) is used: selects `board` mode.
40
+ - If all workers use `generic` harnesses (shell commands without an LLM harness): falls back to `none` mode.
41
+ - **`board`**:
42
+ - Auto-provisions or reuses the board's standing `lead` lane.
43
+ - Workers' brief prompts pin reply targets and approval requests to `--to lead`.
44
+ - Requires at least one coding harness to run the coordinator prompt; fails loudly if attempted with pure `generic` harnesses.
45
+ - **`none`**:
46
+ - Legacy star topology: replies and approvals pin directly to the spawner (`--to <from>`).
47
+ - No autonomous coordinator is provisioned.
48
+
49
+ ---
50
+
51
+ ## 3. Provisioning & Collision Rules
52
+
53
+ 1. **First-Claim-Wins**:
54
+ - On a fresh board without a `lead` agent, `provisionAutoLead` mints the `lead` identity with `role: "lead"`.
55
+ - The token is saved to `logs/lead.token` according to the token-file convention.
56
+ 2. **Reuse Standing Coordinators**:
57
+ - If an active coordinator is already running (live PID on the `lead` lane), subsequent `spawn` bursts reuse the standing coordinator rather than duplicating it.
58
+ - Workers from new bursts are transferred to the lead lane (`spawnedBy: "lead"`), preserving own-crew RBAC permissions for health tracking and `spawn-kill`.
59
+ 3. **Offboarded Safety**:
60
+ - If the `lead` lane has been marked `offboarded: true` (deliberate teardown), auto-provisioning is skipped with a loud warning.
61
+ 4. **Boss Detachment**:
62
+ - If `from === "lead"`, auto-provisioning skips into self-bootstrap mode to prevent recursion.
63
+ 5. **Lead Revive (`crewbus spawn --count 0`)**:
64
+ - When the coordinator died (crash, reboot, budget reap), the crew still has
65
+ its briefs/threads on the board — but nobody triaging. `--count 0` boots
66
+ NOTHING except the auto-coordinator lane: zero worker boots, zero DMs
67
+ delivered; the mission text you pass becomes the coordinator's reminder
68
+ of what the crew was on about (worker threads and scope live on the board).
69
+ - Requires `--lead board` (the default under a coding harness); worker
70
+ operands (`--to`/`--to-file`/`--to-group`) are refused — this path has no
71
+ worker operands. A standing coordinator is reused, never duplicated;
72
+ an offboarded lane skips with a loud warning, same as any burst.
73
+
74
+ ---
75
+
76
+ ## 4. Prompt Engineering
77
+
78
+ - **Workers (`buildSpawnPrompt`)**:
79
+ - Directs completion summaries, checkpoints, and approval requests to `--to lead`.
80
+ - Informs the worker that the spawner stepped back to boss and reads progress via the lead.
81
+ - Reinforces peer-first habits: consult groups before escalating to the lead.
82
+ - **Coordinator (`buildCoordinatorPrompt`)**:
83
+ - Injected with the verbatim mission text from the boss.
84
+ - Lists worker brief IDs for easy threading and reply tracking.
85
+ - Enforces polling discipline (`listen` / `inbox --digest`), fail-closed approval timeouts, and maximum 2 respawn attempts per lane before escalating stalls to the boss.
package/docs/LONG_RUNS.md CHANGED
@@ -41,11 +41,12 @@ the board.
41
41
 
42
42
  | Symptom | Fix |
43
43
  |---|---|
44
- | Post-compaction amnesia | Read the identity card (auto-injected); re-read token file → env; `inbox --unacked --digest` |
44
+ | Post-compaction amnesia | Identity card is auto-injected (hook compact / opencode plugin); unknown who you are? run `crewbus recover` — read-only candidate ranking (session binding → token-file↔tokenHash → cwd), then follow the printed resume script |
45
+ | Landed as "unknown" | Sentinel names ("unknown"/"me"/"you") never mint (register/send refuse them). Run `crewbus recover [--session <id>]` to re-find your real identity; only then re-register your true name |
45
46
  | Token lost entirely | Lead `token revoke --target`, worker re-registers |
46
47
  | Worker silent | `spawn-status`: no reply → read its log; re-brief or `respawn` |
47
48
  | Supervisor gone | `pool-resume --id`; stale locks expire via TTL |
48
- | Reboot | `doctor` → `spawn-status --all` (stale pids read dead, not running) → `respawn`/`pool-resume` |
49
+ | Reboot | `doctor` → `spawn-status --all` (stale pids read dead, not running) → `respawn`/`pool-resume`; dead coordinator: `crewbus spawn --count 0 --body "<what the crew was on>"` (C9 lead revive, workers untouched) |
49
50
  | Primary relay down | `relay promote` on the standby (see `docs/HA.md`) |
50
51
 
51
52
  ## Bottom line
package/docs/RBAC.md CHANGED
@@ -1,69 +1,73 @@
1
- # RBAC + per-board ACLs + group-scoped send permissions (Phase 1b)
2
-
3
- Zero-dependency, file-local. Composes with Phase 1a tokens: `checkToken()`
4
- proves WHO you are; `authorize()` decides WHAT your role may do. `authorize()`
5
- is a SEPARATE function called AFTER `checkToken()` passes — never before,
6
- never instead, never merged into token code.
7
-
8
- ## Roles
9
-
10
- Agent records carry `role` in `{admin, lead, worker, auditor}`.
11
-
12
- - First-registered agent on a board becomes **admin**; everyone else gets
13
- `acl.defaultRole` (default `"worker"`).
14
- - `register --role <r>` is only honored when the caller is **admin**,
15
- otherwise ignored with a warning on stderr (no self-promotion).
16
- - Grant/change: `register --from <admin> --for <target> [--role <r>]`
17
- (admin-only, bypasses frozen boards; also re-onboards offboarded names).
18
- - `agents --json` exposes roles (secrets stripped, role kept).
19
-
20
- ## Permission matrix (minimal)
21
-
22
- | action | admin | lead | worker | auditor |
23
- |---|---|---|---|---|
24
- | send / inbox / ack / redeliver / lock (scoped) | yes | yes | yes | read-only: inbox yes; send/ack/lock NO |
25
- | spawn / pool / spawn-kill (own crew) / group manage / channel post / result record / race close | yes | yes | NO | NO |
26
- | launch (same RBAC + audit as spawn: `cmdLaunch` delegates to `cmdSpawn`; `handleApiLaunch` checks `spawn`) | yes | yes | NO | NO |
27
- | relay pair issue / devices / revoke (`pairing`: CLI gate + `POST /api/pair/*`, `GET /api/pair/devices`) | yes | NO | NO | NO |
28
- | prune / acl set / role-grant / offboard / group restrict / serve `--allow-remote-spawn` | yes | NO | NO | NO |
29
- | reads (gather / thread / log / channel tail / group show / result show / spawn-status / agents) | yes | yes | yes | yes |
30
-
31
- Notes:
32
-
33
- - Reads not listed above default-allow (fail-closed only for writes).
34
- - `spawn-kill` for leads is own-crew only: every target's `spawnedBy` must
35
- equal the caller (or the target was never spawned). Admins may kill any.
36
- - `lock release` still requires ownership even when acquire is allowed.
37
- - MCP twins: `dm_send`→send, `dm_inbox`→inbox, `dm_ack`→ack,
38
- `dm_channel_post`→channel-post (lead|admin). `dm_gather` /
39
- `dm_channel_tail` are identity-less reads (like CLI `gather`), default-allow.
40
- - Relay: `POST /api/spawn`→spawn, `POST /api/launch`→spawn, `POST /api/kill`→spawn-kill (403 on denial); pair endpoints→`pairing` (admin): `POST /api/pair/issue|exchange|revoke`, `GET /api/pair/devices`.
41
- - Device-scope layer: transport credential scopes (`requireScope` in `bin/lib/relay.js`) compose UNDER role checks — a narrowed device can only further restrict, never widen, what the agent token's role allows.
42
- - `prune` and `group create/add/remove` keep the bare operator path (no
43
- `--from`) open for back-compat; with `--from` the caller is token-checked
44
- and authorized. `serve --allow-remote-spawn` with `--from` requires admin.
45
-
46
- ## Per-board ACLs
47
-
48
- `board.json` gains `acl: {defaultRole, frozen?}`.
49
-
50
- - `acl set --from <admin> [--default-role worker] [--freeze|--unfreeze]`
51
- (admin-only). `acl show [--json]` is read-only.
52
- - Frozen boards refuse new registrations (including first-send auto-mint),
53
- except by admin grant (`register --from <admin> --for <new>`).
54
-
55
- ## Group-scoped send permissions
56
-
57
- - `group restrict <name> --from <admin>` sets `restricted: true`
58
- (`group unrestrict` clears it). Admin-only. The flag survives member edits.
59
- - Sends with `--to-group` (or `to_group` / relay `to_group`) to a restricted
60
- group are refused unless the caller is admin/lead or a group member.
61
- - Pattern: curate a private crew (`group create elite --add a,b`),
62
- then `group restrict elite --from <admin>`; outsiders get a loud refusal,
63
- members + leads keep working.
64
-
65
- ## Back-compat
66
-
67
- Boards/agents without roles behave as today: legacy records without `role`
68
- map to **lead**, so existing crews keep working (and keep spawn/group/channel
69
- powers). Token-less legacy records keep the existing migrate-on-auth behavior.
1
+ # RBAC + per-board ACLs + group-scoped send permissions (Phase 1b)
2
+
3
+ Zero-dependency, file-local. Composes with Phase 1a tokens: `checkToken()`
4
+ proves WHO you are; `authorize()` decides WHAT your role may do. `authorize()`
5
+ is a SEPARATE function called AFTER `checkToken()` passes — never before,
6
+ never instead, never merged into token code.
7
+
8
+ ## Roles
9
+
10
+ Agent records carry `role` in `{admin, lead, worker, auditor}`.
11
+
12
+ - First-registered agent on a board becomes **admin**; everyone else gets
13
+ `acl.defaultRole` (default `"worker"`).
14
+ - `register --role <r>` is only honored when the caller is **admin**,
15
+ otherwise ignored with a warning on stderr (no self-promotion).
16
+ - Grant/change: `register --from <admin> --for <target> [--role <r>]`
17
+ (admin-only, bypasses frozen boards; also re-onboards offboarded names).
18
+ - `agents --json` exposes roles (secrets stripped, role kept).
19
+
20
+ ## Permission matrix (minimal)
21
+
22
+ | action | admin | lead | worker | auditor |
23
+ |---|---|---|---|---|
24
+ | send / inbox / ack / redeliver / lock (scoped) | yes | yes | yes | read-only: inbox yes; send/ack/lock NO |
25
+ | spawn / pool / spawn-kill (own crew) / group manage / result record / race close | yes | yes | NO | NO |
26
+ | channel post | yes (anywhere) | yes (anywhere) | members-only: the channel's own group only (`grp-<group>` where the caller is a member) | NO |
27
+ | launch (same RBAC + audit as spawn: `cmdLaunch` delegates to `cmdSpawn`; `handleApiLaunch` checks `spawn`) | yes | yes | NO | NO |
28
+ | relay pair issue / devices / revoke (`pairing`: CLI gate + `POST /api/pair/*`, `GET /api/pair/devices`) | yes | NO | NO | NO |
29
+ | prune / acl set / role-grant / offboard / group restrict / serve `--allow-remote-spawn` | yes | NO | NO | NO |
30
+ | reads (gather / thread / log / channel tail / group show / result show / spawn-status / agents) | yes | yes | yes | yes |
31
+
32
+ Notes:
33
+
34
+ - Reads not listed above default-allow (fail-closed only for writes).
35
+ - `spawn-kill` for leads is own-crew only: every target's `spawnedBy` must
36
+ equal the caller (or the target was never spawned). Admins may kill any.
37
+ - `lock release` still requires ownership even when acquire is allowed.
38
+ - MCP twins: `dm_send`→send, `dm_inbox`→inbox, `dm_ack`→ack,
39
+ `dm_channel_post`→channel-post (member-scoped like the CLI: lead|admin post anywhere, members post only to their own group's channel). `dm_gather` /
40
+ `dm_channel_tail` are identity-less reads (like CLI `gather`), default-allow.
41
+ - Member-scoped channel posting (C4) is default-on with no flag (briefs sent
42
+ with `--also-channel` to a group the sender is not a member of still
43
+ deliver as DMs; only the channel mirror is skipped, with a visible note).
44
+ - Relay: `POST /api/spawn`→spawn, `POST /api/launch`→spawn, `POST /api/kill`→spawn-kill (403 on denial); pair endpoints→`pairing` (admin): `POST /api/pair/issue|exchange|revoke`, `GET /api/pair/devices`.
45
+ - Device-scope layer: transport credential scopes (`requireScope` in `bin/lib/relay.js`) compose UNDER role checks — a narrowed device can only further restrict, never widen, what the agent token's role allows.
46
+ - `prune` and `group create/add/remove` keep the bare operator path (no
47
+ `--from`) open for back-compat; with `--from` the caller is token-checked
48
+ and authorized. `serve --allow-remote-spawn` with `--from` requires admin.
49
+
50
+ ## Per-board ACLs
51
+
52
+ `board.json` gains `acl: {defaultRole, frozen?}`.
53
+
54
+ - `acl set --from <admin> [--default-role worker] [--freeze|--unfreeze]`
55
+ (admin-only). `acl show [--json]` is read-only.
56
+ - Frozen boards refuse new registrations (including first-send auto-mint),
57
+ except by admin grant (`register --from <admin> --for <new>`).
58
+
59
+ ## Group-scoped send permissions
60
+
61
+ - `group restrict <name> --from <admin>` sets `restricted: true`
62
+ (`group unrestrict` clears it). Admin-only. The flag survives member edits.
63
+ - Sends with `--to-group` (or `to_group` / relay `to_group`) to a restricted
64
+ group are refused unless the caller is admin/lead or a group member.
65
+ - Pattern: curate a private crew (`group create elite --add a,b`),
66
+ then `group restrict elite --from <admin>`; outsiders get a loud refusal,
67
+ members + leads keep working.
68
+
69
+ ## Back-compat
70
+
71
+ Boards/agents without roles behave as today: legacy records without `role`
72
+ map to **lead**, so existing crews keep working (and keep spawn/group/channel
73
+ powers). Token-less legacy records keep the existing migrate-on-auth behavior.
@@ -10,6 +10,7 @@ Start with `crewbus doctor` — it prints the resolved board,
10
10
  | `drive root` refusal (`/.crewbus`, `C:\.crewbus`) | cwd resolution failed (detached harness worktree) | Pass an explicit `--board` path or set `CREWBUS_DIR`; see one Windows note below |
11
11
  | Group has one member like `cam-1-cam-2-cam-3` | PowerShell array-splatted an unquoted `--add a,b,c` (npm shim rejoins with spaces) | Quote comma lists on PowerShell: `--add "cam-1,cam-2,cam-3"` (same for `--to`, `--to-group`). List flags also accept whitespace separation, so a space-joined list still parses as several names |
12
12
  | `wrong token` / auth failure | Token missing or from a different name | Tokens print once and never re-print — reuse the `register` output saved at claim time (or `token rotate --from <name>` with the current token); export `CREWBUS_TOKEN`; names are lowercase (`Alice` == `alice`) |
13
+ | After compaction you "do not know" your identity (the `unknown` trap) | The harness summarized your session; register binding survives on the board doc | Run `crewbus recover [--session <id>]` — read-only candidate ranking (register binding, token-file↔hash cross-check, cwd); never re-register as `unknown`/`me`/`you` (those names refuse to mint), and never mint a throwaway name to "get moving" |
13
14
  | Push never arrives (non-opencode harness) | Hooks not trusted / harness not restarted after `init` | Re-run `crewbus init --harness <name>` (merges, never overwrites), approve MCP/trust prompts (`/hooks`, `/hooks-trust`), restart harness |
14
15
  | `doctor` FAIL on hooks/MCP entries | Wiring edited or installed for another harness | Re-run `init --harness <name>`, then follow the printed follow-ups |
15
16
  | Duplicate or replayed DMs | Two push paths racing, or pruned markers | Markers in `delivered/` + `cursors/` dedupe across restarts; `redeliver --from <name> --all` after re-registering a dead watcher; `prune` keeps surviving markers so cursors never replay |
@@ -1,6 +1,6 @@
1
1
  # Version skew (mixed-relay operation)
2
2
 
3
- How crewbus versions interoperate. Evidence: `package.json:2` (`10.0.9`),
3
+ How crewbus versions interoperate. Evidence: `package.json:2` (`10.0.10`),
4
4
  `CHANGELOG.md` (10.0.0 2026-10-08; 7.0.0 2026-10-05; 6.4.0–6.0.0; 4.1.0/4.0.0 baseline).
5
5
  Capabilities: `RELAY_CAPS` + `launch` per `packages/contracts/board-caps.json:6-8`.
6
6
  Cell behavior is the NEW side's verified behavior (`bin/lib/sync.js` refs);
@@ -86,7 +86,7 @@ code{overflow-wrap:anywhere}pre code{overflow-wrap:normal}
86
86
  <main>
87
87
 
88
88
  <h1>crewbus</h1>
89
- <p class="sub">A zero-dependency local DM bus for AI coding agents — v10.0.9 · package <code>crewbus</code> · <a href="https://github.com/eamonpluto/crewbus/actions/workflows/ci.yml">CI status</a></p>
89
+ <p class="sub">A zero-dependency local DM bus for AI coding agents — v10.0.10 · package <code>crewbus</code> · <a href="https://github.com/eamonpluto/crewbus/actions/workflows/ci.yml">CI status</a></p>
90
90
  <p class="sub">Lead audience: developers running <strong>mixed-harness crews</strong> (opencode, Claude Code, Codex, Antigravity, grok-build, Cursor). <code>package.json</code> is the release version source of truth; <code>board.json</code>'s <code>version: 2</code> is the board <em>schema</em> version, not the release.</p>
91
91
 
92
92
  <h2 id="what">1 · What it is</h2>
@@ -302,6 +302,7 @@ crewbus init --harness &lt;name&gt; --portable # portable wiring
302
302
 
303
303
  <h2 id="changes">16 · Changelog</h2>
304
304
  <ul>
305
+ <li><strong>10.0.10</strong> — minor release: Observer coordinator lane model (<code>boss</code> / <code>lead</code> / <code>peers</code>), auto-assigned lead (<code>--lead auto|board|none</code>), and Desktop app alignment. Full text: <code>CHANGELOG.md ## 10.0.10</code>.</li>
305
306
  <li><strong>10.0.9</strong> — minor release: Workbench compound-memory layer — artifacts with adoption/verification and deps edges, lessons auto-injected into spawn briefs, <code>--needs-by</code> handoff deadlines + <code>inbox --overdue</code>, feed-forward gather metrics, exact-recipient pinning in briefs; opencode respawn session capture fixed (direct exe boot + <code>opencode.db</code> storage fallback, doctor drift checks). Full text: <code>CHANGELOG.md ## 10.0.9</code>.</li>
306
307
  <li><strong>10.0.8</strong> — patch release: Launch composer UI refinements (streamlined worker naming, clearer agent count stepper, flat composer card, clean launch console) &amp; desktop companion. Full text: <code>CHANGELOG.md ## 10.0.8</code>.</li>
307
308
  <li><strong>10.0.7</strong> — patch release: design refresh and icon fix across desktop and mobile shells. Full text: <code>CHANGELOG.md ## 10.0.7</code>.</li>
@@ -350,7 +351,7 @@ crewbus init --harness &lt;name&gt; --portable # portable wiring
350
351
  <h3>Mobile shell</h3>
351
352
  <p>Expo shell, remote-only v1 (see <code>apps/mobile/README.md</code>): pairs by QR scan, walks advertised + learned routes, offers triage/approvals/launch/fleet cards with an offline outbox that only retries on explicit tap. Triage groups inbox by brief thread; the Briefs screen shows one row per fan-out with tap-for-thread; a foreground watcher raises in-app alerts for approvals and dead workers.</p>
352
353
 
353
- <footer>crewbus documentation · v10.0.9 tree · zero dependencies, node ≥18 · MIT</footer>
354
+ <footer>crewbus documentation · v10.0.10 tree · zero dependencies, node ≥18 · MIT</footer>
354
355
 
355
356
  </main>
356
357
  </div>