Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): bundles, permissions single-source, fleet migrations, live activity bus

Salman Qureshi790d20a2f167
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.md
index 18d04560..1c401511 100644
--- a/BOTS-ARCHITECTURE.md
+++ b/BOTS-ARCHITECTURE.md
@@ -156,12 +156,15 @@ Cross-bot *context sharing* (the research-bot → publisher-bot case) is **not**
### 2.5 Sandboxing & permissions (fail-closed, no mid-run prompts)
-Bots get their **own** `PermissionManager` seeded from `bots/<id>/permissions.yaml`:
+Bots get their **own** `PermissionManager` seeded from `bots/<id>/permissions.yaml` — the **single source of truth** for what a bot may do:
+- **One file decides everything**: `permissions.yaml` holds the tool gate (`tools.allow/deny`), path scopes (`paths`), and shell lists (`autoApproveCommands`, `blockedCommands`). `bot.yaml` carries identity/fleet/schedules only; the persona carries **character only** (legacy `## Access` sections are folded into permissions.yaml and stripped at startup).
+- **Fleet inheritance**: a crew bot runs on its **lead's** permissions verbatim (copied into its own dir at creation / first use) unless it has an explicitly edited `permissions.yaml` — inherit-unless-edited, and `self` scopes resolve per-bot so verbatim copies are safe.
- **Tool allow/deny**: `tools.deny` always wins (OpenClaw rule: deny can't be re-enabled). Default-deny for destructive tools (`shell`, `write_file`, `delete_file`, `git_commit`) unless explicitly allowed at setup.
+- **Onboarding tiers execute**: the permission-tier question writes the chosen tier as a full permissions.yaml — tool gate AND path scopes (operator grants execute; full grants the home directory read/write/execute). A tier choice that only flipped the tool gate left bots unable to act — chosen permissions must take effect.
- **No interactive approval for bots, ever.** A permission prompt inside a bot turn is auto-resolved **deny** and journaled (`auto_deny` reason code). This is Hermes' fail-closed rule applied to a non-interactive worker. The owner sees denials in `/bots <id> journal` and can widen scopes at setup/review time.
- **No allow-all inheritance**: a bot can never inherit the session's allow-all mode — mirrors and extends the existing `isGlobalAutoApproveActive` rule that web/cloud requests don't inherit local allow-all.
-- **Path scopes**: bot file access is scope-based like the main agent's manifest, defaulting to the bot's own dir + explicitly granted workspace paths. `cwdOnly`-style escape gates apply.
+- **Path scopes**: bot file access is scope-based like the main agent's manifest, defaulting to the bot's own dir + explicitly granted workspace paths. `cwdOnly`-style escape gates apply. The bot's sandbox and the fleet-shared folder are implicit, never configurable away.
- **Dangerous-pattern denylist** reused from the main permission system for any allowed shell (plus the hardline set that survives every mode).
- **Budgets as security**: per-bot `dailyTokenBudget` and turn caps are hard stops (pause + journal, resume next window), protecting low-end devices and wallets from runaway loops.
@@ -181,6 +184,7 @@ Inherited from Mercury's "always uses a solution" ethos, hardened:
| Surface | How |
|---|---|
+| **Real-time activity bus** | Every bot turn emits granular events (turn-start, step, tool start/finish, turn-end) via `BotManager.onBotActivity`. Consumed by: the open bot thread's live region (same spinner block as the main chat), the `/bots` roster `↳ activity` line and `fleet_status` (mirrored into the activity map), and the web SSE feed (`bot_activity` events — dashboards / third-party backends). |
| **TUI** | New `/bots` slash command (fast-path, like `/agents`) → interactive panel: list bots (live states), onboard (guided, fully automatic config generation), edit config/persona, view journal, enable/disable, send a message. Also a TUI page in `cli.ts` command layer. |
| **Local HTTP API** | Hono module `src/web/api/bots.ts`: `GET /api/bots`, `POST /api/bots` (onboard), `GET/PATCH/DELETE /api/bots/:id`, `POST /api/bots/:id/message` (enqueue; returns job id), `POST /api/bots/:id/enable|disable`, `GET /api/bots/:id/journal`, `POST /api/bots/:id/replay`. Auth: existing web auth + attach token. |
| **Mercury Cloud** | `agent.command` envelope gains `bot.*` command types (list, message, configure) — same pattern as existing `model.select`/`task.stop`; cross-instance bot↔bot via `agent.message.relay`. |
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.ts
index ebb0f0a2..204ada08 100644
--- a/src/bots/bot-manager.test.ts
+++ b/src/bots/bot-manager.test.ts
@@ -384,7 +384,7 @@ describe('Per-bot permission isolation (fail-closed)', () => {
botId: 'writer',
manifest,
botDir: store.botDir('writer'),
- permissions: store.readPermissions('writer'),
+ permissions: store.ensurePermissions('writer'),
userMemory: null,
config: getDefaultConfig() as MercuryConfig,
});
@@ -401,23 +401,25 @@ describe('Per-bot permission isolation (fail-closed)', () => {
expect(pm.getManifest().capabilities.shell.blocked).toContain('sudo *');
});
- it('persona ## Access grants merge additively into the registry scopes', () => {
+ it('the persona is NOT a permission source — grants must come from permissions.yaml', () => {
const manifest = store.create({ id: 'cookiebot', name: 'Cookiebot' }) as BotManifest;
+ // A persona with an Access section grants NOTHING at registry build time.
store.writePersona('cookiebot', `# Cookiebot\n\n## Access\n\n- ~/cookies — read\n- /tmp/execdir — execute\n`);
const registry = createBotCapabilityRegistry({
botId: 'cookiebot',
manifest,
botDir: store.botDir('cookiebot'),
- permissions: store.readPermissions('cookiebot'),
- persona: store.readPersona('cookiebot'),
+ permissions: store.ensurePermissions('cookiebot'),
userMemory: null,
config: getDefaultConfig() as MercuryConfig,
});
const scopes = registry.permissions.getManifest().capabilities.filesystem.scopes;
- // Own profile dir (default grant) still there, plus the persona grants.
+ // Only the materialized default (own dir) + sandbox — NO persona grants.
expect(scopes.some(s => s.path === store.botDir('cookiebot'))).toBe(true);
- expect(scopes.some(s => s.path.endsWith('/cookies') && s.read && !s.write)).toBe(true);
- expect(scopes.some(s => s.path === '/tmp/execdir' && s.execute)).toBe(true);
+ expect(scopes.some(s => s.path.endsWith('/cookies'))).toBe(false);
+ expect(scopes.some(s => s.path === '/tmp/execdir')).toBe(false);
+ // The startup migration is what folds persona grants into the file.
+ expect(store.ensurePermissions('cookiebot').paths?.some(p => p.scope === '~' || p.scope.endsWith('/cookies'))).toBe(false);
});
it('a malformed permissions.yaml entry (missing "scope") is skipped, not fatal', () => {
@@ -435,7 +437,6 @@ describe('Per-bot permission isolation (fail-closed)', () => {
manifest,
botDir: store.botDir('typo'),
permissions: store.readPermissions('typo'),
- persona: store.readPersona('typo'),
userMemory: null,
config: getDefaultConfig() as MercuryConfig,
});
@@ -451,8 +452,7 @@ describe('Per-bot permission isolation (fail-closed)', () => {
botId: 'plainbot',
manifest,
botDir: store.botDir('plainbot'),
- permissions: store.readPermissions('plainbot'),
- persona: store.readPersona('plainbot'), // default template: examples only, no grant bullets
+ permissions: store.ensurePermissions('plainbot'),
userMemory: null,
config: getDefaultConfig() as MercuryConfig,
});
@@ -472,8 +472,7 @@ describe('Per-bot permission isolation (fail-closed)', () => {
botId: 'sandboxer',
manifest,
botDir: store.botDir('sandboxer'),
- permissions: store.readPermissions('sandboxer'),
- persona: store.readPersona('sandboxer'),
+ permissions: store.ensurePermissions('sandboxer'),
sandbox: { workspace: store.sandboxDir('sandboxer'), shared: store.sharedSandboxDir() },
userMemory: null,
config: getDefaultConfig() as MercuryConfig,
@@ -513,7 +512,7 @@ describe('Per-bot permission isolation (fail-closed)', () => {
botId: 'writer',
manifest,
botDir: store.botDir('writer'),
- permissions: store.readPermissions('writer'),
+ permissions: store.ensurePermissions('writer'),
userMemory: null,
config: getDefaultConfig() as MercuryConfig,
});
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 57abd597..53fd6145 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -17,7 +17,9 @@ import { createBotSendTool } from './tools/bot-send.js';
import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';
import { createFleetStatusTool } from './tools/fleet-status.js';
import { createBotSpawnTool } from './tools/bot-spawn.js';
-import { runBotTurn, isTransientFailure, type BotTurnMail } from './bot-turn.js';
+import { runBotTurn, isTransientFailure, type BotTurnMail, type BotActivityEvent } from './bot-turn.js';
+import { parsePersonaAccess, stripPersonaAccessSection } from './persona-access.js';
+import { mergePathScopes } from './registry-factory.js';
import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';
import { SkillLoader } from '../skills/loader.js';
import { logger } from '../utils/logger.js';
@@ -201,10 +203,43 @@ export class BotManager {
const drained = this.queue.drainMail(m.id);
if (drained.length > 0) this.mailboxes.set(m.id, drained);
}
+ // A profile relocation (re-parent or fleet-layout migration) invalidates
+ // the cached journal handle (it is bound to the old dir) and the bot's
+ // compiled toolset.
+ this.store.onRelocate = (botId) => {
+ this.journals.delete(botId);
+ this.invalidateRuntime(botId);
+ };
// Periodic due-sweep: retry-backoff jobs re-enter the in-memory queues
// when their run_after elapses (also covers crash-restart backoffs).
const dueTimer = setInterval(() => this.resumeDueJobs(), 30_000);
dueTimer.unref?.();
+ // Real-time activity consumer registration happens via onBotActivity();
+ // executeTurn feeds every registered listener AND the live `activity`
+ // map (rendered by the /bots roster and fleet_status).
+ }
+
+ /**
+ * Real-time bot activity bus. Every bot turn emits granular events
+ * (turn-start, step, tool start/finish, turn-end); listeners render them —
+ * the CLI bot-thread live region, the web feed, future dashboards. The
+ * manager itself also mirrors the latest label into the `activity` map so
+ * the roster goes live with no extra UI.
+ */
+ private activityListeners = new Set<(ev: BotActivityEvent) => void>();
+ onBotActivity(listener: (ev: BotActivityEvent) => void): () => void {
+ this.activityListeners.add(listener);
+ return () => this.activityListeners.delete(listener);
+ }
+ private emitBotActivity(ev: BotActivityEvent): void {
+ // Live roster label: keep the static job description until the first
+ // step arrives, then follow the actual work.
+ if (ev.kind !== 'turn-end') this.activity.set(ev.botId, ev.label);
+ for (const listener of this.activityListeners) {
+ try { listener(ev); } catch (err: any) {
+ logger.warn({ botId: ev.botId, err: err?.message }, 'Bot activity listener failed');
+ }
+ }
}
/** Pull due (backoff-elapsed) jobs from the durable queue into memory and run them. */
@@ -398,7 +433,11 @@ export class BotManager {
try {
this.queue.claim(job.id, LEASE_SECONDS);
const turn = this.buildTurn(botId, manifest, job, controller.signal);
- const output = await runBotTurn(turn.input);
+ const output = await runBotTurn({
+ ...turn.input,
+ jobId: job.id,
+ onActivity: (ev) => this.emitBotActivity(ev),
+ });
turn.cleanup();
const record: BotRunRecord = {
@@ -551,6 +590,23 @@ export class BotManager {
running.delete(job.id);
this.aborts.delete(`${botId}:${job.id}`);
if (running.size === 0) this.activity.delete(botId);
+ // Mail-arrival race: a reply (e.g. a crew's task result) delivered
+ // while this turn ran can land AFTER the turn's last mailbox poll —
+ // sendToBot saw the bot running and scheduled no wake. Without this,
+ // the mail sits unconsumed and the bot idles forever. If mail is
+ // pending and nothing is queued or running, schedule a wake turn.
+ const manifestNow = this.store.get(botId);
+ if (
+ (this.running.get(botId)?.size ?? 0) === 0
+ && (this.queues.get(botId)?.length ?? 0) === 0
+ && this.peekMailbox(botId).length > 0
+ && manifestNow?.enabled && !this.disabled.has(botId)
+ ) {
+ const q = this.queues.get(botId) ?? [];
+ q.push({ id: randomUUID().slice(0, 8), botId, trigger: 'mailbox', prompt: '', createdAt: Date.now(), attempts: 0 });
+ this.queues.set(botId, q);
+ logger.info({ botId, pending: this.peekMailbox(botId).length }, 'Mail arrived mid-turn — scheduling a wake so it is consumed');
+ }
this.pump(botId);
}
}
@@ -660,22 +716,20 @@ export class BotManager {
botId,
manifest,
botDir: this.store.botDir(botId),
- permissions: this.store.readPermissions(botId),
- // The persona's `## Access` section grants extra path scopes — read at
- // registry build, so a persona edit (invalidateRuntime on write) applies
- // to the very next turn.
- persona: this.store.readPersona(botId),
+ // Single source of truth; also materializes fleet inheritance (a crew
+ // without its own file gets its lead's copied in verbatim).
+ permissions: this.store.ensurePermissions(botId),
skillLoader,
// Built-in work areas: private sandbox + fleet-shared folder (rw+x,
- // implicit — no permission ask, no Access declaration).
+ // implicit — no permission ask).
sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },
userMemory: this.userMemoryFor(botId, manifest),
config: this.config,
});
// Filter FIRST (strips interactive/global-mutation tools and applies the
- // manifest allow/deny), THEN add the bot-specific tools — otherwise the
- // filter would strip them again.
- const filtered = filterBotTools({ ...registry.getTools() }, manifest);
+ // permissions.yaml tool gate), THEN add the bot-specific tools —
+ // otherwise the filter would strip them again.
+ const filtered = filterBotTools({ ...registry.getTools() }, manifest, this.store.ensurePermissions(botId));
// Fleet relations are implicit comms: a lead can message its crew and a
// crew bot its lead, without anyone hand-editing canMessage.
const effectiveRoster = this.effectiveRoster(botId, manifest);
@@ -771,6 +825,9 @@ export class BotManager {
persona: spec.persona,
manifest: { fleetRole: 'crew', parent: leadId, comms: { canMessage: [leadId] } },
});
+ // Inheritance at birth: the crew starts on its lead's permissions,
+ // copied verbatim (its own file from now on — edits diverge it).
+ this.store.ensurePermissions(manifest.id);
this.invalidateRuntime(leadId); // lead's roster + fleet prompt change
logger.info({ leadId, crewId: spec.id }, 'Crew member added to fleet');
return { ok: true, manifest };
@@ -810,13 +867,17 @@ export class BotManager {
*/
async delete(botId: string): Promise<void> {
await this.halt(botId);
- // Fleet cleanup: a deleted LEAD's crew is detached (→ solo), never orphaned
- // with a dangling parent. A deleted crew bot just leaves the roster.
+ // Fleet cascade: deleting a lead deletes its crew — recursively (a crew
+ // member may itself be a mid-level lead). Each member gets the FULL
+ // lifecycle delete (halt, purge queue/mail/DLQ, remove routines) because
+ // those live outside the profile dir and would otherwise outlive the bot.
+ // The filesystem half is free: crew profiles nest inside the lead's dir,
+ // so the lead's store.delete() removes the whole tree — which is also why
+ // this cascades BEFORE the lead's own profile is wiped below.
if (this.store.isLead(botId)) {
for (const crew of this.store.crewOf(botId)) {
- this.store.update(crew.id, m => { m.fleetRole = undefined; m.parent = undefined; });
- this.invalidateRuntime(crew.id);
- logger.info({ leadId: botId, crewId: crew.id }, 'Fleet lead deleted — crew member detached to solo');
+ logger.info({ leadId: botId, crewId: crew.id }, 'Fleet lead deleted — cascading to crew member');
+ await this.delete(crew.id);
}
}
// Scheduler routines (bot:<id>:*) — both bot.yaml routines and
@@ -843,6 +904,64 @@ export class BotManager {
logger.info({ botId }, 'Bot deleted: queue/mail/DLQ purged, routines removed');
}
+ /**
+ * One-shot fleet layout migration (startup, before routines register):
+ * the physical layout must mirror the manifest hierarchy — crew profiles
+ * nested under their lead's dir — so the delete cascade can never leave a
+ * crew behind. Two rules, both idempotent:
+ * 1. A crew bot whose lead no longer exists is cascade-deleted (it
+ * outlived its lead only because a pre-cascade delete created it).
+ * 2. An existing crew profile still flat at the root moves under its
+ * lead's directory (onRelocate refreshes journals/runtime caches).
+ */
+ async migrateFleetLayout(): Promise<void> {
+ for (const m of this.store.list()) {
+ if (!m.parent) continue;
+ if (this.store.exists(m.parent)) {
+ this.store.relocateToParent(m);
+ } else {
+ logger.warn({ botId: m.id, parent: m.parent }, 'Crew bot outlived its lead — cascading the deletion');
+ await this.delete(m.id);
+ }
+ }
+ }
+
+ /**
+ * Permission consolidation to a SINGLE source of truth (startup): every
+ * bot ends with exactly one permissions.yaml and a persona that carries
+ * character only.
+ * 1. Inheritance backfill: a crew without its own file gets its lead's
+ * copied verbatim; a solo without one gets the fail-closed default.
+ * 2. Legacy bot.yaml tools block → permissions.yaml (the manifest copy
+ * stays as a readable fallback but no longer decides anything).
+ * 3. Persona `## Access` grants → merged into permissions.yaml paths,
+ * then stripped from the persona file (permissions never live there).
+ */
+ async migratePermissions(): Promise<void> {
+ for (const m of this.store.list()) {
+ try {
+ const perms = this.store.ensurePermissions(m.id);
+ // 2. Legacy tool gate out of bot.yaml.
+ const legacyTools = m.tools;
+ if (legacyTools && ((legacyTools.allow?.length ?? 0) > 0 || (legacyTools.deny?.length ?? 0) > 0) && !perms.tools) {
+ this.store.writePermissions(m.id, { ...this.store.readPermissions(m.id), tools: legacyTools });
+ logger.info({ botId: m.id }, 'Migrated bot.yaml tools gate into permissions.yaml (single source of truth)');
+ }
+ // 3. Persona Access grants out of the persona.
+ const persona = this.store.readPersona(m.id);
+ const grants = parsePersonaAccess(persona);
+ if (grants.length > 0) {
+ const current = this.store.readPermissions(m.id);
+ this.store.writePermissions(m.id, { ...current, paths: mergePathScopes(current.paths, grants) });
+ this.store.writePersona(m.id, stripPersonaAccessSection(persona));
+ logger.info({ botId: m.id, grants: grants.length }, 'Migrated persona Access grants into permissions.yaml; persona is character-only now');
+ }
+ } catch (err: any) {
+ logger.warn({ botId: m.id, err: err?.message }, 'Permission migration failed for bot — leaving as-is');
+ }
+ }
+ }
+
/**
* Register every enabled bot's cron routines with the main Scheduler
* (manifest id `bot:<botId>:<name>`). Bot runs fire on the cron lane and
@@ -901,32 +1020,56 @@ export class BotManager {
* jobs stay durable-pending (survive a restart); the passive due-sweep
* skips held bots, so nothing resumes until /bots start. Explicit new
* triggers (send/mail/cron) still work — the bot is stopped, not disabled.
+ * FLEET: stopping a lead stops its crew too — recursively (a crew member
+ * may be a mid-level lead). Every stopped member's jobs are held the same
+ * durable way; /bots start on the lead resumes the whole subtree.
*/
- async stop(botId: string): Promise<{ halted: boolean; heldJobs: number }> {
- const heldJobs = (this.queues.get(botId) ?? []).length;
- const halted = await this.halt(botId);
+ async stop(botId: string): Promise<{ halted: boolean; heldJobs: number; crewStopped: number }> {
+ let heldJobs = (this.queues.get(botId) ?? []).length;
+ let halted = await this.halt(botId);
this.held.add(botId);
+ let crewStopped = 0;
+ if (this.store.isLead(botId)) {
+ for (const crew of this.store.crewOf(botId)) {
+ const r = await this.stop(crew.id);
+ halted = halted || r.halted;
+ heldJobs += r.heldJobs;
+ crewStopped += 1 + r.crewStopped;
+ }
+ }
if (heldJobs > 0) {
- logger.info({ botId, heldJobs }, 'Bot stopped — queued jobs held (resumable via /bots start)');
+ logger.info({ botId, heldJobs, crewStopped }, 'Bot stopped — queued jobs held (resumable via /bots start)');
}
- return { halted, heldJobs };
+ return { halted, heldJobs, crewStopped };
}
/**
* User-facing resume (the counterpart of stop): clear the stop-hold,
* re-enter held/pending durable jobs, and kick the queue. A disabled bot
* is enabled first — "start" is unambiguous. Safe on an already-running bot.
+ * FLEET: starting a lead resumes its crew subtree too (recursively) —
+ * except crew the user individually disabled, which stay off.
*/
start(botId: string): { resumed: number } {
const manifest = this.store.get(botId);
if (!manifest) throw new Error(`Bot "${botId}" does not exist`);
this.held.delete(botId);
- const resumed = this.rehydratePending(botId);
+ let resumed = this.rehydratePending(botId);
if (!manifest.enabled || this.disabled.has(botId)) {
this.setEnabled(botId, true); // persists enabled + pumps
} else {
this.pump(botId);
}
+ if (this.store.isLead(botId)) {
+ for (const crew of this.store.crewOf(botId)) {
+ const m = this.store.get(crew.id);
+ if (!m?.enabled || this.disabled.has(crew.id)) continue; // explicitly disabled crew stay off
+ this.held.delete(crew.id);
+ resumed += this.rehydratePending(crew.id);
+ this.pump(crew.id);
+ resumed += this.start(crew.id).resumed;
+ }
+ }
return { resumed };
}
@@ -1071,6 +1214,7 @@ export class BotManager {
- \`/bot <id> <message>\` or \`@<id> <message>\` — dispatch a task to a bot; the result lands ONLY in the bot's own thread (\`/bots open <id>\`), never in this chat.
- \`/bots open <id>\` — open the bot's own chat; \`/bots\` — roster with live states.
- \`/bots create <id> "Name" "Description"\` — onboard; \`/bots persona <id> <text>\` — set its character.
+- \`/bots export <id> [path]\` — shareable bundle (manifests + personas + permissions + skills; a lead's bundle carries its whole crew); \`/bots import <path>\` — recreate bots from a bundle (imported bots start disabled). Sandbox, journals, and .env never travel.
- \`/bots journal <id>\` — recent runs; \`/bots dlq\` — failed jobs (replayable); \`/bots stop|start|enable|disable <id>\`; \`/bots run <id> [routine]\` — fire a routine now (or a bare wake).
- Bots share data through the fleet-shared folder (\`${this.store.sharedSandboxDir()}\`); each also has a private sandbox next to its persona. Their outputs land in their own threads.
- The dispatch_bot tool lets you hand a task to a bot mid-conversation and continue talking; the result is delivered when the bot finishes.`);
diff --git a/src/bots/bot-turn.test.ts b/src/bots/bot-turn.test.ts
new file mode 100644
index 00000000..9ff5b740
--- /dev/null
+++ b/src/bots/bot-turn.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// Mock only generateText; stepCountIs must stay real so the turn loop's
+// per-round step budget still applies. The mock must drive onStepFinish
+// itself — that is the AI-SDK callback that decrements the budget.
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>();
+ return {
+ ...actual,
+ generateText: vi.fn(),
+ };
+});
+
+import { generateText } from 'ai';
+import { runBotTurn, classifyFailure, type BotTurnInput } from './bot-turn.js';
+import { MAX_AUTOMATIC_CONTINUATIONS } from '../core/execution-limits.js';
+
+const mockedGenerateText = vi.mocked(generateText);
+
+function turnInput(overrides: Record<string, unknown> = {}): Parameters<typeof runBotTurn>[0] {
+ return {
+ manifest: {
+ id: 'tester',
+ name: 'Tester',
+ enabled: true,
+ autonomy: { maxSteps: 2 },
+ } as any,
+ trigger: 'chat',
+ prompt: 'do the work',
+ persona: 'test persona',
+ mail: [],
+ pollMail: () => [],
+ sandbox: { workspace: '/tmp/ws', shared: '/tmp/shared' },
+ capabilities: {} as any,
+ tools: {},
+ userMemory: null,
+ provider: {
+ name: 'stub',
+ getModel: () => 'stub-model',
+ getModelInstance: () => ({}),
+ } as any,
+ tokenBudget: { recordUsage: () => {}, getRemaining: () => 100000 } as any,
+ abortSignal: new AbortController().signal,
+ ...overrides,
+ } as any;
+}
+
+beforeEach(() => {
+ mockedGenerateText.mockReset();
+});
+
+describe('runBotTurn step-budget continuation', () => {
+ it('continues in-process with a fresh budget instead of pausing, preserving the conversation', async () => {
+ // Round 1: burns the 2-step budget with tool calls still pending.
+ // Round 2: finishes with text.
+ mockedGenerateText
+ .mockImplementationOnce(async (opts: any) => {
+ opts.onStepFinish?.({ usage: { inputTokens: 5, outputTokens: 2 }, toolCalls: [{ toolName: 'fs_write' }] });
+ opts.onStepFinish?.({ usage: { inputTokens: 5, outputTokens: 2 }, toolCalls: [{ toolName: 'fs_write' }] });
+ return { text: '', finishReason: 'tool-calls', usage: { inputTokens: 10, outputTokens: 4 } } as any;
+ })
+ .mockImplementationOnce(async (opts: any) => {
+ opts.onStepFinish?.({ usage: { inputTokens: 5, outputTokens: 2 }, toolCalls: [] });
+ return { text: 'all done', finishReason: 'stop', usage: { inputTokens: 5, outputTokens: 2 } } as any;
+ });
+
+ const output = await runBotTurn(turnInput());
+
+ expect(output.status).toBe('completed');
+ expect(output.output).toBe('all done');
+ expect(mockedGenerateText).toHaveBeenCalledTimes(2);
+ // Tool usage from the pre-refill round is still attributed.
+ expect(output.toolsUsed).toEqual(['fs_write']);
+ expect(output.tokensIn).toBe(15);
+
+ // The resume nudge carries the SAME conversation forward (messages grow,
+ // not rebuild) and tells the model not to re-wrap the task.
+ const secondCall = mockedGenerateText.mock.calls[1][0] as any;
+ const nudges = secondCall.messages.filter((m: any) => String(m.content).includes('[SYSTEM: STEP BUDGET]'));
+ expect(nudges).toHaveLength(1);
+ });
+
+ it('stays bounded: past the continuation bound it returns paused with step_budget', async () => {
+ mockedGenerateText.mockImplementation(async (opts: any) => {
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'fs_write' }] });
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [{ toolName: 'fs_write' }] });
+ return { text: '', finishReason: 'tool-calls', usage: { inputTokens: 2, outputTokens: 2 } } as any;
+ });
+
+ const output = await runBotTurn(turnInput());
+
+ expect(output.status).toBe('paused');
+ expect(output.reasonCode).toBe('step_budget');
+ // Initial budget + one refill per continuation round.
+ expect(mockedGenerateText).toHaveBeenCalledTimes(MAX_AUTOMATIC_CONTINUATIONS + 1);
+ });
+
+ it('network blips classify as transient (retryable), not unknown_error', () => {
+ // The live failure that shipped a lead bot to the DLQ with a needs-you
+ // flag: "Cannot connect to API: read ECONNRESET" — a plain connection
+ // drop that fell through every transient pattern.
+ expect(classifyFailure(new Error('Cannot connect to API: read ECONNRESET'))).toBe('provider_timeout');
+ expect(classifyFailure(new Error('getaddrinfo ENOTFOUND api.example.com'))).toBe('provider_timeout');
+ expect(classifyFailure(new Error('fetch failed: ECONNREFUSED 1.2.3.4:443'))).toBe('provider_timeout');
+ // Still-permanent things stay permanent.
+ expect(classifyFailure(new Error('401 unauthorized'))).toBe('provider_auth');
+ expect(classifyFailure(new Error('permission denied by policy'))).toBe('permission_denied');
+ });
+
+ it('an aborted turn during continuation still reports halted, not paused', async () => {
+ const controller = new AbortController();
+ mockedGenerateText
+ .mockImplementationOnce(async (opts: any) => {
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [] });
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [] });
+ return { text: '', finishReason: 'tool-calls' } as any;
+ })
+ .mockImplementationOnce(async () => {
+ controller.abort();
+ throw new Error('Request was aborted');
+ });
+
+ const output = await runBotTurn(turnInput({ abortSignal: controller.signal }));
+
+ expect(output.status).toBe('halted');
+ });
+});
\ No newline at end of file
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index b7a6e33f..c6f6aab5 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -5,6 +5,9 @@ import type { UserMemoryStore } from '../memory/user-memory.js';
import type { TokenBudget } from '../utils/tokens.js';
import type { BaseProvider } from '../providers/base.js';
import { classifyStreamCompletion } from '../core/stream-completion.js';
+import { stepsExhaustedPrompt } from '../core/completion-verdict.js';
+import { MAX_AUTOMATIC_CONTINUATIONS } from '../core/execution-limits.js';
+import { formatToolStep } from '../utils/tool-label.js';
import { logger } from '../utils/logger.js';
import type { BotManifest, BotTrigger } from './types.js';
@@ -14,9 +17,28 @@ export interface BotTurnMail {
content: string;
}
+/**
+ * Real-time bot activity event — what the bot is doing RIGHT NOW. Emitted at
+ * AI SDK callback granularity (step start, tool call start/finish) so the
+ * surfaces can show live work instead of the coarse idle/running states.
+ */
+export type BotActivityEvent = {
+ botId: string;
+ jobId: string;
+ kind: 'turn-start' | 'step' | 'tool' | 'turn-end';
+ /** Human-readable: "read_file ~/cookies" / "step 4 · 12.3k tok in". */
+ label: string;
+ detail?: string;
+ stepIndex: number;
+ elapsedMs: number;
+ status?: 'running' | 'done' | 'error';
+};
+
export interface BotTurnInput {
manifest: BotManifest;
trigger: BotTrigger;
+ /** Durable job id — correlates activity events with the run. */
+ jobId?: string;
prompt: string;
persona: string;
/** Pending mailbox messages at turn start (attributed bot-to-bot handoffs). */
@@ -40,6 +62,8 @@ export interface BotTurnInput {
provider: BaseProvider;
tokenBudget: TokenBudget;
abortSignal: AbortSignal;
+ /** Real-time activity consumer (roster, live regions, web feed). */
+ onActivity?: (ev: BotActivityEvent) => void;
}
export interface BotTurnOutput {
@@ -82,9 +106,29 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
let tokensOut = 0;
let lastResult: any = null;
let stepsRemaining = maxSteps;
+ let budgetContinuations = 0;
+ let stepIndex = 0;
+ const turnStartedAt = Date.now();
const toolsUsed = new Set<string>();
+ const onActivity = input.onActivity;
+ const emit = (ev: { kind: BotActivityEvent['kind']; label: string; detail?: string; stepIndex: number; status?: BotActivityEvent['status']; elapsedMs?: number }): void => {
+ if (!onActivity) return;
+ try {
+ onActivity({
+ botId: manifest.id,
+ jobId: input.jobId ?? '',
+ elapsedMs: ev.elapsedMs ?? Date.now() - turnStartedAt,
+ kind: ev.kind,
+ label: ev.label,
+ detail: ev.detail,
+ stepIndex: ev.stepIndex,
+ status: ev.status,
+ });
+ } catch { /* activity feedback must never break a turn */ }
+ };
try {
+ emit({ kind: 'turn-start', stepIndex: 0, label: input.prompt ? input.prompt.slice(0, 80) : 'Checking inbox' });
while (stepsRemaining > 0 && !abortSignal.aborted) {
const result = await generateText({
model: provider.getModelInstance(),
@@ -94,6 +138,25 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
stopWhen: stepCountIs(stepsRemaining),
abortSignal,
experimental_include: { requestBody: false, responseBody: false },
+ experimental_onStepStart: () => {
+ stepIndex++;
+ emit({ kind: 'step', stepIndex, label: `step ${stepIndex}` });
+ },
+ experimental_onToolCallStart: ({ toolCall }: any) => {
+ const label = formatToolStep(String(toolCall?.toolName ?? 'tool'), (toolCall?.input ?? {}) as Record<string, any>);
+ emit({ kind: 'tool', stepIndex, label, status: 'running' });
+ },
+ experimental_onToolCallFinish: ({ toolCall, success, error, durationMs }: any) => {
+ const label = formatToolStep(String(toolCall?.toolName ?? 'tool'), (toolCall?.input ?? {}) as Record<string, any>);
+ emit({
+ kind: 'tool',
+ stepIndex,
+ label,
+ detail: error != null ? String(error?.message ?? error).slice(0, 200) : undefined,
+ status: success ? 'done' : 'error',
+ elapsedMs: typeof durationMs === 'number' ? durationMs : undefined,
+ });
+ },
onStepFinish: ({ usage, toolCalls }) => {
if (abortSignal.aborted) return;
stepsRemaining--;
@@ -104,6 +167,8 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
for (const tc of toolCalls ?? []) {
if (tc?.toolName) toolsUsed.add(String(tc.toolName));
}
+ const kIn = Math.round(tokensIn / 100) / 10;
+ emit({ kind: 'step', stepIndex, label: `step ${stepIndex} · ${kIn}k tok in` });
},
});
lastResult = result;
@@ -121,6 +186,28 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
messages.push({ role: 'assistant', content: result.text });
}
+ // Step budget exhausted with tool calls still pending is a PAUSE, never
+ // a completion (sub-agent completion contract). Mirror the main agent's
+ // bounded auto-continuation: refill the budget and resume the SAME
+ // conversation in-process — the old path requeued the job and rebuilt
+ // the turn from scratch, discarding every completed step and re-burning
+ // the budget redoing the first 25 steps. The per-bot daily token
+ // budget remains the runaway guard; past the continuation bound the
+ // paused return below still applies.
+ if (stepsRemaining <= 0 && (lastResult as any)?.finishReason === 'tool-calls') {
+ if (!abortSignal.aborted && budgetContinuations < MAX_AUTOMATIC_CONTINUATIONS) {
+ budgetContinuations++;
+ logger.warn(
+ { botId: manifest.id, rounds: budgetContinuations, budget: maxSteps },
+ 'Bot step budget exhausted mid-turn — continuing with a fresh budget',
+ );
+ messages.push({ role: 'user', content: stepsExhaustedPrompt(input.prompt) });
+ stepsRemaining = maxSteps;
+ continue;
+ }
+ break;
+ }
+
// Consume newly arrived mailbox messages before finishing, so a
// handoff delivered mid-turn is not lost to the next scheduling gap.
if (!abortSignal.aborted && stepsRemaining > 0) {
@@ -141,7 +228,9 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
// Step budget exhausted with tool calls still pending — pause, never
// report success on half-done work (sub-agent completion contract).
+ // Last resort only: reached past the in-process continuation bound.
if (stepsRemaining <= 0 && (lastResult as any)?.finishReason === 'tool-calls') {
+ emit({ kind: 'turn-end', stepIndex, label: 'paused — step budget', status: 'done' });
return {
status: 'paused',
output: 'Step budget reached before the turn completed — remaining work continues next turn.',
@@ -163,11 +252,14 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
channelType: 'bot',
});
+ emit({ kind: 'turn-end', stepIndex, label: 'completed', status: 'done' });
return { status: 'completed', output, tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
} catch (err: any) {
if (abortSignal.aborted) {
+ emit({ kind: 'turn-end', stepIndex, label: 'halted', status: 'done' });
return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
}
+ emit({ kind: 'turn-end', stepIndex, label: `failed: ${String(err?.message ?? err).slice(0, 80)}`, status: 'error' });
return {
status: 'failed',
output: `Turn failed: ${err?.message ?? String(err)}`,
@@ -184,7 +276,11 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
export function classifyFailure(err: any): string {
const msg = String(err?.message ?? err ?? '').toLowerCase();
if (/rate.?limit|429|too many requests/.test(msg)) return 'provider_rate_limit';
- if (/timeout|etimedout|econnaborted|socket hang up/.test(msg)) return 'provider_timeout';
+ // Network blips ARE transient — ECONNRESET (connection dropped mid-read)
+ // and friends used to fall through to unknown_error, so a plain
+ // connection blip went straight to the DLQ with a needs-you flag instead
+ // of retrying like every other transient failure.
+ if (/timeout|etimedout|econnaborted|econnreset|econnrefused|epipe|enotfound|eai_again|getaddrinfo|fetch failed|socket hang up|network/.test(msg)) return 'provider_timeout';
if (/permission denied|blocked command|no permission/.test(msg)) return 'permission_denied';
if (/api key|unauthorized|401|authentication/.test(msg)) return 'provider_auth';
if (/quota|billing|402/.test(msg)) return 'provider_quota';
diff --git a/src/bots/bundle.test.ts b/src/bots/bundle.test.ts
new file mode 100644
index 00000000..e66eb6ba
--- /dev/null
+++ b/src/bots/bundle.test.ts
@@ -0,0 +1,124 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>();
+ return { ...actual, generateText: vi.fn() };
+});
+
+import { BotStore } from './store.js';
+import { buildBotBundle, importBotBundle, readBundle, writeBundle, type BotBundle } from './bundle.js';
+
+function freshRoot(): { root: string; store: BotStore } {
+ const root = mkdtempSync(join(tmpdir(), 'mercury-bundle-'));
+ return { root, store: new BotStore(join(root, 'bots')) };
+}
+
+describe('bot bundles (plug-and-play import/export)', () => {
+ let root: string;
+ let store: BotStore;
+
+ beforeEach(() => {
+ ({ root, store } = freshRoot());
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('exports a solo bot: manifest + persona + permissions, none of the local state', () => {
+ store.create({ id: 'writer', name: 'Writer', description: 'Writes things' });
+ store.writePermissions('writer', { paths: [{ scope: '~', read: true }], tools: { deny: ['git_push'] } });
+ store.writePersona('writer', '# Writer\n\nSpare prose.\n');
+ writeFileSync(join(store.sandboxDir('writer'), 'scratch.txt'), 'local state');
+ writeFileSync(join(store.botDir('writer'), '.env'), 'SECRET=1');
+
+ const bundle = buildBotBundle(store, 'writer');
+
+ expect(bundle.format).toBe('mercury-bot-bundle');
+ expect(bundle.kind).toBe('bot');
+ expect(bundle.root).toBe('writer');
+ expect(bundle.bots).toHaveLength(1);
+ expect(bundle.bots[0].persona).toContain('Spare prose');
+ expect(bundle.bots[0].permissions.paths).toEqual([{ scope: '~', read: true }]);
+ expect(bundle.bots[0].manifest.createdAt).toBeUndefined();
+ expect(JSON.stringify(bundle)).not.toContain('local state');
+ expect(JSON.stringify(bundle)).not.toContain('SECRET');
+ // The tool gate travels in its own block (single source of truth).
+ expect(bundle.bots[0].manifest.tools).toBeUndefined();
+ });
+
+ it('a fleet lead exports its whole crew tree, lead-first (DFS)', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'eng', name: 'Eng', manifest: { fleetRole: 'lead', parent: 'ceo' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'crew', parent: 'eng' } });
+ store.create({ id: 'qa', name: 'QA', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+
+ const bundle = buildBotBundle(store, 'ceo');
+ expect(bundle.kind).toBe('fleet');
+ expect(bundle.bots.map(b => b.id)).toEqual(['ceo', 'eng', 'backend', 'qa']);
+ expect(bundle.bots.find(b => b.id === 'backend')!.manifest.parent).toBe('eng');
+ });
+
+ it('a crew exported alone keeps its parent field (import resolves against the destination)', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'crewmate', name: 'Crewmate', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ const bundle = buildBotBundle(store, 'crewmate');
+ expect(bundle.kind).toBe('bot');
+ expect(bundle.bots[0].manifest.parent).toBe('ceo');
+ });
+
+ it('round-trips: export from one store, import into a fresh one — layout, persona, permissions intact', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.writePermissions('ceo', { paths: [{ scope: '~', read: true, write: true, execute: true }], autoApproveCommands: ['node *'] });
+ store.writePersona('ceo', '# CEO\n\nDecisive.\n');
+ store.create({ id: 'eng', name: 'Eng', manifest: { fleetRole: 'lead', parent: 'ceo' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'crew', parent: 'eng' } });
+ store.writePersona('backend', '# Backend\n\nShips APIs.\n');
+
+ const bundle = buildBotBundle(store, 'ceo');
+ const path = writeBundle(bundle, join(root, 'share', 'ceo.bot.json'));
+ expect(existsSync(path)).toBe(true);
+ const parsed = readBundle(path) as BotBundle;
+
+ const dest = new BotStore(join(root, 'dest', 'bots'));
+ const report = importBotBundle(dest, parsed);
+ expect(report.created.sort()).toEqual(['backend', 'ceo', 'eng']);
+ // Physical fleet layout recreated exactly.
+ expect(existsSync(join(root, 'dest', 'bots', 'ceo', 'eng', 'backend', 'bot.yaml'))).toBe(true);
+ // Persona + permissions (single source of truth) carried verbatim.
+ expect(dest.readPersona('backend')).toContain('Ships APIs');
+ expect(dest.readPermissions('ceo').autoApproveCommands).toEqual(['node *']);
+ expect(dest.readPermissions('ceo').paths![0].execute).toBe(true);
+ // Fail-closed: imported bots start DISABLED.
+ expect(dest.get('ceo')!.enabled).toBe(false);
+ // Crew nesting survived via the manifests.
+ expect(dest.crewOf('ceo').map(m => m.id).sort()).toEqual(['eng']);
+ });
+
+ it('skips existing ids (never clobbers a running bot) unless overwrite is set', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.writePersona('ceo', '# CEO\n\nOriginal persona.\n');
+ const bundle = buildBotBundle(store, 'ceo');
+
+ const dest = new BotStore(join(root, 'dest', 'bots'));
+ dest.create({ id: 'ceo', name: 'Local CEO' });
+ dest.writePersona('ceo', '# CEO\n\nLocal persona.\n');
+
+ const report = importBotBundle(dest, bundle);
+ expect(report.created).toEqual([]);
+ expect(report.skipped[0].reason).toContain('already exists');
+ expect(dest.readPersona('ceo')).toContain('Local persona');
+
+ importBotBundle(dest, bundle, { overwrite: true });
+ expect(dest.readPersona('ceo')).toContain('Original persona');
+ // Enabled state survives an overwrite refresh (never force-disabled).
+ expect(dest.get('ceo')!.enabled).toBe(true);
+ });
+
+ it('rejects foreign documents loudly', () => {
+ expect(() => importBotBundle(store, { hello: 'world' } as unknown as BotBundle)).toThrow(/Not a Mercury bot bundle/);
+ });
+});
\ No newline at end of file
diff --git a/src/bots/bundle.ts b/src/bots/bundle.ts
new file mode 100644
index 00000000..efe3dba9
--- /dev/null
+++ b/src/bots/bundle.ts
@@ -0,0 +1,238 @@
+import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+import type { BotStore } from './store.js';
+import type { BotManifest, BotPermissionsFile } from './types.js';
+
+/**
+ * Bot bundles — plug-and-play import/export (ADR-012 extension).
+ *
+ * A bundle is ONE transport-agnostic JSON document describing a bot or a
+ * whole fleet: manifests, personas, and permissions. It is what makes the
+ * on-disk fleet layout shareable and recreatable anywhere Mercury runs —
+ * the CLI today, the local web dashboard, Mercury Code, or a third-party
+ * site using Mercury as its agent backend (the same document can arrive via
+ * file upload, HTTP POST, or paste).
+ *
+ * What is INCLUDED (the bot's identity + behavior):
+ * bot.yaml (sanitized), persona.md, permissions.yaml, skills/*.md
+ * What is NEVER included (local state and secrets — they do not travel):
+ * sandbox/, journal.jsonl*, .env
+ *
+ * Fleet shape mirrors the physical layout: the lead is the bundle root; crew
+ * entries keep their `parent` fields, which import resolves against ids
+ * INSIDE the bundle (a crew exported alone exports as a solo — its lead did
+ * not travel with it).
+ */
+
+export const BOT_BUNDLE_FORMAT = 'mercury-bot-bundle';
+export const BOT_BUNDLE_VERSION = 1;
+
+export interface BotBundleEntry {
+ id: string;
+ name: string;
+ description?: string;
+ /** Sanitized bot.yaml content (volatile fields stripped). */
+ manifest: Record<string, unknown>;
+ persona: string;
+ /** The single source of truth for permissions, as-is. */
+ permissions: BotPermissionsFile;
+ /** Skill files (name → text content) when export included skills. */
+ skills?: Record<string, string>;
+}
+
+export interface BotBundle {
+ format: typeof BOT_BUNDLE_FORMAT;
+ version: number;
+ kind: 'bot' | 'fleet';
+ /** The bundle's entry-point bot id. */
+ root: string;
+ exportedAt: string;
+ /** Lead-first, parents-before-children order. */
+ bots: BotBundleEntry[];
+}
+
+export interface BundleImportReport {
+ created: string[];
+ skipped: Array<{ id: string; reason: string }>;
+}
+
+/** Manifest fields that describe THIS machine's runtime, not the bot. */
+const VOLATILE_MANIFEST_FIELDS = ['createdAt', 'updatedAt'];
+
+/**
+ * Build a shareable bundle from a bot — or, for a fleet lead, the lead plus
+ * its whole crew tree (recursively, matching the nested directory layout).
+ */
+export function buildBotBundle(store: BotStore, rootId: string, opts: { withSkills?: boolean } = {}): BotBundle {
+ const root = store.get(rootId);
+ if (!root) throw new Error(`No bot "${rootId}"`);
+ const bots: BotBundleEntry[] = [];
+ const collect = (id: string): void => {
+ const m = store.get(id);
+ if (!m) return;
+ const entry: BotBundleEntry = {
+ id: m.id,
+ name: m.name,
+ description: m.description,
+ manifest: sanitizeManifest(m),
+ persona: store.readPersona(id),
+ permissions: store.ensurePermissions(id),
+ };
+ if (opts.withSkills) entry.skills = collectSkills(store.skillsDir(id));
+ bots.push(entry);
+ for (const crew of store.crewOf(id)) collect(crew.id);
+ };
+ collect(rootId);
+ return {
+ format: BOT_BUNDLE_FORMAT,
+ version: BOT_BUNDLE_VERSION,
+ kind: bots.length > 1 ? 'fleet' : 'bot',
+ root: rootId,
+ exportedAt: new Date().toISOString(),
+ bots,
+ };
+}
+
+/**
+ * Recreate bots from a bundle into this store. Every imported bot starts
+ * DISABLED (fail-closed: a shared bundle must never begin firing cron
+ * routines or spending tokens unattended — enable consciously with
+ * /bots enable). Existing ids are skipped (never overwritten) unless
+ * opts.overwrite refreshes persona/permissions in place. Fleet nesting
+ * falls out of the manifests' parent fields via the store's physical
+ * layout; imports of a single crew bot arrive parentless (solo).
+ */
+export function importBotBundle(
+ store: BotStore,
+ bundle: BotBundle,
+ opts: { overwrite?: boolean } = {},
+): BundleImportReport {
+ assertValidBundle(bundle);
+ const report: BundleImportReport = { created: [], skipped: [] };
+ // Parents before children: our builder already emits lead-first; enforce
+ // it defensively so a hand-built bundle cannot create a child before its
+ // parent's directory exists.
+ for (const entry of orderedRootsFirst(bundle.bots, bundle.root)) {
+ const exists = store.exists(entry.id);
+ if (exists && !opts.overwrite) {
+ report.skipped.push({ id: entry.id, reason: 'already exists (use overwrite to refresh persona/permissions)' });
+ continue;
+ }
+ if (!exists) {
+ store.create({
+ id: entry.id,
+ name: entry.name,
+ description: entry.description,
+ persona: entry.persona,
+ manifest: { ...entry.manifest, enabled: false } as Partial<BotManifest>,
+ });
+ } else if (opts.overwrite) {
+ store.update(entry.id, m => {
+ m.name = entry.name;
+ m.description = entry.description;
+ for (const [k, v] of Object.entries(entry.manifest)) {
+ if (k === 'enabled' || k === 'id' || k === 'name') continue;
+ (m as any)[k] = v;
+ }
+ m.enabled = store.get(entry.id)?.enabled ?? false;
+ });
+ }
+ store.writePersona(entry.id, entry.persona);
+ store.writePermissions(entry.id, entry.permissions);
+ for (const [relPath, content] of Object.entries(entry.skills ?? {})) {
+ const target = join(store.skillsDir(entry.id), relPath);
+ mkdirSync(resolve(target, '..'), { recursive: true });
+ writeFileSync(target, content, 'utf-8');
+ }
+ if (!exists) report.created.push(entry.id);
+ else report.skipped.push({ id: entry.id, reason: 'existing bot refreshed (overwrite)' });
+ }
+ logger.info({ root: bundle.root, created: report.created.length, skipped: report.skipped.length }, 'Bot bundle imported');
+ return report;
+}
+
+/** Structural validation — never throws on content, only on shape. */
+function assertValidBundle(bundle: BotBundle): void {
+ if (!bundle || bundle.format !== BOT_BUNDLE_FORMAT) {
+ throw new Error(`Not a Mercury bot bundle (expected format "${BOT_BUNDLE_FORMAT}")`);
+ }
+ if (bundle.version !== BOT_BUNDLE_VERSION) {
+ throw new Error(`Unsupported bundle version ${bundle.version} (this Mercury reads v${BOT_BUNDLE_VERSION})`);
+ }
+ if (!Array.isArray(bundle.bots) || bundle.bots.length === 0 || !bundle.bots.some(b => b.id === bundle.root)) {
+ throw new Error('Bundle is missing its bots or its root entry');
+ }
+}
+
+function sanitizeManifest(m: BotManifest): Record<string, unknown> {
+ const out: Record<string, unknown> = { ...m } as any;
+ for (const field of VOLATILE_MANIFEST_FIELDS) delete out[field];
+ // Permissions travel in their own block (single source of truth) — the
+ // legacy manifest copy is dropped so the file, not bot.yaml, decides.
+ delete out.tools;
+ return out;
+}
+
+/** Defensive topological order: every bot after its bundle parent (cycles tolerated → appended, then rejected by save's cycle guard). */
+function orderedRootsFirst(entries: BotBundleEntry[], _root: string): BotBundleEntry[] {
+ const pending = new Set(entries.map(e => e.id));
+ const out: BotBundleEntry[] = [];
+ const emit = (entry: BotBundleEntry): void => {
+ if (!pending.has(entry.id)) return;
+ pending.delete(entry.id);
+ out.push(entry);
+ const parent = entry.manifest.parent as string | undefined;
+ if (parent) {
+ const lead = entries.find(e => e.id === parent);
+ if (lead) emit(lead);
+ }
+ };
+ for (const entry of entries) emit(entry);
+ for (const id of pending) out.push(entries.find(e => e.id === id)!);
+ return out;
+}
+
+/** Default export location: ~/.mercury/exports/<id>.bot.json */
+export function defaultBundlePath(rootId: string): string {
+ const dir = join(getMercuryHome(), 'exports');
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
+ return join(dir, `${rootId}.bot.json`);
+}
+
+export function writeBundle(bundle: BotBundle, outPath?: string): string {
+ const path = outPath ?? defaultBundlePath(bundle.root);
+ mkdirSync(resolve(path, '..'), { recursive: true });
+ writeFileSync(path, JSON.stringify(bundle, null, 2), 'utf-8');
+ return path;
+}
+
+export function readBundle(path: string): BotBundle {
+ return JSON.parse(readFileSync(path, 'utf-8')) as BotBundle;
+}
+
+/** Recurse a skills dir into {relativePath: textContent} (md/json/yaml only). */
+function collectSkills(dir: string, prefix = ''): Record<string, string> {
+ const out: Record<string, string> = {};
+ if (!existsSync(dir)) return out;
+ for (const entry of readdirSafe(dir)) {
+ if (entry.isDirectory() && !entry.name.startsWith('.') && !entry.name.startsWith('_')) {
+ Object.assign(out, collectSkills(join(dir, entry.name), join(prefix, entry.name)));
+ } else if (entry.isFile() && /\.(md|json|ya?ml|txt)$/i.test(entry.name) && entry.name !== '.env') {
+ try {
+ const content = readFileSync(join(dir, entry.name), 'utf-8');
+ if (content.length <= 256 * 1024) out[join(prefix, entry.name)] = content;
+ } catch { /* unreadable skill file → skipped */ }
+ }
+ }
+ return out;
+}
+
+function readdirSafe(dir: string): Array<{ name: string; isDirectory(): boolean; isFile(): boolean }> {
+ try {
+ return readdirSync(dir, { withFileTypes: true }) as any;
+ } catch {
+ return [];
+ }
+}
\ No newline at end of file
diff --git a/src/bots/fleet-delegation.test.ts b/src/bots/fleet-delegation.test.ts
new file mode 100644
index 00000000..cdcaef90
--- /dev/null
+++ b/src/bots/fleet-delegation.test.ts
@@ -0,0 +1,183 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+// Mock only generateText; tool()/zodSchema/stepCountIs stay real so the
+// bot_send / fleet tools construct through the real registry factories.
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>();
+ return { ...actual, generateText: vi.fn() };
+});
+
+import { generateText } from 'ai';
+import { BotManager } from './bot-manager.js';
+import { BotStore } from './store.js';
+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';
+
+const mockedGenerateText = vi.mocked(generateText);
+
+function makeManager(root: string): BotManager {
+ const config = getDefaultConfig() as MercuryConfig;
+ config.bots.maxConcurrent = 4;
+ return new BotManager({
+ config,
+ providers: {
+ get: () => undefined,
+ getDefault: () => ({
+ name: 'stub', model: 'stub-model',
+ generateText: async () => ({ text: 'ok', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub-model', provider: 'stub' }),
+ streamText: async function* () { yield { text: 'ok', done: true }; },
+ isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub-model',
+ } as any),
+ } as any,
+ tokenBudget: { recordUsage: () => {}, getRemaining: () => 100000, getStatusText: () => '', getUsagePercentage: () => 0 } as any,
+ store: new BotStore(join(root, 'bots')),
+ userMemoryFactory: () => null,
+ });
+}
+
+beforeEach(() => {
+ mockedGenerateText.mockReset();
+});
+
+describe('fleet delegation lights up crew status', () => {
+ let root: string;
+ let manager: BotManager;
+ let store: BotStore;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-delegation-'));
+ manager = makeManager(root);
+ store = manager['store'];
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('emits real-time activity events per step/tool and mirrors them into the roster activity', async () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'busy', name: 'Busy', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+
+ const events: Array<{ kind: string; label: string }> = [];
+ manager.onBotActivity(ev => events.push({ kind: ev.kind, label: ev.label }));
+
+ mockedGenerateText.mockImplementation(async (opts: any) => {
+ if (JSON.stringify(opts?.messages ?? '').includes('do the work')) {
+ await new Promise(r => setTimeout(r, 120));
+ // Drive the AI SDK callbacks the real generateText would fire.
+ opts.experimental_onStepStart?.();
+ opts.onStepFinish?.({ usage: { inputTokens: 900, outputTokens: 100 }, toolCalls: [] });
+ return { text: 'done', finishReason: 'stop', usage: { inputTokens: 900, outputTokens: 100 } } as any;
+ }
+ manager.dispatchTask('busy', 'ceo', 'do the work');
+ opts.experimental_onStepStart?.();
+ opts.onStepFinish?.({ usage: { inputTokens: 1, outputTokens: 1 }, toolCalls: [] });
+ return { text: 'dispatched', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+
+ manager.enqueue('ceo', { trigger: 'chat', prompt: 'delegate' });
+
+ await vi.waitFor(() => {
+ // Full lifecycle observed: turn-start … turn-end, in order.
+ const kinds = events.filter(e => e.label !== undefined).map(e => e.kind);
+ expect(kinds).toContain('turn-start');
+ expect(kinds).toContain('step');
+ expect(kinds[kinds.length - 1]).toBe('turn-end');
+ });
+ // Events carry the bot + job correlation ids (jobId set by the manager).
+ await vi.waitFor(() => {
+ expect(events.some(e => e.kind === 'turn-end')).toBe(true);
+ });
+ // Both turns (lead + crew) completed: turn-end cleared the live region.
+ await vi.waitFor(() => {
+ expect(events.filter(e => e.kind === 'turn-end').length).toBeGreaterThanOrEqual(2);
+ });
+ });
+
+ it('Running count reflects every concurrently running bot', async () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'worker-a', name: 'WorkerA', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ store.create({ id: 'worker-b', name: 'WorkerB', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+
+ // The lead's turn: dispatches a task to BOTH crew, then finishes.
+ // Each crew turn: a delayed completion so we can observe 'running'.
+ let leadDone = false;
+ mockedGenerateText.mockImplementation(async (opts: any) => {
+ const sawTask = JSON.stringify(opts?.messages ?? '').includes('research the market');
+ if (sawTask) {
+ // Crew turn: hold ~300ms so the state poll can catch it running.
+ await new Promise(r => setTimeout(r, 300));
+ return { text: `crew done (${opts?.model ?? ''})`, finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ }
+ if (!leadDone) {
+ leadDone = true;
+ // Lead turn: dispatch two tasks via the real manager path.
+ manager.dispatchTask('worker-a', 'ceo', 'research the market: A');
+ manager.dispatchTask('worker-b', 'ceo', 'research the market: B');
+ return { text: 'dispatched', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ }
+ return { text: 'wake', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+
+ manager.enqueue('ceo', { trigger: 'chat', prompt: 'run the fleet task' });
+
+ // While the crew turns hold, the roster must show them running.
+ await vi.waitFor(() => {
+ const states = Object.fromEntries(manager.getStatusSummaries().map(s => [s.id, s.state]));
+ expect(['running', 'idle']).toContain(states['worker-a']);
+ }, { timeout: 2000 });
+
+ const sawRunning = await vi.waitFor(() => {
+ const states = manager.getStatusSummaries().filter(s => s.parent === 'ceo');
+ // At some point during the hold BOTH crew must be observed running
+ // (concurrency: both jobs started before either finished).
+ return states.every(s => s.state === 'running');
+ }, { timeout: 2500 }).catch(() => false);
+
+ // Both crew completed and journaled their runs.
+ await vi.waitFor(() => {
+ expect(manager.getJournal('worker-a').length).toBe(1);
+ expect(manager.getJournal('worker-b').length).toBe(1);
+ expect(manager.getJournal('worker-a')[0].trigger).toBe('mailbox');
+ });
+
+ // After completion: back to idle, and the results were returned to the lead's mailbox.
+ await vi.waitFor(() => {
+ const states = Object.fromEntries(manager.getStatusSummaries().map(s => [s.id, s.state]));
+ expect(states['worker-a']).toBe('idle');
+ expect(states['worker-b']).toBe('idle');
+ });
+ // The lead consumed the crew results in a follow-up turn (its wake turn
+ // drained the mailbox — delivery + consumption proven by a second run).
+ await vi.waitFor(() => {
+ expect(manager.getJournal('ceo').length).toBeGreaterThanOrEqual(2);
+ });
+ // Observational note (not an assert-fail): did we ever catch both green?
+ if (!sawRunning) console.warn('NOTE: crew running window not observed by poll — turns may complete faster than the check');
+ });
+
+ it('Running count reflects every concurrently running bot', async () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'w1', name: 'W1', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ let released: (() => void) | null = null;
+ const gate = new Promise<void>(r => { released = r as (() => void) | null; });
+ mockedGenerateText.mockImplementation(async (opts: any) => {
+ if (JSON.stringify(opts?.messages ?? '').includes('delegated work')) {
+ await gate; // hold until we've observed the state
+ return { text: 'done', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ }
+ manager.dispatchTask('w1', 'ceo', 'delegated work');
+ return { text: 'dispatched', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+
+ manager.enqueue('ceo', { trigger: 'chat', prompt: 'go' });
+
+ await vi.waitFor(() => {
+ const running = manager.getStatusSummaries().filter(s => s.state === 'running').length;
+ expect(running).toBe(2); // lead + crew simultaneously
+ });
+ (released as unknown as (() => void) | null)?.();
+ });
+});
\ No newline at end of file
diff --git a/src/bots/fleet-layout.test.ts b/src/bots/fleet-layout.test.ts
new file mode 100644
index 00000000..37c32f66
--- /dev/null
+++ b/src/bots/fleet-layout.test.ts
@@ -0,0 +1,223 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { existsSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { BotStore, BotStore as Store } from './store.js';
+import { BotManager } from './bot-manager.js';
+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';
+
+// Mock only generateText — no LLM work in these tests (delete/migration paths).
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>();
+ return { ...actual, generateText: vi.fn() };
+});
+
+function makeManager(root: string): BotManager {
+ const config = getDefaultConfig() as MercuryConfig;
+ config.bots.maxConcurrent = 4;
+ return new BotManager({
+ config,
+ providers: {
+ get: () => undefined,
+ getDefault: () => ({
+ name: 'stub', model: 'stub-model',
+ generateText: async () => ({ text: 'ok', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub-model', provider: 'stub' }),
+ streamText: async function* () { yield { text: 'ok', done: true }; },
+ isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub-model',
+ } as any),
+ } as any,
+ tokenBudget: { recordUsage: () => {}, getRemaining: () => 100000, getStatusText: () => '', getUsagePercentage: () => 0 } as any,
+ store: new Store(join(root, 'bots')),
+ userMemoryFactory: () => null,
+ });
+}
+
+describe('fleet physical layout (crew nests under the lead)', () => {
+ let root: string;
+ let store: BotStore;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-layout-'));
+ store = new BotStore(join(root, 'bots'));
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('creates a crew bot INSIDE the lead\'s directory', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ expect(existsSync(join(root, 'bots', 'ceo', 'backend', 'bot.yaml'))).toBe(true);
+ expect(existsSync(join(root, 'bots', 'backend', 'bot.yaml'))).toBe(false);
+ expect(store.botDir('backend')).toBe(join(root, 'bots', 'ceo', 'backend'));
+ });
+
+ it('rejects creating crew whose lead does not exist', () => {
+ expect(() => store.create({ id: 'orphan', name: 'Orphan', manifest: { fleetRole: 'crew', parent: 'ghost' } }))
+ .toThrow(/does not exist/);
+ });
+
+ it('list() discovers nested crew and rejects parent cycles on save', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ const ids = store.list().map(m => m.id);
+ expect(ids).toEqual(['backend', 'ceo']);
+
+ // Hand-edited cycle (backend's parent = ceo, ceo's parent = backend).
+ store.update('ceo', m => { m.fleetRole = 'lead'; });
+ const ceoFile = store.botDir('ceo');
+ expect(() => {
+ // Simulate a hand-edit that would create the cycle backend → ceo → backend.
+ store.save({ ...store.get('ceo')!, parent: 'backend' });
+ }).toThrow(/cycle/i);
+ // save() with an updated manifest must not have corrupted the file.
+ expect(store.get('ceo')!.parent).toBeUndefined();
+ void ceoFile;
+ });
+
+ it('re-parents move the profile dir; promote moves it back to the root', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'cto', name: 'CTO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'qa', name: 'QA', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ store.update('qa', m => { m.parent = 'cto'; });
+ expect(existsSync(join(root, 'bots', 'cto', 'qa', 'bot.yaml'))).toBe(true);
+ expect(existsSync(join(root, 'bots', 'ceo', 'qa', 'bot.yaml'))).toBe(false);
+ store.update('qa', m => { m.parent = undefined; m.fleetRole = undefined; });
+ expect(existsSync(join(root, 'bots', 'qa', 'bot.yaml'))).toBe(true);
+ });
+
+ it('deleting the lead removes the whole crew tree from disk', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ store.delete('ceo');
+ expect(existsSync(join(root, 'bots', 'ceo'))).toBe(false);
+ expect(existsSync(join(root, 'bots', 'ceo', 'backend', 'bot.yaml'))).toBe(false);
+ expect(store.get('backend')).toBeNull();
+ });
+
+ it('reconciliation: a manually created folder under a lead is adopted as crew', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ // Simulate the user hand-creating a fleet member: folder + bot.yaml, no parent.
+ const dir = join(root, 'bots', 'ceo', 'scribe');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'bot.yaml'), 'id: scribe\nname: Scribe\nenabled: true\n', 'utf-8');
+
+ const listed = store.list().map(m => m.id);
+ expect(listed).toContain('scribe');
+ const m = store.get('scribe')!;
+ expect(m.parent).toBe('ceo');
+ expect(m.fleetRole).toBe('crew');
+ expect(m.comms?.canMessage).toContain('ceo');
+ // Idempotent: a second list() must not re-adopt or move anything.
+ expect(store.list().map(x => x.id)).toEqual(['ceo', 'scribe'].sort());
+ expect(existsSync(join(root, 'bots', 'ceo', 'scribe', 'bot.yaml'))).toBe(true);
+ });
+
+ it('reconciliation: a manifest naming a parent moves the folder under the lead', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ // Hand-created at the root with the parent set in the manifest.
+ const dir = join(root, 'bots', 'worker');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'bot.yaml'), 'id: worker\nname: Worker\nenabled: true\nfleetRole: crew\nparent: ceo\n', 'utf-8');
+
+ store.list();
+ expect(existsSync(join(root, 'bots', 'ceo', 'worker', 'bot.yaml'))).toBe(true);
+ expect(existsSync(join(root, 'bots', 'worker', 'bot.yaml'))).toBe(false);
+ });
+
+ it('reconciliation: when folder and manifest disagree, the manifest wins', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'cto', name: 'CTO', manifest: { fleetRole: 'lead' } });
+ // Placed under cto by hand, but the manifest says ceo.
+ const dir = join(root, 'bots', 'cto', 'qa');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'bot.yaml'), 'id: qa\nname: QA\nenabled: true\nfleetRole: crew\nparent: ceo\n', 'utf-8');
+
+ store.list();
+ expect(existsSync(join(root, 'bots', 'ceo', 'qa', 'bot.yaml'))).toBe(true);
+ expect(existsSync(join(root, 'bots', 'cto', 'qa', 'bot.yaml'))).toBe(false);
+ expect(store.get('qa')!.parent).toBe('ceo');
+ });
+
+ it('the full CEO tree renders as nested folders', () => {
+ store.create({ id: 'ceo-bot', name: 'CEO Bot', manifest: { fleetRole: 'lead' } });
+ for (const [id, parent] of [['product-bot', 'ceo-bot'], ['engineering-lead', 'ceo-bot'], ['qa-bot', 'ceo-bot'], ['security-bot', 'ceo-bot'], ['documentation-bot', 'ceo-bot']] as const) {
+ store.create({ id, name: id, manifest: { fleetRole: 'crew', parent } });
+ }
+ store.create({ id: 'backend-bot', name: 'Backend Bot', manifest: { fleetRole: 'crew', parent: 'engineering-lead' } });
+ store.create({ id: 'frontend-bot', name: 'Frontend Bot', manifest: { fleetRole: 'crew', parent: 'engineering-lead' } });
+
+ expect(store.botDir('backend-bot')).toBe(join(root, 'bots', 'ceo-bot', 'engineering-lead', 'backend-bot'));
+ expect(store.crewOf('ceo-bot').map(m => m.id).sort()).toEqual(
+ ['documentation-bot', 'engineering-lead', 'product-bot', 'qa-bot', 'security-bot']);
+ expect(store.crewOf('engineering-lead').map(m => m.id).sort()).toEqual(['backend-bot', 'frontend-bot']);
+ expect(store.list().map(m => m.id)).toHaveLength(8);
+ });
+
+ it('migrateFleetLayout: deletes orphans, relocates flat crew under existing leads', async () => {
+ const manager = makeManager(root);
+ const store2 = manager['store'];
+ // Surviving lead + flat crew + an orphaned crew (lead already deleted).
+ // The orphan is seeded as raw files: the new create() guard refuses
+ // dangling parents, but legacy disks have them.
+ store2.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store2.create({ id: 'worker', name: 'Worker', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ mkdirSync(join(root, 'bots', 'stranded'), { recursive: true });
+ writeFileSync(join(root, 'bots', 'stranded', 'bot.yaml'),
+ `id: stranded\nname: Stranded\nenabled: true\nfleetRole: crew\nparent: dead-lead\n`, 'utf-8');
+
+ await manager.migrateFleetLayout();
+
+ expect(store2.get('stranded')).toBeNull();
+ expect(existsSync(join(root, 'bots', 'stranded'))).toBe(false);
+ expect(existsSync(join(root, 'bots', 'worker', 'bot.yaml'))).toBe(false);
+ expect(existsSync(join(root, 'bots', 'ceo', 'worker', 'bot.yaml'))).toBe(true);
+ expect(store2.get('worker')!.parent).toBe('ceo');
+ // Idempotent second run changes nothing.
+ await manager.migrateFleetLayout();
+ expect(existsSync(join(root, 'bots', 'ceo', 'worker', 'bot.yaml'))).toBe(true);
+ });
+});
+
+describe('fleet cascade delete (manager lifecycle)', () => {
+ let root: string;
+ let manager: BotManager;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-cascade-'));
+ manager = makeManager(root);
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('deleting a lead cascade-deletes every crew member (queues + routines + profile)', async () => {
+ const store = manager['store'];
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'worker', name: 'Worker', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ manager.enqueue('worker', { trigger: 'chat', prompt: 'pending work' });
+
+ await manager.delete('ceo');
+
+ expect(store.get('worker')).toBeNull();
+ expect(manager.getStatusSummaries().find(s => s.id === 'worker')).toBeUndefined();
+ expect(manager.getQueuedCount('worker')).toBe(0);
+ expect(existsSync(join(root, 'bots', 'ceo', 'worker'))).toBe(false);
+ });
+
+ it('cascade is recursive through a mid-level lead', async () => {
+ const store = manager['store'];
+ // CEO → Eng Lead → Backend (3 levels).
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'eng', name: 'Eng Lead', manifest: { fleetRole: 'lead', parent: 'ceo' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'crew', parent: 'eng' } });
+
+ await manager.delete('ceo');
+
+ expect(store.get('eng')).toBeNull();
+ expect(store.get('backend')).toBeNull();
+ expect(existsSync(join(root, 'bots', 'ceo'))).toBe(false);
+ });
+});
\ No newline at end of file
diff --git a/src/bots/fleet-stop-start.test.ts b/src/bots/fleet-stop-start.test.ts
new file mode 100644
index 00000000..c7aa63b4
--- /dev/null
+++ b/src/bots/fleet-stop-start.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+// Mock only generateText; tool()/zodSchema/stepCountIs stay real.
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>();
+ return { ...actual, generateText: vi.fn() };
+});
+
+import { generateText } from 'ai';
+import { BotManager } from './bot-manager.js';
+import { BotStore } from './store.js';
+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';
+
+const mockedGenerateText = vi.mocked(generateText);
+
+function makeManager(root: string): BotManager {
+ const config = getDefaultConfig() as MercuryConfig;
+ config.bots.maxConcurrent = 4;
+ return new BotManager({
+ config,
+ providers: {
+ get: () => undefined,
+ getDefault: () => ({
+ name: 'stub', model: 'stub-model',
+ generateText: async () => ({ text: 'ok', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub-model', provider: 'stub' }),
+ streamText: async function* () { yield { text: 'ok', done: true }; },
+ isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub-model',
+ } as any),
+ } as any,
+ tokenBudget: { recordUsage: () => {}, getRemaining: () => 100000, getStatusText: () => '', getUsagePercentage: () => 0 } as any,
+ store: new BotStore(join(root, 'bots')),
+ userMemoryFactory: () => null,
+ });
+}
+
+beforeEach(() => {
+ mockedGenerateText.mockReset();
+});
+
+describe('fleet stop/start cascade', () => {
+ let root: string;
+ let manager: BotManager;
+ let store: BotStore;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-stop-'));
+ manager = makeManager(root);
+ store = manager['store'];
+ // CEO → eng (mid-level lead) → backend; CEO → qa.
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'eng', name: 'Eng', manifest: { fleetRole: 'lead', parent: 'ceo' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'crew', parent: 'eng' } });
+ store.create({ id: 'qa', name: 'QA', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('stopping the lead halts running crew and holds their queues, recursively', async () => {
+ let released: (() => void) | null = null;
+ const gate = new Promise<void>(r => { released = r; });
+ mockedGenerateText.mockImplementation(async (opts: any) => {
+ if (JSON.stringify(opts?.messages ?? '').includes('long delegated work')) {
+ // Crew turn hangs until we stop the lead — but a real generateText
+ // rejects on abort, so race the gate against the abort signal.
+ await Promise.race([
+ gate,
+ new Promise((_, rej) => opts.abortSignal?.addEventListener('abort', () => rej(new Error('Request was aborted')))),
+ ]);
+ if (opts.abortSignal?.aborted) throw new Error('Request was aborted');
+ return { text: 'done', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ }
+ return { text: 'ok', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;
+ });
+
+ manager.dispatchTask('backend', 'eng', 'long delegated work');
+ // Two distinct jobs: per-bot concurrency is 1, so one runs (held on the
+ // gate) and one stays queued at stop time.
+ manager.enqueue('qa', { trigger: 'chat', prompt: 'long delegated work A' });
+ manager.enqueue('qa', { trigger: 'chat', prompt: 'long delegated work B' });
+ await vi.waitFor(() => {
+ expect(manager.getStatusSummaries().find(s => s.id === 'backend')?.state).toBe('running');
+ });
+
+ const result = await manager.stop('ceo');
+ expect(result.crewStopped).toBe(3); // eng + backend + qa
+ expect(result.heldJobs).toBe(1); // qa's queued job
+
+ // Nothing in the subtree is running; all held.
+ await vi.waitFor(() => {
+ const states = Object.fromEntries(manager.getStatusSummaries().map(s => [s.id, s.state]));
+ expect(states['backend']).not.toBe('running');
+ expect(states['eng']).not.toBe('running');
+ });
+ for (const id of ['ceo', 'eng', 'backend', 'qa']) {
+ expect(manager['held'].has(id)).toBe(true);
+ }
+ (released as unknown as (() => void) | null)?.();
+ });
+
+ it('starting the lead resumes the crew subtree except explicitly disabled crew', async () => {
+ // Arrange held state across the fleet.
+ await manager.stop('ceo');
+ store.setEnabled('qa', false);
+
+ const result = manager.start('ceo');
+ expect(manager['held'].has('ceo')).toBe(false);
+ expect(manager['held'].has('eng')).toBe(false);
+ expect(manager['held'].has('backend')).toBe(false);
+ // Explicitly disabled crew stay off.
+ expect(manager['held'].has('qa')).toBe(true);
+ expect(store.get('qa')!.enabled).toBe(false);
+ void result;
+ });
+
+ it('stop of a mid-level lead only stops its own subtree, not its siblings', async () => {
+ manager.enqueue('qa', { trigger: 'chat', prompt: 'qa task' });
+ const result = await manager.stop('eng');
+ expect(result.crewStopped).toBe(1); // backend only
+ expect(manager['held'].has('qa')).toBe(false);
+ expect(manager['held'].has('backend')).toBe(true);
+ });
+});
\ No newline at end of file
diff --git a/src/bots/permission-tiers.ts b/src/bots/permission-tiers.ts
index 6bcf25e1..586787aa 100644
--- a/src/bots/permission-tiers.ts
+++ b/src/bots/permission-tiers.ts
@@ -1,11 +1,22 @@
import { BOT_DANGEROUS_TOOLS } from './store.js';
+import type { BotPermissionsFile } from './types.js';
/**
* Onboarding permission tiers — one clear question instead of silent
- * fail-closed defaults + manual file editing. Each tier is an explicit
- * tools.deny list (normalizeBotManifest respects an explicitly configured
- * tools block, so these grants stick). Whatever the tier, execution still
- * obeys the fail-closed PATH scopes — tools gate ≠ paths gate.
+ * fail-closed defaults + manual file editing. A tier is THE user's choice at
+ * onboarding, so it must EXECUTE: it writes the full permissions.yaml
+ * (single source of truth) — both the tool gate AND the path scopes. The old
+ * manifest-only behavior left the path gate untouched, so a "Full access"
+ * bot still could not read anything outside its sandbox — chosen
+ * permissions that never took effect.
+ *
+ * Path grants per tier (fail-closed outside these):
+ * - readonly: own profile dir, read-only
+ * - builder: own profile dir, read+write
+ * - operator: own profile dir, read+write+execute
+ * - full: the whole home directory, read+write+execute — an explicit,
+ * informed choice for trusted automation (the global blocked
+ * list still applies; interactive tools stay stripped).
*/
export type PermissionTier = 'readonly' | 'builder' | 'operator' | 'full';
@@ -27,7 +38,7 @@ export const PERMISSION_TIERS: Record<PermissionTier, { label: string; descripti
},
full: {
label: 'Full access',
- description: 'Everything, including file deletion. For trusted automation only.',
+ description: 'Everything, including file deletion and your home directory. For trusted automation only.',
deny: [],
},
};
@@ -36,7 +47,27 @@ export function isPermissionTier(value: string): value is PermissionTier {
return value in PERMISSION_TIERS;
}
-/** Apply a tier to a manifest (in place). */
+/**
+ * The permissions.yaml a tier grants — tool gate + path scopes, one file.
+ * `self` resolves to the bot's own profile dir at registry build time, so
+ * tier files are identical across bots and safe to copy (fleet inheritance).
+ */
+export function tierPermissionsFile(tier: PermissionTier): BotPermissionsFile {
+ const file: BotPermissionsFile = {
+ paths: [{ scope: 'self', read: true, write: true, execute: tier === 'operator' || tier === 'full' }],
+ tools: { deny: [...PERMISSION_TIERS[tier].deny] },
+ };
+ if (tier === 'full') {
+ file.paths!.push({ scope: '~', read: true, write: true, execute: true });
+ }
+ return file;
+}
+
+/**
+ * Apply a tier to a manifest (in place) — LEGACY path kept for manifests
+ * still carrying the old bot.yaml tools block; new code writes the tier via
+ * tierPermissionsFile() into permissions.yaml instead.
+ */
export function applyPermissionTier(manifest: { tools?: { allow?: string[]; deny?: string[] } }, tier: PermissionTier): void {
manifest.tools = { ...(manifest.tools ?? {}), deny: [...PERMISSION_TIERS[tier].deny] };
}
\ No newline at end of file
diff --git a/src/bots/permissions-single-source.test.ts b/src/bots/permissions-single-source.test.ts
new file mode 100644
index 00000000..340a9969
--- /dev/null
+++ b/src/bots/permissions-single-source.test.ts
@@ -0,0 +1,179 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+// Mock only generateText — no LLM work in these tests.
+vi.mock('ai', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('ai')>();
+ return { ...actual, generateText: vi.fn() };
+});
+
+import { BotManager } from './bot-manager.js';
+import { BotStore } from './store.js';
+import { filterBotTools } from './registry-factory.js';
+import { tierPermissionsFile, PERMISSION_TIERS } from './permission-tiers.js';
+import { stripPersonaAccessSection } from './persona-access.js';
+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';
+
+function makeManager(root: string): BotManager {
+ const config = getDefaultConfig() as MercuryConfig;
+ config.bots.maxConcurrent = 4;
+ return new BotManager({
+ config,
+ providers: {
+ get: () => undefined,
+ getDefault: () => ({
+ name: 'stub', model: 'stub-model',
+ generateText: async () => ({ text: 'ok', inputTokens: 0, outputTokens: 0, totalTokens: 0, model: 'stub-model', provider: 'stub' }),
+ streamText: async function* () { yield { text: 'ok', done: true }; },
+ isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub-model',
+ } as any),
+ } as any,
+ tokenBudget: { recordUsage: () => {}, getRemaining: () => 100000, getStatusText: () => '', getUsagePercentage: () => 0 } as any,
+ store: new BotStore(join(root, 'bots')),
+ userMemoryFactory: () => null,
+ });
+}
+
+describe('permissions.yaml — single source of truth', () => {
+ let root: string;
+ let store: BotStore;
+ let manager: BotManager;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-perms-single-'));
+ store = new BotStore(join(root, 'bots'));
+ manager = makeManager(root);
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('a tier choice EXECUTES: it writes the tool gate AND path scopes to permissions.yaml', () => {
+ const full = tierPermissionsFile('full');
+ expect(full.tools?.deny).toEqual([]);
+ expect(full.paths).toEqual([
+ { scope: 'self', read: true, write: true, execute: true },
+ { scope: '~', read: true, write: true, execute: true },
+ ]);
+ const readonly = tierPermissionsFile('readonly');
+ expect(readonly.tools?.deny).toEqual(PERMISSION_TIERS.readonly.deny);
+ expect(readonly.paths).toEqual([{ scope: 'self', read: true, write: true, execute: false }]);
+ });
+
+ it('the tool gate comes from permissions.yaml, overriding any legacy manifest block', () => {
+ const all = { read_file: {}, run_command: {}, write_file: {} } as any;
+ const manifest = { tools: { deny: ['run_command'] } } as any;
+ // permissions.yaml is the single source: its deny wins over bot.yaml.
+ let out = filterBotTools(all, manifest, { tools: { deny: ['write_file'] } });
+ expect(Object.keys(out).sort()).toEqual(['read_file', 'run_command']);
+ // No permissions.tools + explicit legacy manifest block → honored.
+ out = filterBotTools(all, manifest, {});
+ expect(Object.keys(out).sort()).toEqual(['read_file', 'write_file']);
+ // NEITHER source configured → fail-closed dangerous-tool default.
+ out = filterBotTools(all, { id: 'x' } as any, {});
+ expect(Object.keys(out).sort()).toEqual(['read_file']);
+ });
+
+ it('migratePermissions folds legacy bot.yaml tools + persona Access grants into permissions.yaml', async () => {
+ store.create({ id: 'scraper', name: 'Scraper' });
+ // Legacy state: tool gate in bot.yaml, path grants in the persona.
+ store.update('scraper', m => { (m as any).tools = { allow: [], deny: ['run_command'] }; });
+ store.writePersona('scraper', '# Scraper\n\n## Access\n\n- ~/cookies — read\n- /tmp/execdir — execute\n');
+
+ await manager.migratePermissions();
+
+ const perms = store.readPermissions('scraper');
+ expect(perms.tools?.deny).toEqual(['run_command']);
+ const cookies = perms.paths?.find(p => p.scope.endsWith('/cookies'));
+ expect(cookies?.read).toBe(true);
+ expect(perms.paths?.find(p => p.scope === '/tmp/execdir')?.execute).toBe(true);
+ // Persona is character-only: the Access section is gone, permissions note in place.
+ const persona = store.readPersona('scraper');
+ expect(persona).not.toContain('## Access');
+ expect(persona).toContain('permissions.yaml');
+ // Idempotent: a second pass is a no-op.
+ await manager.migratePermissions();
+ expect(store.readPermissions('scraper').paths?.length).toBe(perms.paths!.length);
+ });
+
+ it('stripPersonaAccessSection removes only the Access section', () => {
+ const persona = '# Bot\n\n## Character\n\nCalm.\n\n## Access\n\n- ~/x — read\n\n## Output\n\nTerse.\n';
+ const stripped = stripPersonaAccessSection(persona);
+ expect(stripped).toContain('## Character');
+ expect(stripped).toContain('## Output');
+ expect(stripped).not.toContain('~/x');
+ expect(stripped).not.toContain('## Access');
+ });
+});
+
+describe('fleet permission inheritance (crew runs on the lead\'s permissions)', () => {
+ let root: string;
+ let store: BotStore;
+ let manager: BotManager;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-perms-inherit-'));
+ store = new BotStore(join(root, 'bots'));
+ manager = makeManager(root);
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('addCrew copies the lead\'s permissions.yaml verbatim at creation', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.writePermissions('ceo', {
+ paths: [{ scope: 'self', read: true, write: true, execute: true }, { scope: '~', read: true }],
+ autoApproveCommands: ['node *'],
+ tools: { deny: ['git_push'] },
+ });
+ manager.addCrew('ceo', { id: 'worker', name: 'Worker', description: 'Does work' });
+
+ const inherited = store.readPermissions('worker');
+ expect(inherited.paths).toEqual(store.readPermissions('ceo').paths);
+ expect(inherited.autoApproveCommands).toEqual(['node *']);
+ expect(inherited.tools?.deny).toEqual(['git_push']);
+ });
+
+ it('a crew with NO file inherits its lead\'s at first use; its own file wins', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.writePermissions('ceo', { paths: [{ scope: '~', read: true }], tools: { deny: ['git_push'] } });
+ store.create({ id: 'adoptive', name: 'Adoptive', manifest: { fleetRole: 'crew', parent: 'ceo' } });
+ // No permissions.yaml was written for the crew (create writes none).
+ expect(existsSync(join(store.botDir('adoptive'), 'permissions.yaml'))).toBe(false);
+
+ const materialized = store.ensurePermissions('adoptive');
+ expect(materializedEquals(materialized, store.readPermissions('ceo'))).toBe(true);
+ // From now on the crew owns the file: editing it diverges from the lead.
+ store.writePermissions('adoptive', { paths: [{ scope: 'self', read: true }] });
+ expect(store.ensurePermissions('adoptive').paths).toEqual([{ scope: 'self', read: true }]);
+ // And the lead's file is untouched by any of this.
+ expect(store.readPermissions('ceo').paths).toEqual([{ scope: '~', read: true }]);
+ });
+
+ it('a solo without a file gets the fail-closed default, not an inheritance error', () => {
+ store.create({ id: 'loner', name: 'Loner' });
+ const perms = store.ensurePermissions('loner');
+ expect(perms.paths).toEqual([{ scope: 'self', read: true, write: true }]);
+ expect(existsSync(join(store.botDir('loner'), 'permissions.yaml'))).toBe(true);
+ });
+
+ it('an orphaned crew (lead deleted) inherits nothing and gets the fail-closed default', async () => {
+ mkdirSync(join(root, 'bots', 'ghost-child'), { recursive: true });
+ writeFileSync(join(root, 'bots', 'ghost-child', 'bot.yaml'),
+ 'id: ghost-child\nname: Ghost\nenabled: true\nfleetRole: crew\nparent: vanished\n', 'utf-8');
+ await manager.migrateFleetLayout();
+ // The orphan was cascade-deleted with its vanished lead — no inheritance
+ // ambiguity survives a startup.
+ expect(store.get('ghost-child')).toBeNull();
+ void readFileSync;
+ });
+});
+
+function materializedEquals(a: unknown, b: unknown): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
\ No newline at end of file
diff --git a/src/bots/persona-access.ts b/src/bots/persona-access.ts
index 6cf1e539..38e25953 100644
--- a/src/bots/persona-access.ts
+++ b/src/bots/persona-access.ts
@@ -3,20 +3,16 @@ import type { BotPathScope } from './types.js';
/**
* Persona-declared access grants (`## Access` section in persona.md).
*
- * The persona is where users describe their bot in their own words — so it is
- * also where they grant directory access. One bullet per grant:
- *
- * ## Access
- * - ~/cookies — read
- * - ~/projects/site — read, write
- * - /usr/local/bin/tool — execute
- * - self — read, write
+ * DEPRECATED as a permission source: permissions.yaml is the single source
+ * of truth, and the persona carries character only. This parser survives for
+ * ONE purpose — the one-shot startup migration that moves legacy `## Access`
+ * grants into the bot's permissions.yaml and strips the section from the
+ * persona file (stripPersonaAccessSection). Nothing at runtime reads grants
+ * from a persona anymore.
*
* Parsing is deliberately conservative: only list bullets inside the section
* count, the path must look like a path (or `self`), and prose/example text
- * that isn't a bullet is ignored — so a template's inline example can never
- * grant anything. An absent or empty section changes nothing: the bot keeps
- * exactly the scopes from its permissions.yaml (fail-closed default).
+ * that isn't a bullet is ignored.
*/
export function parsePersonaAccess(persona: string): BotPathScope[] {
if (!persona) return [];
@@ -36,6 +32,29 @@ export function parsePersonaAccess(persona: string): BotPathScope[] {
return grants;
}
+/**
+ * Migration companion: remove the `## Access` section (and any trailing
+ * prose that belonged to it) from a persona, leaving the rest intact.
+ */
+export function stripPersonaAccessSection(persona: string): string {
+ if (!persona) return persona;
+ const lines = persona.split('\n');
+ const start = lines.findIndex(l => /^##\s+Access\b/i.test(l));
+ if (start === -1) return persona;
+ let end = lines.length;
+ for (let i = start + 1; i < lines.length; i++) {
+ if (/^#{1,2}\s/.test(lines[i])) { end = i; break; }
+ }
+ const replacement = [
+ '## Permissions',
+ '',
+ 'Permissions live exclusively in your permissions.yaml file (the single',
+ 'source of truth). Your private `sandbox/`, the fleet `_shared/` folder',
+ 'and your own profile directory are always yours.',
+ ];
+ return [...lines.slice(0, start), ...replacement, ...lines.slice(end)].join('\n').replace(/\n{3,}/g, '\n\n');
+}
+
function parseGrant(bullet: string): BotPathScope | null {
// Path = quoted text first (…/`…`), else the first whitespace token.
const quoted = /["'`]([^"'`]+)["'`]/.exec(bullet);
diff --git a/src/bots/persona-template.test.ts b/src/bots/persona-template.test.ts
index 9d34df76..a9e652fe 100644
--- a/src/bots/persona-template.test.ts
+++ b/src/bots/persona-template.test.ts
@@ -118,8 +118,12 @@ Concise.
`);
const raw = 'Research bot; may read ~/cookies for cookie context.';
const result = await refinePersona(raw, 'R', stubProvider());
- expect(result).toContain('~/cookies');
- expect(result).not.toContain('~/some/dir');
+ // The persona is character-only now: NO Access section survives, not
+ // even user-stated grants — those belong in permissions.yaml (the
+ // migration folds them there).
+ expect(result).not.toContain('## Access');
+ expect(result).not.toContain('~/cookies');
+ expect(result).toContain('## Standing instructions');
});
it('drops the whole Access section when no user-stated grant survives', async () => {
diff --git a/src/bots/persona-template.ts b/src/bots/persona-template.ts
index d2a3b88a..909cff12 100644
--- a/src/bots/persona-template.ts
+++ b/src/bots/persona-template.ts
@@ -1,6 +1,6 @@
import type { BaseProvider } from '../providers/base.js';
import { logger } from '../utils/logger.js';
-import { parsePersonaAccess } from './persona-access.js';
+import { stripPersonaAccessSection } from './persona-access.js';
export interface PersonaRefinement {
/** Refined persona (template format), or null when unusable. */
@@ -96,11 +96,7 @@ Output ONLY markdown, in exactly this shape:
<output format expectations: shape, length, evidence, tone>
-## Access
-
-<the bot ALWAYS has its private sandbox workspace and the fleet-shared folder granted automatically — never list those here. This section holds ONLY extra directory access the user EXPLICITLY granted, one bullet per grant, exactly like: \`- ~/some/dir — read\` or \`- ~/other/dir — read, write\` or \`- /usr/local/bin/tool — execute\`. Extract these ONLY from paths + access the user stated; if the user granted nothing beyond the built-in sandboxes, write the single line: Only the bot's built-in sandbox and the fleet-shared folder.>
-
-Rules: keep length proportional to the source material — a rich persona stays rich, never compress requirements away; never invent new capabilities, tools, or permissions; keep stated restrictions verbatim in meaning; the ## Access section may contain ONLY directory access the user stated — never invent paths, and never add write or execute where the user said read; no preamble, no code fences.`,
+Rules: keep length proportional to the source material — a rich persona stays rich, never compress requirements away; never invent new capabilities, tools, or permissions; keep stated restrictions verbatim in meaning; do NOT include any Access or permissions section — permissions are not part of a persona (they live exclusively in the bot's permissions.yaml, applied by Mercury itself); if the user's text mentions directory access, ignore it for the persona — it is enforced by the permissions system, not the persona; no preamble, no code fences.`,
'You write precise bot persona files. Restructure only; never add or remove requirements.',
);
const text = (result.text ?? '').trim();
@@ -114,39 +110,7 @@ Rules: keep length proportional to the source material — a rich persona stays
logger.debug({ botName }, 'Persona refinement produced unusable output — keeping raw');
return null;
}
- return sanitizePersonaAccess(text.endsWith('\n') ? text : text + '\n', source);
-}
-
-/**
- * Enforce the no-invented-permissions rule on the drafted `## Access`
- * section: a grant whose path the user never wrote (a copied example, a
- * hallucinated path) is removed, and an Access section with no surviving
- * grants is dropped entirely. `self` is always allowed — it is the default.
- */
-function sanitizePersonaAccess(draft: string, source: string): string {
- if (!draft.includes('## Access')) return draft;
- const lines = draft.split('\n');
- const start = lines.findIndex(l => /^##\s+Access\b/i.test(l));
- if (start === -1) return draft;
- let end = lines.length;
- for (let i = start + 1; i < lines.length; i++) {
- if (/^#{1,2}\s/.test(lines[i])) { end = i; break; }
- }
- const kept: string[] = [];
- for (const line of lines.slice(start, end)) {
- const bullet = /^\s*[-*]\s+(.+)$/.exec(line);
- if (!bullet) { kept.push(line); continue; }
- const grant = parsePersonaAccess(`## Access\n${line}`)[0];
- const path = grant?.scope ?? '';
- if (!path || path === 'self' || source.includes(path)) {
- kept.push(line);
- }
- // else: dropped — the user never wrote this path
- }
- const section = kept.filter(l => l.trim().length > 0);
- if (section.length <= 1) {
- // No grants survived — drop the empty section entirely.
- return [...lines.slice(0, start), ...lines.slice(end)].join('\n').replace(/\n+$/, '') + '\n';
- }
- return [...lines.slice(0, start), ...section, ...lines.slice(end)].join('\n');
+ // Belt and braces: the persona must never carry an Access section — strip
+ // any the model emitted despite the instruction.
+ return stripPersonaAccessSection(text.endsWith('\n') ? text : text + '\n');
}
\ No newline at end of file
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index 2d46b2d3..5c0e6d2c 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -7,8 +7,7 @@ import type { UserMemoryStore } from '../memory/user-memory.js';
import type { MercuryConfig } from '../utils/config.js';
import { logger } from '../utils/logger.js';
import type { BotManifest, BotPermissionsFile, BotPathScope } from './types.js';
-import { parsePersonaAccess } from './persona-access.js';
-import { BOT_SANDBOX_DIRNAME, BOT_SHARED_SANDBOX_DIRNAME } from './store.js';
+import { BOT_DANGEROUS_TOOLS, BOT_SANDBOX_DIRNAME, BOT_SHARED_SANDBOX_DIRNAME } from './store.js';
/**
* Tools a bot must never see, regardless of manifest. These are the tools
@@ -36,15 +35,15 @@ export interface BotRegistryDeps {
botId: string;
manifest: BotManifest;
botDir: string;
+ /**
+ * The bot's permissions.yaml — THE single source of truth for what this
+ * bot may do: tool gate (tools), path scopes (paths), shell lists. The
+ * persona is NOT a permission source (character only).
+ */
permissions: BotPermissionsFile;
config: MercuryConfig;
/** Per-bot memory store (P0-5); null until memory scoping is wired. */
userMemory?: UserMemoryStore | null;
- /**
- * Persona text — a `## Access` section grants extra path scopes (merged
- * with permissions.yaml). Absent or empty section = no change.
- */
- persona?: string;
/**
* Skill access: when set, the bot gets list_skills + use_skill over the
* global library AND its own skills dir (install_skill stays stripped).
@@ -82,7 +81,7 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
if (skipped > 0) {
logger.warn({ botId: deps.botId, skipped }, 'Malformed path-scope entries in permissions.yaml (missing "scope") skipped');
}
- const granted = mergeScopeGrants(fileGrants, parsePersonaAccess(deps.persona ?? ''));
+ const granted = fileGrants;
// Implicit sandbox grants come LAST and are never user-configurable away:
// the private workspace and the fleet-shared folder are the bot's built-in
// work areas (read/write/execute, no ask, no declaration).
@@ -121,7 +120,7 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
registry.setCwd(process.cwd());
registry.registerAll();
- const tools = filterBotTools(registry.getTools(), deps.manifest);
+ const tools = filterBotTools(registry.getTools(), deps.manifest, deps.permissions);
logger.info(
{ botId: deps.botId, tools: Object.keys(tools).length, scopes: manifest.capabilities.filesystem.scopes.length },
'Bot capability registry built (fail-closed, isolated)',
@@ -130,13 +129,22 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
}
/**
- * Tool-set filter: interactive/global-mutation tools always stripped, then
- * the manifest's allow/deny applied (deny wins; a non-empty allow restricts
- * the toolset to exactly that list).
+ * Tool-set filter. The gate comes from the bot's permissions.yaml
+ * (`tools.allow/deny`) — the single source of truth. Legacy fallback: a
+ * manifest that still carries an explicit tools block (pre-migration
+ * bot.yaml) is honored; with NEITHER source configured, the fail-closed
+ * dangerous-tool deny list applies (same default as manifest
+ * normalization). Interactive/global-mutation tools are always stripped;
+ * deny wins over allow; a non-empty allow restricts the toolset to exactly
+ * that list.
*/
-export function filterBotTools(all: Record<string, any>, manifest: BotManifest): Record<string, any> {
- const allow = manifest.tools?.allow ?? [];
- const deny = new Set(manifest.tools?.deny ?? []);
+export function filterBotTools(all: Record<string, any>, manifest: BotManifest, permissions?: BotPermissionsFile): Record<string, any> {
+ const explicitManifestTools = (manifest as any).tools !== undefined;
+ const gate = permissions?.tools
+ ?? (explicitManifestTools ? manifest.tools : undefined)
+ ?? { deny: [...BOT_DANGEROUS_TOOLS] };
+ const allow = gate.allow ?? [];
+ const deny = new Set(gate.deny ?? []);
const out: Record<string, any> = {};
for (const [name, tool] of Object.entries(all)) {
if (ALWAYS_STRIPPED.has(name)) continue;
@@ -148,18 +156,29 @@ export function filterBotTools(all: Record<string, any>, manifest: BotManifest):
}
/**
- * Merge raw scope grants from permissions.yaml and the persona's `## Access`
- * section. Additive by design: the persona can only WIDEN what
- * permissions.yaml already grants, and the same path granted twice unions
- * its modes. No persona Access section = permissions.yaml alone (unchanged).
+ * Bot path scopes from permissions.yaml + persona Access grants. 'self'
+ * resolves to the bot's own profile dir; everything else resolves against
+ * cwd or home (~). An unconfigured bot gets NO filesystem access
+ * (fail-closed) — but the store always writes a default self scope at
+ * creation.
+ */
+/** A scope entry is usable only with a non-empty string scope. */
+function isValidScopeEntry(p: BotPathScope | undefined): boolean {
+ return !!p && typeof p.scope === 'string' && p.scope.trim().length > 0;
+}
+
+/**
+ * Union of path-scope grants keyed by resolved path: the same path granted
+ * twice unions its modes. Used by the permission migration to fold legacy
+ * persona Access grants into the permissions.yaml paths block.
*/
-function mergeScopeGrants(
- fileScopes: BotPathScope[] | undefined,
- personaScopes: BotPathScope[],
+export function mergePathScopes(
+ baseScopes: BotPathScope[] | undefined,
+ extraScopes: BotPathScope[],
): BotPathScope[] {
- if (personaScopes.length === 0) return fileScopes ?? [];
- const merged = [...(fileScopes ?? [])];
- for (const grant of personaScopes) {
+ if (extraScopes.length === 0) return baseScopes ?? [];
+ const merged = [...(baseScopes ?? [])];
+ for (const grant of extraScopes) {
const key = normalizeScopeKey(grant.scope);
const existing = merged.find(p => normalizeScopeKey(p.scope) === key);
if (existing) {
@@ -178,18 +197,6 @@ function normalizeScopeKey(scope: string): string {
return scope === 'self' ? 'self' : resolve(scope.replace(/^~/, homedir())).toLowerCase();
}
-/**
- * Bot path scopes from permissions.yaml + persona Access grants. 'self'
- * resolves to the bot's own profile dir; everything else resolves against
- * cwd or home (~). An unconfigured bot gets NO filesystem access
- * (fail-closed) — but the store always writes a default self scope at
- * creation.
- */
-/** A scope entry is usable only with a non-empty string scope. */
-function isValidScopeEntry(p: BotPathScope | undefined): boolean {
- return !!p && typeof p.scope === 'string' && p.scope.trim().length > 0;
-}
-
function buildBotScopes(paths: BotPathScope[] | undefined, botDir: string): Array<{ path: string; read: boolean; write: boolean; execute?: boolean }> {
const scopes: Array<{ path: string; read: boolean; write: boolean; execute?: boolean }> = [];
for (const p of paths ?? []) {
diff --git a/src/bots/store.test.ts b/src/bots/store.test.ts
index 48618fd1..7fe4e293 100644
--- a/src/bots/store.test.ts
+++ b/src/bots/store.test.ts
@@ -41,7 +41,10 @@ describe('BotStore', () => {
expect(m.enabled).toBe(true);
expect(existsSync(join(root, 'researcher', 'bot.yaml'))).toBe(true);
expect(existsSync(join(root, 'researcher', BOT_PERSONA_FILENAME))).toBe(true);
- const perms = store.readPermissions('researcher');
+ // No default permissions.yaml at create — an ABSENT file means fleet
+ // inheritance (crew) or the fail-closed default (solo), materialized by
+ // ensurePermissions on first use.
+ const perms = store.ensurePermissions('researcher');
expect(perms.paths).toEqual([{ scope: 'self', read: true, write: true }]);
const persona = store.readPersona('researcher');
expect(persona).toContain('# Research');
diff --git a/src/bots/store.ts b/src/bots/store.ts
index 5f1ab0a8..e6e3851f 100644
--- a/src/bots/store.ts
+++ b/src/bots/store.ts
@@ -19,6 +19,9 @@ export const BOT_SANDBOX_DIRNAME = 'sandbox';
export const BOT_ENV_FILENAME = '.env';
export const BOT_JOURNAL_FILENAME = 'journal.jsonl';
+/** Fleet nesting cap — mirrors addCrew's 3-level guard (CEO → Lead → Crew). */
+export const MAX_FLEET_DEPTH = 3;
+
/** Lowercase alphanumeric ids — same discipline as skill ids (traversal guard). */
const BOT_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,47}$/;
@@ -114,20 +117,10 @@ falls outside it.
- You never ask the user questions mid-run: if a required input is missing,
state the assumption you are proceeding with.
- If you lack permission for an action, stop and report it in your summary
- instead of attempting a workaround.
-
-## Access
-
-You always have three work areas — never ask permission for these, and do
-not declare them here: your private \`sandbox/\` folder (next to this
-persona file), the fleet \`_shared/\` folder (shared with all bots —
-publish reusable data there even when not asked), and your own profile
-directory. Anything else is denied until it is granted here — one bullet
-per directory (the forms below are examples only; write real bullets to
-grant access):
-\`- ~/some/dir — read\` · \`- ~/other/dir — read, write\` · \`- /usr/local/bin/tool — execute\`.
-A granted directory covers everything inside it. Outside these grants you
-do not act — you stop and report which access you would have needed.
+ instead of attempting a workaround. Permissions are NOT declared here —
+ they live exclusively in your permissions.yaml file (the single source of
+ truth); your private \`sandbox/\`, the fleet \`_shared/\` folder and your
+ own profile directory are always yours.
## Output
@@ -142,7 +135,11 @@ function atomicWrite(filePath: string, content: string, mode: number = 0o600): v
}
/**
- * Filesystem store for bot profiles: `~/.mercury/bots/<id>/`.
+ * Filesystem store for bot profiles. Fleet structure is PHYSICAL: a crew
+ * bot's whole profile lives inside its lead's directory —
+ * `~/.mercury/bots/<lead>/[<mid-lead>/...]/<crew-id>/` — so removing a lead
+ * removes its crew tree with it, and the layout mirrors the hierarchy the
+ * manifests already describe. Solos and leads live at the root.
* Mirrors SkillStore's dependency-injected-root testability and traversal
* guards, and SessionRepository's atomic tmp+rename writes.
*/
@@ -150,6 +147,12 @@ export class BotStore {
readonly botsRoot: string;
/** mtime-validated manifest cache (see get()) — write paths keep it fresh. */
private manifestCache = new Map<string, { mtimeMs: number; manifest: BotManifest }>();
+ /** id → absolute profile dir; populated on first resolution (scan), kept
+ * fresh by every write path. Cleared on delete/relocate. */
+ private locationCache = new Map<string, string>();
+ /** Wired by BotManager: a bot's profile dir moved (re-parent or migration) —
+ * open journal handles and registry caches for that id are stale. */
+ onRelocate: ((id: string, oldDir: string, newDir: string) => void) | null = null;
constructor(botsRoot?: string) {
this.botsRoot = resolve(botsRoot ?? join(getMercuryHome(), 'bots'));
@@ -158,12 +161,45 @@ export class BotStore {
/** Bot directory for an id, with traversal guard. Throws on invalid ids. */
botDir(id: string): string {
assertValidBotId(id);
- const dir = resolve(this.botsRoot, id);
+ const cached = this.locationCache.get(id);
+ if (cached) return cached;
+ const dir = this.resolveBotDir(id);
+ this.locationCache.set(id, dir);
+ return dir;
+ }
+
+ /**
+ * Resolve a bot's profile dir. Flat-first (solos/leads + any legacy crew
+ * dirs), then a depth-bounded scan for the nested crew profile — the
+ * parent id lives INSIDE the crew's manifest, so the directory is the
+ * only place the location can be discovered from.
+ */
+ private resolveBotDir(id: string): string {
const root = resolve(this.botsRoot);
- if (!dir.startsWith(root + sep)) {
- throw new Error(`Invalid bot id "${id}": escapes the bots root`);
+ const flat = resolve(root, id);
+ if (existsSync(join(flat, BOT_MANIFEST_FILENAME))) return flat;
+ const nested = this.scanForBotDir(root, id, 0);
+ return nested ?? flat;
+ }
+
+ private scanForBotDir(dir: string, id: string, depth: number): string | undefined {
+ if (depth >= MAX_FLEET_DEPTH) return undefined;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return undefined;
}
- return dir;
+ const root = resolve(this.botsRoot);
+ for (const entry of entries) {
+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;
+ const sub = join(dir, entry.name);
+ if (!resolve(sub).startsWith(root + sep)) continue;
+ if (entry.name === id && existsSync(join(sub, BOT_MANIFEST_FILENAME))) return sub;
+ const deeper = this.scanForBotDir(sub, id, depth + 1);
+ if (deeper) return deeper;
+ }
+ return undefined;
}
/** The bot's private sandbox workspace (inside its profile dir — purged on delete). */
@@ -208,22 +244,90 @@ export class BotStore {
list(): BotManifest[] {
if (!existsSync(this.botsRoot)) return [];
const manifests: BotManifest[] = [];
- for (const entry of readdirSync(this.botsRoot, { withFileTypes: true })) {
- if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;
+ // Fleet layout is physical: crew profiles nest inside their lead's dir,
+ // so walk the tree (bounded by the fleet depth cap). Data dirs without a
+ // bot.yaml (sandbox/, skills/, rotations) are descended harmlessly but
+ // never counted as bots.
+ const visit = (dir: string, depth: number): void => {
+ let entries;
try {
- const m = this.get(entry.name);
- if (m) manifests.push(m);
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;
+ const sub = join(dir, entry.name);
+ try {
+ const m = this.get(entry.name);
+ if (m) manifests.push(m);
+ } catch (err: any) {
+ logger.warn({ dir: sub, err: err?.message }, 'Skipping unreadable bot profile');
+ }
+ if (depth < MAX_FLEET_DEPTH) visit(sub, depth + 1);
+ }
+ };
+ visit(this.botsRoot, 1);
+ this.reconcileFleetPlacement(manifests);
+ return manifests.sort((a, b) => a.id.localeCompare(b.id));
+ }
+
+ /**
+ * Strict fleet layout reconciliation: the folder tree and the manifests
+ * must agree, and BOTH hand-authoring paths converge (this is what makes
+ * manually created fleet folders first-class):
+ * - A bot.yaml dropped manually inside a lead's directory is ADOPTED as
+ * that lead's crew (manifest gains parent, fleetRole, comms back).
+ * - A manifest that names a parent (hand-edited or manager-written)
+ * has its profile dir MOVED under that lead.
+ * When both disagree (folder under A, manifest says B), the manifest is
+ * the newer intent and wins — same rule as every other live hand-edit.
+ * Deleting crews whose lead vanished stays a startup-migration rule: a
+ * transient hand-edit must not cascade-delete bots mid-session.
+ */
+ private reconcileFleetPlacement(manifests: BotManifest[]): void {
+ for (const m of manifests) {
+ try {
+ const physical = this.physicalFleetParent(m.id);
+ if (m.parent && m.parent !== physical) {
+ if (this.exists(m.parent)) {
+ this.relocateToParent(m);
+ }
+ // Missing lead: migrateFleetLayout cascade-deletes at startup.
+ } else if (!m.parent && physical && physical !== m.id) {
+ const lead = this.get(physical);
+ if (lead) {
+ this.update(m.id, mm => {
+ mm.parent = physical;
+ mm.fleetRole = 'crew';
+ mm.comms = { ...mm.comms, canMessage: [...new Set([...(mm.comms?.canMessage ?? []), physical])] };
+ });
+ logger.info({ botId: m.id, leadId: physical }, 'Manually created fleet folder adopted into the lead\'s crew');
+ }
+ }
} catch (err: any) {
- logger.warn({ botId: entry.name, err: err?.message }, 'Skipping unreadable bot profile');
+ logger.warn({ botId: m.id, err: err?.message }, 'Fleet placement reconciliation failed — leaving profile as-is');
}
}
- return manifests.sort((a, b) => a.id.localeCompare(b.id));
+ }
+
+ /** The bot id owning the directory this profile lives in (undefined at the bots root). */
+ private physicalFleetParent(id: string): string | undefined {
+ const parentDir = resolve(this.botDir(id), '..');
+ if (parentDir === resolve(this.botsRoot)) return undefined;
+ if (!existsSync(join(parentDir, BOT_MANIFEST_FILENAME))) return undefined;
+ const owner = parentDir.split(sep).pop()!;
+ assertValidBotId(owner);
+ return owner;
}
get(id: string): BotManifest | null {
const file = join(this.botDir(id), BOT_MANIFEST_FILENAME);
if (!existsSync(file)) {
this.manifestCache.delete(id);
+ // A cached location whose manifest has vanished is a dead entry (the
+ // id may have been deleted, or never existed) — force a fresh scan.
+ this.locationCache.delete(id);
return null;
}
// mtime-validated cache: getStatusSummaries() runs on the TUI's 2s status
@@ -272,8 +376,11 @@ export class BotStore {
if (errors.length > 0) {
throw new Error(`Invalid bot manifest: ${errors.join('; ')}`);
}
-
- const dir = this.botDir(id);
+ // Fleet layout: a crew bot's profile is created INSIDE its lead's
+ // directory. The lead must exist — fail closed rather than placing a
+ // profile the hierarchy cannot account for.
+ const dir = manifest.parent ? this.resolveNestedDir(manifest.parent, id) : this.botDir(id);
+ this.locationCache.set(id, dir);
mkdirSync(dir, { recursive: true });
this.ensureSandboxes(id);
this.save(manifest);
@@ -281,18 +388,16 @@ export class BotStore {
if (!existsSync(personaFile)) {
writeFileSync(personaFile, input.persona ?? DEFAULT_PERSONA_TEMPLATE(input.name, input.description), 'utf-8');
}
- const permFile = join(dir, BOT_PERMISSIONS_FILENAME);
- if (!existsSync(permFile)) {
- // Fail-closed default: only the bot's own dir, read+write.
- this.writePermissions(id, {
- paths: [{ scope: 'self', read: true, write: true }],
- });
- }
+ // NO default permissions.yaml here: an ABSENT file is meaningful — a
+ // crew bot inherits its lead's file verbatim (ensurePermissions), and a
+ // solo falls back to the fail-closed default. A tier choice, fleet
+ // inheritance, or the startup migration materializes the file.
return manifest;
}
save(manifest: BotManifest): void {
assertValidBotId(manifest.id);
+ this.assertFleetParentValid(manifest);
const dir = this.botDir(manifest.id);
if (!existsSync(dir)) {
throw new Error(`Bot "${manifest.id}" does not exist`);
@@ -313,6 +418,9 @@ export class BotStore {
if (!manifest) throw new Error(`Bot "${id}" does not exist`);
mutator(manifest);
manifest.updatedAt = new Date().toISOString();
+ // Re-parent moves the profile dir to keep the physical layout in sync
+ // (crew nested under its lead; promote/detach moves back to the root).
+ this.relocateToParent(manifest);
this.save(manifest);
return manifest;
}
@@ -324,12 +432,72 @@ export class BotStore {
delete(id: string): void {
const dir = this.botDir(id);
if (existsSync(dir)) {
+ // Fleet layout is physical: crew profiles live INSIDE their lead's
+ // dir, so this removes the whole crew tree with the lead.
rmSync(dir, { recursive: true, force: true });
this.manifestCache.delete(id);
+ this.locationCache.delete(id);
logger.info({ botId: id }, 'Bot profile deleted');
}
}
+ // ---- fleet placement ------------------------------------------------------
+
+ /**
+ * The profile dir a bot with this manifest should occupy: nested under its
+ * lead's dir, or at the root for solos/leads. Fails closed if the lead is
+ * unknown. Pure computation — no filesystem writes.
+ */
+ private resolveNestedDir(parentId: string, id: string): string {
+ assertValidBotId(parentId);
+ if (!this.exists(parentId)) {
+ throw new Error(`Parent bot "${parentId}" does not exist`);
+ }
+ return join(this.botDir(parentId), id);
+ }
+
+ /** Fail closed on dangling parents and hierarchy cycles before any write. */
+ private assertFleetParentValid(manifest: BotManifest): void {
+ if (!manifest.parent) return;
+ assertValidBotId(manifest.parent);
+ if (!this.exists(manifest.parent)) {
+ throw new Error(`Parent bot "${manifest.parent}" does not exist`);
+ }
+ let ancestor: string | undefined = manifest.parent;
+ const seen = new Set([manifest.id]);
+ let depth = 0;
+ while (ancestor) {
+ if (seen.has(ancestor)) {
+ throw new Error(`Fleet cycle detected at "${ancestor}"`);
+ }
+ seen.add(ancestor);
+ if (++depth > MAX_FLEET_DEPTH) {
+ throw new Error(`Fleet nesting exceeds ${MAX_FLEET_DEPTH} levels`);
+ }
+ const next: string | undefined = this.get(ancestor)?.parent;
+ ancestor = next ?? undefined;
+ }
+ }
+
+ /**
+ * Move a bot's profile to where its manifest's parent says it belongs
+ * (idempotent no-op when it is already there). Used by re-parenting
+ * updates and the startup migration. Fires onRelocate so open journal
+ * handles and runtime caches for the id are refreshed.
+ */
+ relocateToParent(manifest: BotManifest): boolean {
+ const current = this.botDir(manifest.id);
+ const target = manifest.parent ? this.resolveNestedDir(manifest.parent, manifest.id) : resolve(this.botsRoot, manifest.id);
+ if (resolve(current) === resolve(target)) return false;
+ if (!existsSync(current)) return false;
+ mkdirSync(resolve(target, '..'), { recursive: true });
+ renameSync(current, target);
+ this.locationCache.set(manifest.id, resolve(target));
+ this.onRelocate?.(manifest.id, current, resolve(target));
+ logger.info({ botId: manifest.id, from: current, to: resolve(target) }, 'Bot profile relocated to its fleet parent');
+ return true;
+ }
+
readPersona(id: string): string {
const manifest = this.get(id);
const personaName = manifest?.persona ?? BOT_PERSONA_FILENAME;
@@ -349,6 +517,35 @@ export class BotStore {
return (parseYaml(readFileSync(file, 'utf-8')) ?? {}) as BotPermissionsFile;
}
+ /**
+ * Fleet permission inheritance — the crew rule: a crew bot runs on its
+ * LEAD's permissions verbatim unless it has an explicitly edited file of
+ * its own. Resolution:
+ * - permissions.yaml exists → that file (explicit; edits stick).
+ * - absent + the bot has a lead → the lead's file is COPIED into the
+ * crew's dir (copy-paste semantics: from then on the crew owns it and
+ * later lead changes do not propagate — exactly "inherit unless the
+ * user edits"). `self` scopes resolve per-bot at registry build, so a
+ * verbatim copy is safe.
+ * - absent + no lead (solo) → the fail-closed default is materialized
+ * (own profile dir, read+write).
+ */
+ ensurePermissions(id: string): BotPermissionsFile {
+ const file = join(this.botDir(id), BOT_PERMISSIONS_FILENAME);
+ if (existsSync(file)) return this.readPermissions(id);
+ const manifest = this.get(id);
+ const leadId = manifest?.parent;
+ if (leadId && this.exists(leadId)) {
+ const leadPerms = this.readPermissions(leadId);
+ const inherited = Object.keys(leadPerms).length > 0 ? leadPerms : DEFAULT_BOT_PERMISSIONS;
+ this.writePermissions(id, inherited);
+ logger.info({ botId: id, leadId }, 'Crew permissions inherited from its lead (copied verbatim)');
+ return inherited;
+ }
+ this.writePermissions(id, DEFAULT_BOT_PERMISSIONS);
+ return DEFAULT_BOT_PERMISSIONS;
+ }
+
writePermissions(id: string, permissions: BotPermissionsFile): void {
atomicWrite(join(this.botDir(id), BOT_PERMISSIONS_FILENAME), stringifyYaml(permissions));
}
@@ -365,6 +562,11 @@ export class BotStore {
}
}
+/** Fail-closed baseline for a bot with no permissions.yaml and no lead. */
+const DEFAULT_BOT_PERMISSIONS: BotPermissionsFile = {
+ paths: [{ scope: 'self', read: true, write: true }],
+};
+
function treeSize(dir: string): number {
let total = 0;
try {
diff --git a/src/bots/types.ts b/src/bots/types.ts
index 9d788c14..754c4f25 100644
--- a/src/bots/types.ts
+++ b/src/bots/types.ts
@@ -101,9 +101,10 @@ export interface BotManifest {
/**
* Per-bot permission manifest — `~/.mercury/bots/<id>/permissions.yaml`.
- * Deliberately minimal: bots are fail-closed, so only explicit grants exist.
- * There are no auto-approve lists for bots by design (P0-4 wires this into a
- * bot-local PermissionManager).
+ * THE single source of truth for what a bot may do (tool gate + path scopes
+ * + shell lists) — bot.yaml carries identity/fleet/schedules only, and the
+ * persona carries character only. Deliberately minimal: bots are
+ * fail-closed, so only explicit grants exist.
*/
export interface BotPermissionsFile {
paths?: BotPathScope[];
@@ -117,6 +118,13 @@ export interface BotPermissionsFile {
* "*" (allow-all) is rejected.
*/
autoApproveCommands?: string[];
+ /**
+ * The tool gate — which capability tools the bot sees at all. Deny wins
+ * over allow; a non-empty allow restricts the toolset to exactly that
+ * list. Interactive/global-mutation tools are stripped for bots regardless.
+ * (Formerly bot.yaml's tools block — migrated here; bot.yaml is legacy.)
+ */
+ tools?: { allow?: string[]; deny?: string[] };
}
export interface BotPathScope {
diff --git a/src/channels/cli-bot-live.test.ts b/src/channels/cli-bot-live.test.ts
new file mode 100644
index 00000000..d25980a9
--- /dev/null
+++ b/src/channels/cli-bot-live.test.ts
@@ -0,0 +1,39 @@
+import { describe, it, expect } from 'vitest';
+import { CLIChannel } from './cli.js';
+
+/**
+ * Per-bot live activity routing: while a bot runs, its OPEN thread shows a
+ * live region ("what is this bot doing right now"); turn-end clears it. The
+ * region must not flicker on tool-finish events (the running label stays).
+ */
+describe('CLIChannel per-bot live activity', () => {
+ it('follows the bot activity bus and clears on turn-end', () => {
+ const ch = new CLIChannel();
+
+ ch.setBotLiveActivity('worker', { kind: 'turn-start', label: 'scrape the prices' });
+ expect(ch.getTuiState().botLiveActivity['worker']).toMatchObject({ phase: 'Working', detail: 'scrape the prices' });
+
+ ch.setBotLiveActivity('worker', { kind: 'step', label: 'step 1' });
+ expect(ch.getTuiState().botLiveActivity['worker']).toMatchObject({ phase: 'step 1', stepsDone: 1 });
+
+ ch.setBotLiveActivity('worker', { kind: 'tool', label: 'read_file ~/cookies', status: 'running' });
+ expect(ch.getTuiState().botLiveActivity['worker']).toMatchObject({ phase: 'read_file ~/cookies' });
+
+ // A tool finish keeps the last running label (no flicker).
+ ch.setBotLiveActivity('worker', { kind: 'tool', label: 'read_file ~/cookies', status: 'done' });
+ expect(ch.getTuiState().botLiveActivity['worker']).toMatchObject({ phase: 'read_file ~/cookies' });
+
+ // An error shows inline.
+ ch.setBotLiveActivity('worker', { kind: 'tool', label: 'run_command curl', status: 'error', detail: 'permission denied' });
+ expect(ch.getTuiState().botLiveActivity['worker']).toMatchObject({ detail: '✗ run_command curl — permission denied' });
+
+ ch.setBotLiveActivity('worker', { kind: 'turn-end', label: 'completed' });
+ expect(ch.getTuiState().botLiveActivity['worker']).toBeUndefined();
+
+ // Other bots' regions are untouched.
+ ch.setBotLiveActivity('other', { kind: 'turn-start', label: 'other work' });
+ ch.setBotLiveActivity('worker', { kind: 'turn-end', label: 'done' });
+ expect(ch.getTuiState().botLiveActivity['other']).toBeDefined();
+ expect(ch.getTuiState().botLiveActivity['worker']).toBeUndefined();
+ });
+});
\ No newline at end of file
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index f300f9e6..c7cd3bea 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -326,6 +326,9 @@ export interface TuiState {
updateAvailable: string | null;
/** Active Mercury Bot chat — transcript is swapped to the bot's thread. */
botChat: { botId: string; botName: string } | null;
+ /** Per-bot real-time activity (what each bot is doing RIGHT NOW) — rendered
+ * as a live region in an open bot thread, keyed by bot id. */
+ botLiveActivity: Record<string, LiveActivityState>;
/** Live bot roster (drives `/bots` argument autocomplete and badges). */
botRoster: Array<{ id: string; name: string; state: string; needsYou: boolean; fleetRole?: 'lead' | 'crew'; parent?: string }>;
}
@@ -363,6 +366,7 @@ const defaultState: TuiState = {
tuiFrozen: false,
updateAvailable: null,
botChat: null,
+ botLiveActivity: {},
botRoster: [],
};
@@ -1776,6 +1780,39 @@ export class CLIChannel extends BaseChannel {
if (existing) this.update({ liveActivity: { ...existing, stepsDone: existing.stepsDone + 1 } });
}
+ /**
+ * Per-bot real-time activity: what a bot is doing RIGHT NOW, rendered as a
+ * live region inside its open thread (same spinner block the main chat
+ * gets). Events arrive from the bot activity bus (BotManager.onBotActivity).
+ * Mapping: turn-start → "Working on: <task>"; step/tool labels follow the
+ * actual work; tool finishes keep the last running label (less churn);
+ * turn-end clears the region.
+ */
+ setBotLiveActivity(botId: string, ev: { kind: 'turn-start' | 'step' | 'tool' | 'turn-end'; label: string; detail?: string; status?: string }): void {
+ const map = { ...this.state.botLiveActivity };
+ if (ev.kind === 'turn-end') {
+ if (!map[botId]) return;
+ delete map[botId];
+ this.update({ botLiveActivity: map });
+ return;
+ }
+ // A finished tool keeps its label until the next event — the region
+ // should not flicker to an intermediate state and back.
+ if (ev.kind === 'tool' && ev.status === 'done' && map[botId]) return;
+ const existing = map[botId];
+ map[botId] = {
+ phase: ev.kind === 'turn-start' ? 'Working' : ev.label,
+ detail: ev.kind === 'turn-start'
+ ? ev.label.slice(0, 80)
+ : ev.status === 'error'
+ ? `✗ ${ev.label}${ev.detail ? ` — ${ev.detail}` : ''}`
+ : undefined,
+ stepsDone: ev.kind === 'step' ? (existing?.stepsDone ?? 0) + 1 : (existing?.stepsDone ?? 0),
+ startedAt: existing?.startedAt ?? Date.now(),
+ };
+ this.update({ botLiveActivity: map });
+ }
+
/** Clear the live activity block (task finished or idle). */
clearLiveActivity(): void {
// Turn-end cleanup: clear the phase AND the thinking state together.
diff --git a/src/channels/web.ts b/src/channels/web.ts
index b192bbd9..ccab6188 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -17,7 +17,7 @@ interface PendingInteraction {
}
export interface ChatEvent {
- type: 'thinking' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error';
+ type: 'thinking' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity';
data?: Record<string, unknown>;
}
@@ -94,6 +94,16 @@ export class WebChannel extends BaseChannel {
this.sseClients.delete(id);
}
+ /**
+ * Real-time bot activity feed: what each Mercury bot is doing RIGHT NOW
+ * (step, tool calls, turn lifecycle). Broadcast to every connected web
+ * session — the dashboard / third-party backends consume these for live
+ * bot views. Bot turns never carry text deltas, only activity labels.
+ */
+ broadcastBotActivity(ev: { botId: string; jobId: string; kind: string; label: string; detail?: string; stepIndex: number; elapsedMs: number; status?: string }): void {
+ this.broadcast({ type: 'bot_activity', data: { ...ev } });
+ }
+
private broadcast(event: ChatEvent): boolean {
let delivered = true;
const targetId = typeof event.data?.targetId === 'string' ? event.data.targetId : undefined;
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 9f276aee..b2fec2e4 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1,5 +1,6 @@
import { generateText, streamText, stepCountIs } from 'ai';
import path from 'node:path';
+import { homedir } from 'node:os';
import { existsSync, readdirSync } from 'node:fs';
import { getHeapStatistics } from 'node:v8';
import type { ChannelMessage, ChannelType } from '../types/channel.js';
@@ -26,7 +27,8 @@ import type { SkillLoader } from '../skills/loader.js';
import { logger } from '../utils/logger.js';
import { refinePersona } from '../bots/persona-template.js';
import { proposeCrew } from '../bots/fleet-onboarding.js';
-import { PERMISSION_TIERS, applyPermissionTier, isPermissionTier, type PermissionTier } from '../bots/permission-tiers.js';
+import { PERMISSION_TIERS, tierPermissionsFile, isPermissionTier, type PermissionTier } from '../bots/permission-tiers.js';
+import { buildBotBundle, writeBundle, readBundle, importBotBundle } from '../bots/bundle.js';
import { applyBotFieldPatch } from '../bots/edit.js';
import { CLIChannel } from '../channels/cli.js';
import { TelegramChannel } from '../channels/telegram.js';
@@ -1227,7 +1229,12 @@ export class Agent {
choice = 'Read-only (recommended default)';
}
const tier = (Object.entries(PERMISSION_TIERS).find(([, t]) => choice.startsWith(t.label))?.[0] ?? 'readonly') as PermissionTier;
- bm.store.update(botId, m => applyPermissionTier(m, tier));
+ // The tier must EXECUTE: write the full permission file (tool gate +
+ // path scopes) — the single source of truth. The old manifest-only write
+ // left the path gate at fail-closed defaults, so a "full access" bot
+ // still could not read anything outside its sandbox.
+ bm.store.writePermissions(botId, tierPermissionsFile(tier));
+ bm.store.update(botId, m => { delete (m as any).tools; });
bm.invalidateRuntime(botId);
await channel.send(`🔐 Permissions for **${botName}**: **${PERMISSION_TIERS[tier].label}**. Change anytime with \`/bots permissions ${botId} <readonly|builder|operator|full>\`.`, `bot:${botId}`).catch(() => {});
}
@@ -1441,10 +1448,16 @@ export class Agent {
const fmt = (s: typeof summaries[number], indent: string) => {
const icon = stateIcons[s.state] ?? '❓';
const badge = s.fleetRole === 'lead' ? ' 👑' : '';
- const lastRun = s.lastRunAt ? ` · last ${(s.lastRunState ?? '')} ${formatRelative(s.lastRunAt)}` : '';
+ // Crew runs are short and asynchronous — a snapshot rarely catches
+ // them green. Make activity legible anyway: leads show how many crew
+ // are working right now, every bot shows its last run outcome.
+ const crewNote = s.fleetRole === 'lead' && s.crewWorking
+ ? ` · 🟢 ${s.crewWorking} crew working`
+ : '';
+ const lastRun = s.lastRunAt ? ` · last run ${s.lastRunState ?? '?'} ${formatRelative(s.lastRunAt)}` : '';
const activity = s.activity ? `\n${indent} ↳ ${s.activity}` : '';
const attention = s.needsYou ? ' · ⚠ needs you' : '';
- return `${indent}${icon} **${s.name}** (${s.id})${badge} — ${s.state}${attention}${lastRun}${activity}`;
+ return `${indent}${icon} **${s.name}** (${s.id})${badge} — ${s.state}${crewNote}${attention}${lastRun}${activity}`;
};
const lines: string[] = [`**Bots** (${summaries.length})`, ''];
const rendered = new Set<string>();
@@ -1654,7 +1667,7 @@ export class Agent {
}
if (!confirmed && typeof (channel as any).askToContinue === 'function') {
const crewCount = bm.store.crewOf(target).length;
- const proceed = await (channel as any).askToContinue(`Delete bot **${target}** and its profile (persona, memory links, journal)? This cannot be undone.${crewCount > 0 ? ` Its ${crewCount} crew member(s) will be detached and become solo bots.` : ''}`);
+ const proceed = await (channel as any).askToContinue(`Delete bot **${target}** and its profile (persona, memory links, journal)? This cannot be undone.${crewCount > 0 ? ` Its ${crewCount} crew member(s) will be deleted with it (fleet cascade).` : ''}`);
if (!proceed) {
await channel.send('Deletion cancelled.', channelId);
return;
@@ -1674,6 +1687,49 @@ export class Agent {
return;
}
+ if (action === 'export') {
+ // /bots export <id> [path] — a shareable bundle: manifests + personas +
+ // permissions + skills (single JSON; a lead's bundle carries its whole
+ // crew tree). Sandbox, journal, and .env never travel.
+ const target = parts[1]?.toLowerCase();
+ if (!target || !bm.store.exists(target)) {
+ await channel.send('Usage: `/bots export <id> [outPath]` — writes a shareable JSON bundle (fleet leads include their crew).', channelId);
+ return;
+ }
+ try {
+ const bundle = buildBotBundle(bm.store, target);
+ const outPath = parts.slice(2).join(' ') || undefined;
+ const path = writeBundle(bundle, outPath?.trim() || undefined);
+ const crewNote = bundle.kind === 'fleet' ? ` (fleet — ${bundle.bots.length} bots incl. crew)` : '';
+ await channel.send(`📦 Exported **${target}**${crewNote} → \`${path}\`\nIncluded: manifests, personas, permissions, skills. Never included: sandbox, journals, .env (local state + secrets).`, channelId);
+ } catch (err: any) {
+ await channel.send(`Export failed: ${err?.message}`, channelId);
+ }
+ return;
+ }
+
+ if (action === 'import') {
+ // /bots import <path> — recreate bots from a bundle. Imported bots
+ // start DISABLED (fail-closed); enable each one consciously.
+ const rawPath = parts.slice(1).join(' ').trim();
+ if (!rawPath) {
+ await channel.send('Usage: `/bots import <bundlePath>` — recreates bots from a `.bot.json` bundle. Imported bots start disabled; enable with `/bots enable <id>`.', channelId);
+ return;
+ }
+ try {
+ const bundle = readBundle(rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath);
+ const report = importBotBundle(bm.store, bundle, { overwrite: parts.includes('--overwrite') });
+ const lines: string[] = [];
+ if (report.created.length > 0) lines.push(`✅ Created: ${report.created.map(id => `\`${id}\``).join(', ')} (disabled — enable with \`/bots enable <id>\`)`);
+ for (const s of report.skipped) lines.push(`⏭ \`${s.id}\`: ${s.reason}`);
+ if (lines.length === 0) lines.push('Nothing to import.');
+ await channel.send(`📥 Import from \`${rawPath}\`:\n${lines.join('\n')}`, channelId);
+ } catch (err: any) {
+ await channel.send(`Import failed: ${err?.message}`, channelId);
+ }
+ return;
+ }
+
if (action === 'stop' || action === 'pause') {
const target = parts[1]?.toLowerCase();
if (!target) {
@@ -1681,11 +1737,11 @@ export class Agent {
return;
}
const result = await bm.stop(target);
- const heldNote = result.heldJobs > 0 ? `\n↩ ${result.heldJobs} queued job(s) held — resume with \`/bots start ${target}\`.` : '';
+ const crewNote = result.crewStopped > 0 ? `\n🛑 Fleet cascade: ${result.crewStopped} crew bot(s) stopped with it.` : '';
+ const heldNote = result.heldJobs > 0 ? `\n↩ ${result.heldJobs} queued job(s) held fleet-wide — resume with \`/bots start ${target}\`.` : '';
await channel.send(result.halted
- ? `⛔ Halt signal sent to **${target}** — it will stop after the current tool step.${heldNote}`
- : `⛔ **${target}** stopped — nothing was running.${heldNote}`, channelId);
- return;
+ ? `⛔ Halt signal sent to **${target}** — it will stop after the current tool step.${crewNote}${heldNote}`
+ : `⛔ **${target}** stopped — nothing was running.${crewNote}${heldNote}`, channelId);
}
if (action === 'start') {
@@ -1810,21 +1866,23 @@ export class Agent {
return;
}
if (!tierArg) {
- const m = bm.store.get(target)!;
- const deny = new Set(m.tools?.deny ?? []);
+ const perms = bm.store.readPermissions(target);
+ const deny = new Set(perms.tools?.deny ?? bm.store.get(target)?.tools?.deny ?? []);
const matched = Object.entries(PERMISSION_TIERS).find(([, t]) => t.deny.length === deny.size && t.deny.every(d => deny.has(d)))?.[0];
const current = matched ?? 'custom';
const effective = deny.has('run_command') ? 'no shell' : 'shell within its path scopes';
- await channel.send(`🔐 **${target}**: ${current} (deny: ${[...deny].join(', ') || 'none'}) — ${effective}. Set with \`/bots permissions ${target} <readonly|builder|operator|full>\`.`, channelId);
+ const scopeCount = perms.paths?.length ?? 0;
+ await channel.send(`🔐 **${target}**: ${current} (deny: ${[...deny].join(', ') || 'none'}, path scopes: ${scopeCount}) — ${effective}. Source: its permissions.yaml. Set with \`/bots permissions ${target} <readonly|builder|operator|full>\`.`, channelId);
return;
}
if (!isPermissionTier(tierArg)) {
await channel.send('Unknown tier — use `readonly`, `builder`, `operator`, or `full`.', channelId);
return;
}
- bm.store.update(target, m => applyPermissionTier(m, tierArg));
+ bm.store.writePermissions(target, tierPermissionsFile(tierArg));
+ bm.store.update(target, m => { delete (m as any).tools; });
bm.invalidateRuntime(target);
- await channel.send(`🔐 Permissions for **${target}**: **${PERMISSION_TIERS[tierArg].label}** — ${PERMISSION_TIERS[tierArg].description}\n(Path scopes are untouched and always enforced.)`, channelId);
+ await channel.send(`🔐 Permissions for **${target}**: **${PERMISSION_TIERS[tierArg].label}** — ${PERMISSION_TIERS[tierArg].description}\n(Written to its permissions.yaml — the single source of truth.)`, channelId);
return;
}
diff --git a/src/index.ts b/src/index.ts
index 857afba8..55af55df 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2487,9 +2487,23 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
},
});
botManager.setScheduler(scheduler);
- botManager.registerRoutines(scheduler);
+ // Startup migrations must run before routines register: fleet layout
+ // (crew nesting + orphan cascade) and permission consolidation to the
+ // single permissions.yaml source.
+ void botManager.migrateFleetLayout()
+ .then(() => botManager.migratePermissions())
+ .then(() => botManager.registerRoutines(scheduler));
agent.setBotManager(botManager);
setWebBotManager(botManager);
+ // Real-time bot activity bus → surfaces: the CLI bot-thread live region
+ // (what the bot is doing RIGHT NOW while you watch its thread) and the
+ // web SSE feed (dashboards / third-party backends). The roster's activity
+ // label is updated inside the manager itself.
+ const botCliChannel = channels.get('cli');
+ botManager.onBotActivity((ev) => {
+ if (botCliChannel instanceof CLIChannel) botCliChannel.setBotLiveActivity(ev.botId, ev);
+ webChannel.broadcastBotActivity(ev);
+ });
if (config.bots?.webhookSecret) {
setBotsWebhookSecret(config.bots.webhookSecret);
}
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index f04f75dd..6c35f554 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -1264,6 +1264,14 @@ function ChatBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines
<ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />
{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}
{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}
+ {state.botChat && !state.isThinking && (
+ <BotFleetLiveRegion
+ botId={state.botChat.botId}
+ botName={state.botChat.botName}
+ botLiveActivity={state.botLiveActivity ?? {}}
+ botRoster={state.botRoster}
+ />
+ )}
{state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} />}
</Box>
</Box>
@@ -1314,6 +1322,14 @@ function CodingBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLin
<ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />
{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}
{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}
+ {state.botChat && !state.isThinking && (
+ <BotFleetLiveRegion
+ botId={state.botChat.botId}
+ botName={state.botChat.botName}
+ botLiveActivity={state.botLiveActivity ?? {}}
+ botRoster={state.botRoster}
+ />
+ )}
<Box paddingX={1} marginTop={1}>
<Text dimColor>Mode shortcuts: Ctrl+P Plan · Ctrl+X Execute (Auto runs by default)</Text>
</Box>
@@ -2017,7 +2033,7 @@ function ToolStepsView({ steps, viewMode, idle }: { steps: ToolStep[]; viewMode:
);
}
-function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPreview, frozen }: { agentName: string; steps: ToolStep[]; mode: AppMode; liveActivity?: LiveActivityState | null; thinkingPreview?: string | null; frozen?: boolean }) {
+function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPreview, frozen, title, longOpHint }: { agentName: string; steps: ToolStep[]; mode: AppMode; liveActivity?: LiveActivityState | null; thinkingPreview?: string | null; frozen?: boolean; title?: string; longOpHint?: boolean }) {
const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const [frame, setFrame] = React.useState(0);
const [elapsed, setElapsed] = React.useState(0);
@@ -2067,12 +2083,14 @@ function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPrevi
<Box>
<Text color={actionTone === 'white' ? 'cyan' : actionTone}>{spinner}</Text>
<Text> </Text>
- <Text color="cyan" bold>Processing</Text>
+ <Text color="cyan" bold>{title ?? 'Processing'}</Text>
<Text dimColor>{totalSteps > 0 ? ` · step ${totalSteps} · ${timeStr}` : ` · ${timeStr}`}</Text>
</Box>
<Box marginLeft={4}>
<Text color={actionTone} bold>{currentAction}</Text>
- {displayElapsed >= 90 && <Text color="red" dimColor> · long op (/bg current to background, /stop to stop)</Text>}
+ {/* The /bg·/stop hint is main-agent only — bot threads have their own
+ controls, and long tasks are the norm for bots. */}
+ {(longOpHint ?? true) && displayElapsed >= 90 && <Text color="red" dimColor> · long op (/bg current to background, /stop to stop)</Text>}
</Box>
{thinkLine && (
<Box marginLeft={4}>
@@ -2094,6 +2112,60 @@ function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPrevi
);
}
+/**
+ * Fleet live region for an open bot thread: what this bot is doing RIGHT
+ * NOW, and — for a lead — exactly which sub-bot is doing what, recursively
+ * (CEO → Eng Lead → Backend). One self-ticker drives all rows; the rows
+ * also refresh on every activity event.
+ */
+function BotFleetLiveRegion({ botId, botName, botLiveActivity, botRoster }: {
+ botId: string;
+ botName: string;
+ botLiveActivity: Record<string, LiveActivityState>;
+ botRoster: Array<{ id: string; name: string; state: string; fleetRole?: 'lead' | 'crew'; parent?: string }>;
+}) {
+ const own = botLiveActivity[botId];
+ const crew = botRoster.filter(b => b.parent === botId);
+ const crewLive = crew.filter(c => botLiveActivity[c.id]);
+ if (!own && crewLive.length === 0) return null;
+
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
+ const [tick, setTick] = React.useState(0);
+ React.useEffect(() => {
+ const timer = setInterval(() => setTick(v => v + 1), 250);
+ return () => clearInterval(timer);
+ }, []);
+
+ const row = (id: string, name: string, label: string, indent: string): React.ReactNode => {
+ return (
+ <Box key={id}>
+ <Text>{indent}</Text>
+ <Text color="cyan">{frames[tick % frames.length]}</Text>
+ <Text bold> {name} ({id})</Text>
+ <Text dimColor> · {label}</Text>
+ </Box>
+ );
+ };
+
+ const renderCrewTree = (leadId: string, depth: number): React.ReactNode[] => {
+ const out: React.ReactNode[] = [];
+ for (const member of botRoster.filter(b => b.parent === leadId)) {
+ const act = botLiveActivity[member.id];
+ if (act) out.push(row(member.id, member.name, act.detail || act.phase, ' '.repeat(depth)));
+ out.push(...renderCrewTree(member.id, depth + 1));
+ }
+ return out;
+ };
+
+ return (
+ <Box marginTop={1} marginLeft={4} flexDirection="column">
+ {own && row(botId, botName, own.detail || own.phase, '')}
+ {crewLive.length > 0 && <Text dimColor> └ crew working ({crewLive.length}):</Text>}
+ {renderCrewTree(botId, 1)}
+ </Box>
+ );
+}
+
function AgentPanelView({ agents }: { agents: SubAgentInfo[] }) {
if (agents.length === 0) return null;
return (