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/CHANGELOG.md CHANGED
@@ -1,5 +1,43 @@
1
1
  # Changelog
2
2
 
3
+ ## 10.0.11
4
+
5
+ Post-compaction identity recovery + stale-pid guards + coordinator budgets + member-scoped channels + inbox archive + lead revive (engine hardening batches 2-5, 9).
6
+
7
+ - **Member-scoped channel posting (C4, default-on)**: channel post is no longer lead|admin-only for everyone — workers (default role) may post to `grp-<group>` channels of groups they are a MEMBER of; lead/admin keep board-wide posting. Every refusal stays loud: board channels and foreign group channels refuse workers with the reason (`authorizeCheck` gains a `channel-post` scoped branch; MCP mirror `dm_channel_post` + `authorizeMcp` updated identically). `--also-channel` brief mirrors become member-gated per group: the DM always delivers, only unauthorized channel mirrors are skipped with a visible `[channel mirror skipped, members-only: <g>]` note (CLI `send`/`spawn` + MCP `dm_send`). `docs/RBAC.md` matrix updated.
8
+
9
+ - **Coordinator budgets (`--lead-budget-tokens` / `--lead-budget-minutes`)**: the auto-provisioned lead lane accepts the same budget semantics as workers — stamped on the lane doc at boot (`budgetTokens`/`budgetMinutes`/`budgetSince`), surfaced in the coordinator prompt as a mandate line ("post the aggregate BEFORE the budget runs out; a budgeted coordinator gets reaped at the cap"), validated at parse (`--lead-budget-*` must be positive numbers). Unset = persistent boss-supervised coordinator (default, unchanged from 10.0.10). A standing coordinator keeps its boot-time budget; flags cannot change it mid-flight.
10
+
11
+ - **Sentinel names never mint**: `"unknown"`, `"me"`, `"you"` are reserved — register/self-claim, admin `--for` grants, and send (`ensureSender`, hence every write path incl. relay auto-mint) refuse them loudly. They exist so amnesia-throwaway identities surface instead of silently locking a board (`logs/unknown.token` owned by nobody).
12
+ - **`crewbus recover [--session <id>] [--cwd <dir>]`**: new read-only triage command (never mints, never writes). Scans `agents/*.json` ∩ `logs/*.token` and prints scored candidates best-first — session-id register binding +4, token-file↔stored-hash cross-check +3 (proven), token file exists +1, `lastDir` cwd match +1 — plus the exact resume script (CREWBUS_AGENT, token-file path, `crewbus inbox --from <you> --unacked --digest`). Offboarded agents excluded.
13
+ - **Rehydrators resolve before blessing "unknown"**: the compaction identity card (opencode plugin template + repo plugin + `crewbus-hook compact`) now tries the session↔agent map → `CREWBUS_AGENT` → board-side lite scoring (no hash cross-check in the standalone copies) before printing a whoami card; when nothing sticks it prints the `crewbus recover` instruction and the never-re-register-unknown warning.
14
+ - **Bug fixed — sessionless traffic wiped register bindings**: `mergeAgentDoc` treats undefined patch keys as deletions, so `touchAgent(…, { sessionId: undefined })` inside sessionless send/re-register/admin-grant erased the `--session` binding stamped at register (v-bumped docs, `sessionId` silently dropped). Sessionid is now only added to touch patches when actually provided.
15
+ - **Inbox archive (C6, explicit opt-in)**: `crewbus inbox archive --from <you> (--all | --before <dur>)` moves acked direct DMs + checkpoints from `dm/<you>/` into `dm-archive/<you>/` — unacked work NEVER archives implicitly (scope is mandatory; the command fails with usage otherwise). Broadcasts are board-level files and are never moved (admin `prune` territory). Id collisions (archive already holds the file, e.g. an id re-delivered after the move) keep both copies — no double-move. Read-back is explicitly opt-in: `crewbus inbox --from <you> --archived` lists the archive view (direct DMs only); the live read never shows archived rows.
16
+ - New tests: `test/crewbus.recover.mjs` (32 checks: recoverIdentity scoring incl. forged-token never-proven + legacy no-hash handling, sentinel CLI guards, recover resume script, `crewbus-hook compact` sentinel resolution), `test/crewbus.lead-budget.mjs` (11 checks: prompt mandate lines, `provisionAutoLead` budget stamping through bootWorker, CLI parse validation), `test/crewbus.channel-member.mjs` (17 checks: authorizeCheck matrix, CLI member/non-members/restricted posting, `--also-channel` mirror gating), and `test/crewbus.inbox-archive.mjs` (13 checks: scope guard, window + --all moves, unacked-work invariant, ids read-back gating, id-collision safety, owner-token gate, --json shape).
17
+ - Test suite hygiene: `crewbus.workbench.mjs` strips leaked operator identity too.
18
+ - **Stale-pid guards everywhere (C2)**: `isPidStale` (a live pid that provably postdates the spawn record = OS pid reuse after a reboot, i.e. an unrelated process) is now wired into every standing/liveness decision, not just `spawn-status`: auto-lead reuse (`provisionAutoLead`), dry-run lead previews (CLI `spawn` + desktop launch + relay spawn API), the spawn live-name refusal, `respawn`'s still-running gate, group telemetry "running", relay `/healthz` worker counts, the web roster `aliveByName`, and — safety-critical — `killWorkers` refuses to `taskkill`/`signal` a pid-stale record (new `pid-stale` result; killing an unrelated recycled process would have been possible before).
19
+ - Docs: `docs/LONG_RUNS.md` recovery ladder rows, `docs/IDENTITY.md` "Post-compaction identity recovery" section.
20
+ - **Lead revive (`crewbus spawn --count 0`)**: a crashed/rebooted coordinator can be brought back without touching the crew — boots nothing except the auto-coordinator lane (zero worker boots, zero DMs delivered; the passed mission text becomes the coordinator's reminder of what the crew was on about, worker briefs/threads live on the board). Requires `--lead board` and refuses worker operands (`--to`/`--to-file`/`--to-group`) and negative counts; a standing coordinator is reused, never duplicated; `--dry-run` previews the lead-only plan. `docs/LEAD_ASSIGN.md` §3.5 + `docs/LONG_RUNS.md` reboot row.
21
+ - CI: new `lead-e2e` lane (ubuntu, Node 22) installs the real `opencode-ai` CLI and runs the harness-backed E2E suites that local `npm test` skips when opencode is absent — kidproc, lead-assign (incl. lead revive) and lead-budget.
22
+ - Docs: `docs/GROUPS.md` channel-post wording updated to member-scoped semantics; `docs/TROUBLESHOOTING.md` gains the post-compaction "unknown" trap row (`crewbus recover`).
23
+
24
+ DEP0190-free child spawning (engine hardening batch 1).
25
+
26
+ - **DEP0190-free child spawning**: Node >=22 deprecates `spawn(exe, args, { shell: true })` when `args` is non-empty (a hard error on a future Node). New standalone module `bin/lib/kidproc.js` converts shell-needing targets (npm `.cmd` shims: claude/codex/cursor; the `where opencode` probe; binary probes via `probeBinary`) into an explicit shell argv0 (`cmd.exe /d /s /c "<ms-quoted line>"` with `windowsVerbatimArguments`, `/bin/sh -c` on POSIX) with **correct** quoting — the old wire passed args unescaped (space splitting, quote eating, bare `& | ^` command injection). Worker-prompt delivery is now argv-identity round-trip safe (`bin/crewbus.js: `launchWorkerProcess`/`probeBinary`/`resolveOpencodeExe` migrated; real-exe `shell:false` targets like resolved opencode pass through untouched so the spawned pid stays the harness process). Argv identity is asserted by round-trip through the real cmd parser. Known cmd limitation documented: a matched `%VAR%` pattern inside a quoted token still expands at the cmd layer (unmatched `%` passes intact).
27
+ - **Escape hatch**: `CREWBUS_SHELL_LEGACY=1` restores the pre-refactor `shell: true` behavior for exactly one release.
28
+ - Test env hygiene: suites strip operator identity leaks (`CREWBUS_TOKEN`/`CREWBUS_AGENT`) so fresh tmp-board identities always mint their own tokens.
29
+ - New tests: `test/crewbus.kidproc.mjs` (32 checks: MS/POSIX quoting vectors, cmd round-trip identity, resolveShellShot migration shape, legacy hatch pin).
30
+
31
+ ## 10.0.10 (2026-10-18)
32
+
33
+ MINOR RELEASE: Observer coordinator lane model (`boss` / `lead` / `peers`), auto-assigned lead (`--lead auto|board|none`), and Desktop app alignment. No board-schema change (`board.json` stays v2).
34
+
35
+ - **Auto-assigned Lead & Observer Lane Model (`--lead auto|board|none`)**: Separates spawn authority from acting lead. `spawn` bursts now auto-provision a persistent background coordinator (`lead`, role: `lead`) that monitors worker health, answers approval requests, runs respawn loops, and sends aggregate reports back to the spawner (`boss`). Workers pin all checkpoints, approvals, and completions `--to lead`.
36
+ - **Peer-to-Peer Lane Structure**: Establishes 3 explicit lanes: `boss` (human operator / board admin), `lead` (autonomous Observer coordinator), and `peers` (workers executing tasks). Workers coordinate with each other directly via peer-DMs and report to `lead` only for approvals and milestones.
37
+ - **Desktop App & Sidecar Alignment**: Desktop loopback server auto-provisions `boss` as the human operator (with transparent fallback for existing `lead` boards). Launch Studio composer adds a Coordinator selector (`auto` | `none`), surfaces live coordinator status, and displays role badges in the agent roster. Approvals view surfaces pending unacked approvals sent to `lead` for supervisor review.
38
+ - **Contract & Validation**: `packages/contracts/launch.json` and `validateLaunchPlan` updated with `lead` mode options and `coordinator` response payload.
39
+ - New tests: `test/crewbus.lead-assign.mjs` (33 checks) + expanded `test/crewbus.web-launch.mjs`.
40
+
3
41
  ## 10.0.9 (2026-10-17)
4
42
 
5
43
  MINOR RELEASE: Workbench compound-memory layer (artifacts, lessons, needs-by) + opencode respawn capture fix. No board-schema change (`board.json` stays v2); the additive `artifacts/` and `lessons/` directories appear on first write — old boards pick them up lazily, nothing to migrate.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # crewbus v10.0.9 — DM bus
1
+ # crewbus v10.0.10 — DM bus
2
2
 
3
3
  [![CI](https://github.com/eamonpluto/crewbus/actions/workflows/ci.yml/badge.svg)](https://github.com/eamonpluto/crewbus/actions/workflows/ci.yml)
4
4
 
@@ -55,7 +55,7 @@ env overrides below.)
55
55
  Layout: `board.json`, `agents/<name>.json`, `dm/<recipient>/<id>.json`,
56
56
  `delivered/<recipient>/<id>.json` (push markers, written by the plugin).
57
57
 
58
- Versions: `package.json` (currently 10.0.9) is the source of truth for the
58
+ Versions: `package.json` (currently 10.0.10) is the source of truth for the
59
59
  release version. `board.json`'s `version: 2` is the **board schema version**
60
60
  (a different number on purpose — do not "align" them). New to the project?
61
61
  Start with `docs/QUICKSTART.md` (5 minutes).
@@ -114,6 +114,46 @@ function resolveAgent(args, what) {
114
114
  return cleanName(getFlag(args, "--from") || process.env.CREWBUS_AGENT, what);
115
115
  }
116
116
 
117
+ // C1 lite recovery (self-contained: no bin/lib imports — the hook ships
118
+ // standalone). Same scoring spirit as `crewbus recover`, minus the
119
+ // token-hash cross-check: session binding +4, token file +1, cwd match +1.
120
+ // Returns [{ name, role, score, proven, why }] best-first.
121
+ function recoverCandidatesLite(root, opts = {}) {
122
+ const cands = [];
123
+ try {
124
+ const agentsDir = path.join(root, "agents");
125
+ const logsDir = path.join(root, "logs");
126
+ const tokenNames = new Set();
127
+ try {
128
+ for (const f of fs.readdirSync(logsDir)) if (f.endsWith(".token")) tokenNames.add(f.slice(0, -6).toLowerCase());
129
+ } catch {}
130
+ const cwd = String(opts.cwd || "").replace(/\\/g, "/").toLowerCase();
131
+ for (const f of fs.readdirSync(agentsDir)) {
132
+ if (!f.endsWith(".json")) continue;
133
+ const doc = readJsonSafe(path.join(agentsDir, f));
134
+ if (!doc || !doc.name || doc.offboarded) continue;
135
+ let score = 0;
136
+ const why = [];
137
+ if (opts.sessionID && doc.sessionId && String(doc.sessionId) === String(opts.sessionID)) {
138
+ score += 4;
139
+ why.push("session id matches register binding");
140
+ }
141
+ if (tokenNames.has(String(doc.name).toLowerCase())) {
142
+ score += 1;
143
+ why.push("token file exists for this name");
144
+ }
145
+ if (doc.lastDir && cwd && String(doc.lastDir).replace(/\\/g, "/").toLowerCase() === cwd) {
146
+ score += 1;
147
+ why.push("worked from this directory");
148
+ }
149
+ if (score <= 0) continue;
150
+ cands.push({ name: doc.name, role: doc.role || "peer", score, proven: false, why: why.join("; ") });
151
+ }
152
+ } catch {}
153
+ cands.sort((a, b) => b.score - a.score || String(a.name).localeCompare(String(b.name)));
154
+ return cands;
155
+ }
156
+
117
157
  function readJsonSafe(p) {
118
158
  try {
119
159
  return JSON.parse(fs.readFileSync(p, "utf8"));
@@ -466,10 +506,25 @@ async function cmdMonitor(args) {
466
506
 
467
507
  async function cmdCompact(args) {
468
508
  const root = boardDir(args);
469
- const agent = resolveAgent(args, "agent");
509
+ const agent0 = resolveAgent(args, "agent");
510
+ const sessionID = getFlag(args, "--session");
470
511
  // Best-effort reads only: a compaction hook must never break its harness,
471
512
  // so missing boards/docs degrade to "what is known", never a loud failure.
513
+ // When the invoked name is an amnesia sentinel ("unknown"), try board-side
514
+ // recovery BEFORE blessing it (post-compaction rehydration: C1).
515
+ let agent = agent0;
516
+ const RES = ["unknown", "me", "you"];
517
+ if (RES.includes(agent)) {
518
+ const cands = recoverCandidatesLite(root, { sessionID, cwd: process.cwd() });
519
+ if (cands[0] && cands[0].score >= 2) agent = cands[0].name;
520
+ }
472
521
  const doc = readJsonSafe(path.join(root, "agents", `${agent}.json`));
522
+ if (RES.includes(agent)) {
523
+ console.log(`crewbus: context refreshed after compaction, but this hook could not identify '${agent0}' on board ${root}.`);
524
+ console.log(`Recover (read-only, never mints): crewbus recover${sessionID ? ` --session ${sessionID}` : ""} — it ranks candidate identities (register session binding, token files, cwd history) and prints exact resume commands.`);
525
+ console.log(`NEVER re-register as 'unknown'/'me'/'you' — those sentinel names are reserved and refuse to mint; recover your real identity instead.`);
526
+ return;
527
+ }
473
528
  console.log(`crewbus: context refreshed after compaction. You are '${agent}' on board ${root}.`);
474
529
  console.log(`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.`);
475
530
  console.log(`Then: crewbus inbox --from ${agent} --unacked --digest (escalate to full reads on hits).`);
@@ -509,7 +564,7 @@ async function main() {
509
564
  " crewbus-hook monitor --from <you> [--timeout <sec>] [--interval <sec>] [--board <path>]\n" +
510
565
  " (blocking event stream for grok-build's monitor tool: prints each new batch to stdout on arrival,\n" +
511
566
  " silent otherwise. Defaults: 0s timeout (run until killed), 1s interval.)\n" +
512
- " crewbus-hook compact --from <you> [--board <path>]\n" +
567
+ " crewbus-hook compact --from <you> [--session <id>] [--board <path>]\n" +
513
568
  " (post-compaction identity card: who/where/token-path plus the inbox\n" +
514
569
  " next step; spawned workers also get their brief promptPath. Never\n" +
515
570
  " fails on missing files — prints what is known.)"
@@ -751,12 +751,24 @@ function authorizeMcp(d, agent, action, scope) {
751
751
  const role = getRoleMcp(d, agent);
752
752
  const act = String(action || "");
753
753
  const ADMIN_ONLY = new Set(["prune", "acl-set", "role-grant", "offboard", "group-restrict", "serve-remote"]);
754
- const LEAD_PLUS = new Set(["spawn", "respawn", "pool", "group-manage", "channel-post", "result-record", "race-close"]);
754
+ const LEAD_PLUS = new Set(["spawn", "respawn", "pool", "group-manage", "result-record", "race-close"]);
755
755
  const WORKER_WRITES = new Set(["send", "ack", "redeliver", "lock"]);
756
756
  if (role !== "admin") {
757
757
  if (ADMIN_ONLY.has(act)) throw new Error(`role "${role}" cannot ${act} (need admin)`);
758
758
  if (LEAD_PLUS.has(act) && role !== "lead") throw new Error(`role "${role}" cannot ${act} (need lead|admin)`);
759
759
  if (act === "spawn-kill" && role !== "lead") throw new Error(`role "${role}" cannot spawn-kill (need lead|admin)`);
760
+ if (act === "channel-post" && role !== "lead") {
761
+ // Member-scoped channel posting (C4): members post to their group's
762
+ // channel; board channels + foreign groups stay lead|admin.
763
+ const targetGroup = scope && scope.channelGroup ? String(scope.channelGroup) : undefined;
764
+ if (!targetGroup) {
765
+ throw new Error(`role "${role}" may post only to a group channel it belongs to (board channels are lead|admin)`);
766
+ }
767
+ const gdoc = readGroupMcp(d, targetGroup);
768
+ if (!gdoc) throw new Error(`channel group "${targetGroup}" not found (groups register their channels — board channels are lead|admin)`);
769
+ const members = Array.isArray(gdoc.members) ? gdoc.members : [];
770
+ if (!members.includes(agent)) throw new Error(`group channel "${targetGroup}" — members only (member or lead|admin)`);
771
+ }
760
772
  if (WORKER_WRITES.has(act) && role !== "lead" && role !== "worker") {
761
773
  throw new Error(`role "${role}" cannot ${act} (auditor is read-only)`);
762
774
  }
@@ -1048,7 +1060,16 @@ function callTool(name, args) {
1048
1060
  const mirror = (batch) => {
1049
1061
  if (a.also_channel !== true) return "";
1050
1062
  const mirrored = [];
1063
+ const skipped = [];
1051
1064
  for (const g of groupNames) {
1065
+ // Member-scoped mirrors (C4): non-members' DMs deliver; the channel
1066
+ // mirror is skipped with a visible note. Lead/admin pass trivially.
1067
+ try {
1068
+ authorizeMcp(d, from, "channel-post", { channelGroup: g });
1069
+ } catch (err) {
1070
+ skipped.push(g);
1071
+ continue;
1072
+ }
1052
1073
  const post = { id: newId("ch"), from, body, at };
1053
1074
  if (subject) post.subject = subject;
1054
1075
  if (replyTo) post.replyTo = replyTo;
@@ -1058,7 +1079,7 @@ function callTool(name, args) {
1058
1079
  appendChannelPostMcp(d, groupChannelNameMcp(g), post);
1059
1080
  mirrored.push(groupChannelNameMcp(g));
1060
1081
  }
1061
- return mirrored.length > 0 ? ` +channel ${mirrored.join(",")}` : "";
1082
+ return (mirrored.length > 0 ? ` +channel ${mirrored.join(",")}` : "") + (skipped.length > 0 ? ` [channel mirror skipped, members-only: ${skipped.join(",")}]` : "");
1062
1083
  };
1063
1084
  const isAll = recipients.length === 1 && recipients[0] === "@all";
1064
1085
  if (isAll || recipients.length > BROADCAST_AFTER) {
@@ -1294,7 +1315,8 @@ function callTool(name, args) {
1294
1315
  const subject = a.subject === undefined || a.subject === null || String(a.subject).trim() === "" ? undefined : String(a.subject).trim().slice(0, 120);
1295
1316
  const priority = cleanPriorityMcp(a.priority);
1296
1317
  const minted = ensureSender(d, from, resolveToken(a));
1297
- authorizeMcp(d, from, "channel-post"); // lead|admin only (worker refused)
1318
+ // Member-scoped posting (C4): grp-<g> channels admit members of <g>.
1319
+ authorizeMcp(d, from, "channel-post", { channelGroup: chan.startsWith("grp-") ? chan.slice(4) : undefined });
1298
1320
  touchAgent(d, from);
1299
1321
  const tokenHint = minted.created ? ` identity '${from}' claimed, token ${minted.token} (set CREWBUS_TOKEN=${minted.token})` : "";
1300
1322
  const post = { id: newId("ch"), from, body, at: new Date().toISOString() };