Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(bots): fleet duplication on reopen + /bots stays inside the bot thread
Salman Qureshi26e0704be5dc
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex 41eacad0..3f8fd562 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -786,7 +786,11 @@ describe('Bot fleets (lead + crew)', () => {expect(manager.addCrew('ceo', { id: 'over-cap', name: 'Over' })).toMatchObject({ ok: false });store.create({ id: 'solo-bot', name: 'Solo' });expect(manager.addCrew('solo-bot', { id: 'x', name: 'X' })).toMatchObject({ ok: false }); // not a lead- expect(manager.addCrew('ceo', { id: 'researcher', name: 'Dup' })).toMatchObject({ ok: false }); // exists+ // Replay-safety: re-adding a member the lead already has (by id or+ // normalized name) is a no-op success, not a duplicate bot on disk.+ expect(manager.addCrew('ceo', { id: 'researcher', name: 'Dup' })).toMatchObject({ ok: true, duplicate: true });+ expect(manager.addCrew('ceo', { id: 'brand-new-id', name: 'researcher' })).toMatchObject({ ok: true, duplicate: true });+ expect(store.list().filter(m => m.parent === 'ceo')).toHaveLength(6);});it('delegated tasks return results to the lead mailbox (attributed)', async () => {diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex fd88566b..9d2f2437 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -854,8 +854,12 @@ export class BotManager {for (const p of proposals) {const result = this.addCrew(botId, p);if (result.ok) {- created++;- hooks.onMember?.(p.name, result.manifest.id);+ // A duplicate (already on the crew) is success without growth —+ // replayed builds converge instead of inflating the roster.+ if (!result.duplicate) {+ created++;+ hooks.onMember?.(p.name, result.manifest.id);+ }} else {hooks.onError?.(`Crew member ${p.name} (${p.id}): ${result.error}`);}@@ -867,7 +871,7 @@ export class BotManager {})();}- addCrew(leadId: string, spec: { id: string; name: string; description?: string; persona?: string }): { ok: true; manifest: BotManifest } | { ok: false; error: string } {+ addCrew(leadId: string, spec: { id: string; name: string; description?: string; persona?: string }): { ok: true; manifest: BotManifest; duplicate?: boolean } | { ok: false; error: string } {const lead = this.store.get(leadId);if (!lead) return { ok: false, error: `No bot "${leadId}"` };if (lead.fleetRole !== 'lead') {@@ -887,16 +891,35 @@ export class BotManager {ancestor = this.store.get(ancestor)?.parent;if (++depth > 3) return { ok: false, error: 'Fleet nesting is capped at 3 levels' };}+ // Replay-safety BEFORE the crew cap: a re-run "build the crew" turn+ // (durable job replayed after an interrupted session) re-derives its+ // specs through the LLM and can land on a DIFFERENT id for a specialist+ // the fleet already has — the id guard alone let the roster grow a+ // duplicate crew per replay. A spec matching an id or the normalized+ // NAME of a member already under THIS lead is already-staffed: success+ // without creation. Only foreign ids / names from another lead are an+ // error. Duplicates skip the cap check — a full fleet stays full.+ const id = spec.id.toLowerCase();+ let existing: BotManifest | null = this.store.exists(id) ? this.store.get(id) : null;+ if (!existing) {+ const nameKey = (spec.name ?? '').trim().toLowerCase();+ if (nameKey) {+ existing = this.store.crewOf(leadId).find(m => m.name.trim().toLowerCase() === nameKey) ?? null;+ }+ }+ if (existing) {+ if (existing.fleetRole === 'crew' && existing.parent === leadId) {+ return { ok: true, manifest: existing, duplicate: true };+ }+ return { ok: false, error: `Bot "${id}" already exists` };+ }const crew = this.store.crewOf(leadId);const cap = this.maxCrew();if (crew.length >= cap) {return { ok: false, error: `Fleet is at the crew cap (${crew.length}/${cap}) — retire a member first or raise BOTS_FLEET_MAX_CREW` };}- if (this.store.exists(spec.id)) {- return { ok: false, error: `Bot "${spec.id}" already exists` };- }const manifest = this.store.create({- id: spec.id.toLowerCase(),+ id,name: spec.name,description: spec.description,persona: spec.persona,diff --git a/src/bots/fleet-replay-idempotency.test.ts b/src/bots/fleet-replay-idempotency.test.tsnew file mode 100644index 00000000..936469f7--- /dev/null+++ b/src/bots/fleet-replay-idempotency.test.ts@@ -0,0 +1,211 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } 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 (fleet build / replay paths).+vi.mock('ai', async (importOriginal) => {+ const actual = await importOriginal<typeof import('ai')>();+ return { ...actual, generateText: vi.fn() };+});++// Windows EBUSY guard: every BotManager owns an open SQLite queue handle;+// afterEach disposes all of them before the tmpdir is deleted.+const activeManagers: Array<{ dispose: () => void }> = [];++function makeManager(root: string): BotManager {+ const config = getDefaultConfig() as MercuryConfig;+ config.bots.maxConcurrent = 4;+ const manager = 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,+ });+ activeManagers.push(manager);+ return manager;+}++const FULL_FLEET = ['research', 'writer', 'editor', 'scout', 'packager', 'checker'];++function buildFleet(manager: BotManager): void {+ const store = manager['store'];+ store.create({ id: 'ceo', name: 'CEO', description: 'lead', manifest: { fleetRole: 'lead' } });+ for (const id of FULL_FLEET) {+ const r = manager.addCrew('ceo', { id, name: id, description: id, persona: 'x'.repeat(40) });+ if (!r.ok) throw new Error(r.error);+ }+}++describe('fleet replay-safety — a rebuilt crew never grows the roster', () => {+ let root: string;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-replay-'));+ manager = makeManager(root);+ });++ afterEach(() => {+ for (const m of activeManagers.splice(0)) m.dispose();+ rmSync(root, { recursive: true, force: true });+ });++ it('re-running the crew build with the SAME ids is a no-op (duplicate:true)', () => {+ buildFleet(manager);+ expect(manager.getStatusSummaries()).toHaveLength(7);+ for (const id of FULL_FLEET) {+ const r = manager.addCrew('ceo', { id, name: id, description: id, persona: 'y'.repeat(40) });+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.duplicate).toBe(true);+ }+ expect(manager.getStatusSummaries()).toHaveLength(7);+ });++ it('a replayed build that RE-DERIVES ids (same names) creates nothing', () => {+ buildFleet(manager);+ // The LLM invents fresh ids for the same specialties — historically this+ // passed the id-only guard and duplicated the fleet per replay.+ const derivedIds = ['curator', 'drafts', 'polish', 'watcher', 'shipper', 'auditor'];+ derivedIds.forEach((id, i) => {+ const r = manager.addCrew('ceo', { id, name: FULL_FLEET[i], description: id, persona: 'z'.repeat(40) });+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.duplicate).toBe(true);+ });+ const roster = manager.getStatusSummaries();+ expect(roster).toHaveLength(7);+ expect(execBotYamlCount(root)).toBe(7);+ });++ it('the name match is scoped to the lead — same name under another lead is allowed', () => {+ const store = manager['store'];+ store.create({ id: 'ceo', name: 'CEO', description: 'lead', manifest: { fleetRole: 'lead' } });+ store.create({ id: 'cto', name: 'CTO', description: 'lead 2', manifest: { fleetRole: 'lead' } });+ const r1 = manager.addCrew('ceo', { id: 'research', name: 'Research', description: '', persona: 'q'.repeat(40) });+ expect(r1.ok).toBe(true);+ // Same display name under a DIFFERENT lead is a legitimate new member.+ const r2 = manager.addCrew('cto', { id: 'research-2', name: 'Research', description: '', persona: 'q'.repeat(40) });+ expect(r2.ok).toBe(true);+ if (r2.ok) expect(r2.duplicate).toBeUndefined();+ expect(manager.getStatusSummaries()).toHaveLength(4);+ });++ it('an id belonging to another lead stays an error (never re-parents implicitly)', () => {+ buildFleet(manager);+ const store = manager['store'];+ store.create({ id: 'other-lead', name: 'Other Lead', manifest: { fleetRole: 'lead' } });+ const r = manager.addCrew('other-lead', { id: 'research', name: 'Different Name Anyway', description: '', persona: 'q'.repeat(40) });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.error).toMatch(/already exists/);+ });++ it('case differences in spec name do not defeat the dedupe', () => {+ buildFleet(manager); // crew names are the ids, e.g. "research"+ const r = manager.addCrew('ceo', { id: 'fresh-id', name: ' RESEARCH ', description: '', persona: 'q'.repeat(40) });+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.duplicate).toBe(true);+ expect(manager.getStatusSummaries()).toHaveLength(7);+ });+});++describe('reopen sequence (single runtime) — fleet stays intact', () => {+ let root: string;+ let manager1: BotManager;+ let manager2: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-reopen-dup-'));+ });++ afterEach(() => {+ for (const m of activeManagers.splice(0)) m.dispose();+ rmSync(root, { recursive: true, force: true });+ });++ it('session 1 builds 7; session 2 (migrations + 50 roster polls) keeps 7', async () => {+ manager1 = makeManager(root);+ buildFleet(manager1);+ expect(manager1.getStatusSummaries().length).toBe(7);+ manager1.dispose();++ manager2 = makeManager(root);+ await manager2.migrateFleetLayout();+ await manager2.migratePermissions();+ for (let i = 0; i < 50; i++) manager2.getStatusSummaries();++ const roster = manager2.getStatusSummaries().map(s => s.id).sort();+ expect(roster.length).toBe(7);+ expect(new Set(roster).size).toBe(7);+ expect(execBotYamlCount(root)).toBe(7);+ });++ it('a durable job from a crashed mid-crew-build session replays WITHOUT duplicating crew', async () => {+ manager1 = makeManager(root);+ buildFleet(manager1);+ // Simulate the interrupted turn that built the crew: its durable job was+ // claimed, never settled, and the process died (app closed mid-turn).+ const job = manager1.enqueue('ceo', { trigger: 'chat', prompt: 'hire your crew' });+ expect(job.accepted).toBe(true);+ manager1.dispose();++ const manager2 = makeManager(root);+ await manager2.migrateFleetLayout();+ const roster = manager2.getStatusSummaries();+ expect(roster.length).toBe(7);+ expect(new Set(roster.map(s => s.id)).size).toBe(7);+ manager2.dispose();+ });+});++describe('store.list() roster dedupe — a forked physical copy is shown once', () => {+ let root: string;+ let store: BotStore;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-list-dedupe-'));+ store = new BotStore(join(root, 'bots'));+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('a bot profile existing both at the root and nested under its lead renders once', () => {+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });+ store.create({ id: 'qa', name: 'QA', manifest: { fleetRole: 'crew', parent: 'ceo' } });+ // Simulate the historical fork: a stale FLAT copy left behind when a+ // relocation raced another runtime / failed on Windows-locked dirs.+ // (Same directory NAME in two places — only that shape double-counted.)+ const flatCopy = join(root, 'bots', 'qa');+ mkdirSync(flatCopy, { recursive: true });+ writeFileSync(join(flatCopy, 'bot.yaml'), 'id: qa\nname: QA\n', 'utf-8');++ const ids = store.list().map(m => m.id);+ expect(ids.filter(x => x === 'ceo')).toHaveLength(1);+ expect(ids.filter(x => x === 'qa')).toHaveLength(1);+ });+});++function execBotYamlCount(root: string): number {+ let count = 0;+ const visit = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'bot.yaml') count += 1;+ else if (entry.isDirectory()) visit(join(dir, entry.name));+ }+ };+ visit(join(root, 'bots'));+ return count;+}\ No newline at end of filediff --git a/src/bots/store.ts b/src/bots/store.tsindex 98150632..d4fe62ce 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -253,6 +253,13 @@ export class BotStore {list(): BotManifest[] {if (!existsSync(this.botsRoot)) return [];const manifests: BotManifest[] = [];+ // Bot identity is the manifest id, and it must stay 1:1 with the roster:+ // a profile dir that somehow exists in MORE than one place in the tree+ // (a forked/stale copy — historically possible when a relocate races a+ // concurrent runtime or a rename fails on Windows) must not let the same+ // bot appear twice. First occurrence wins; extra copies are flagged.+ const seenIds = new Set<string>();+ const reportedForks = new Set<string>();// 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@@ -269,7 +276,15 @@ export class BotStore {const sub = join(dir, entry.name);try {const m = this.get(entry.name);- if (m) manifests.push(m);+ if (m) {+ if (!seenIds.has(m.id)) {+ seenIds.add(m.id);+ manifests.push(m);+ } else if (!reportedForks.has(m.id)) {+ reportedForks.add(m.id);+ logger.warn({ botId: m.id, dir: sub }, 'Duplicate physical bot profile — roster keeps only the first occurrence; run `mercury` and remove the stale copy');+ }+ }} catch (err: any) {logger.warn({ dir: sub, err: err?.message }, 'Skipping unreadable bot profile');}diff --git a/src/bots/tools/bot-spawn.ts b/src/bots/tools/bot-spawn.tsindex e6c9be8b..d7331cdc 100644--- a/src/bots/tools/bot-spawn.ts+++ b/src/bots/tools/bot-spawn.ts@@ -44,6 +44,9 @@ function createSpawnTool(manager: BotManager, leadId: string, maxCrew: number) {if (!result.ok) {return `Error: ${result.error}`;}+ if (result.duplicate) {+ return `**${result.manifest.name}** (\`${result.manifest.id}\`) is already on your crew — no new bot created. Check your roster (fleet_status / bot list) before spawning replacements.`;+ }return `Crew member created: **${name}** (${result.manifest.id}) — fail-closed defaults, comms linked to you, persona ${refined ? 'refined through the persona builder' : 'saved as written'}. Dispatch tasks with bot_send (task: true); its results will arrive in your mailbox.`;},});diff --git a/src/channels/cli-bot-chat.test.ts b/src/channels/cli-bot-chat.test.tsindex ad44c8ca..65ed2f48 100644--- a/src/channels/cli-bot-chat.test.ts+++ b/src/channels/cli-bot-chat.test.ts@@ -121,4 +121,20 @@ describe('bot chat /persona + /skip routing', () => {it('/bots persona resolves bot names too (not just ids)', () => {expect(agentSrc).toMatch(/'open', 'send', 'journal', 'inbox', 'budget', 'edit', 'delete', 'enable', 'disable', 'stop', 'pause', 'start', 'run', 'persona'/);});+});++describe('bot chat /bots routing — control commands stay inside the thread', () => {+ it('/bots inside a bot chat parks the reply target instead of exiting', () => {+ // cli side: the /bots branch sets the pending target and passes the+ // command through; it must precede the generic exit-slash branch.+ const botsBranch = cliSrc.indexOf("trimmed.startsWith('/bots')");+ const exitBranch = cliSrc.indexOf("trimmed.startsWith('/')", botsBranch);+ expect(botsBranch).toBeGreaterThan(-1);+ expect(exitBranch).toBeGreaterThan(botsBranch);+ expect(cliSrc.slice(botsBranch, exitBranch)).toMatch(/pendingBotChatTarget = this\.activeBotId/);+ });++ it('the agent routes /bots replies into the bot thread the command was typed from', () => {+ expect(agentSrc).toMatch(/const pendingBot = \(channel as any\)\.consumePendingBotChatTarget\?\.\(\) \?\? null;[\s\S]*?const channelId = pendingBot \? `bot:\$\{pendingBot\}` : msg\.channelId;/);+ });});\ No newline at end of filediff --git a/src/channels/cli.ts b/src/channels/cli.tsindex c7cd3bea..5b1c767c 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -790,6 +790,19 @@ export class CLIChannel extends BaseChannel {: `/bots persona ${this.activeBotId}`);return;}+ // /bots control commands STAY inside the bot thread: the agent routes+ // their replies into this transcript via the pending bot-chat target+ // (same mechanism as /bot dispatch) — the roster, journal, inbox etc.+ // all render here. `/bots open <other-id>` naturally swaps threads.+ if (trimmed.startsWith('/bots')) {+ this.pendingBotChatTarget = this.activeBotId;+ try {+ onInput(trimmed);+ } finally {+ this.pendingBotChatTarget = null;+ }+ return;+ }// Any other slash command exits the bot chat first (review D2):// command replies route to the main transcript and would otherwise// be invisible from inside the bot thread.diff --git a/src/core/agent.ts b/src/core/agent.tsindex b2fec2e4..d1efece5 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1291,7 +1291,9 @@ export class Agent {for (const p of proposals) {const result = bm.addCrew(botId, p);if (result.ok) {- lines.push(`• **${p.name}** (\`${result.manifest.id}\`) — ${p.description || 'specialist'}`);+ lines.push(result.duplicate+ ? `• **${p.name}** (\`${result.manifest.id}\`) — already on the crew, skipped`+ : `• **${p.name}** (\`${result.manifest.id}\`) — ${p.description || 'specialist'}`);} else {lines.push(`⚠ ${p.name} (${p.id}): ${result.error}`);}@@ -1412,7 +1414,11 @@ export class Agent {*/private async handleBotsCommand(trimmed: string, msg: ChannelMessage, channel: any): Promise<void> {const bm = this.botManager;- const channelId = msg.channelId;+ // A /bots command typed from INSIDE a bot thread replies THERE (cli.ts+ // parks the thread id) — the roster/journal/inbox render in the bot's+ // transcript instead of bouncing the user back to the main chat.+ const pendingBot = (channel as any).consumePendingBotChatTarget?.() ?? null;+ const channelId = pendingBot ? `bot:${pendingBot}` : msg.channelId;if (!bm) {await channel.send('Bots are not available (BotManager not wired).', channelId);return;diff --git a/src/index.ts b/src/index.tsindex 603b1abf..0f374cba 100644--- a/src/index.ts+++ b/src/index.ts@@ -3680,6 +3680,15 @@ programreturn;}// A second terminal joins the running runtime instead of fighting it.+ // THE DAEMON COUNTS: booting a full foreground runtime next to it gave+ // two schedulers and two bot pollers on one queue.db — bots got called+ // twice and fleet-creation turns raced. Attach instead.+ const daemon = getDaemonStatus();+ if (daemon.running && daemon.pid) {+ console.log(chalk.cyan(` ⚿ Mercury is already running in the background (PID: ${daemon.pid}) — attaching.`));+ await runAttach();+ return;+ }const foreground = getForegroundRuntimeStatus();if (foreground.running && foreground.pid) {console.log(chalk.cyan(` ⚿ Mercury is already running (PID: ${foreground.pid}) — attaching.`));@@ -3710,6 +3719,13 @@ program}if (opts.foreground) {+ // Same single-runtime rule: a live daemon is already "Mercury running".+ const daemon = getDaemonStatus();+ if (daemon.running && daemon.pid) {+ console.log(chalk.cyan(` ⚿ Mercury is already running in the background (PID: ${daemon.pid}) — attaching.`));+ await runAttach();+ return;+ }const foreground = getForegroundRuntimeStatus();if (foreground.running && foreground.pid) {console.log(chalk.cyan(` ⚿ Mercury is already running (PID: ${foreground.pid}) — attaching.`));@@ -4862,6 +4878,14 @@ cloud// immediately. The background daemon (started by runCloudConnect) keeps// the WebSocket alive even after the user exits the foreground.if (isSetupComplete()) {+ // runCloudConnect (re)starts the daemon — join IT, never boot a second+ // runtime next to it (two schedulers would call bots in lockstep).+ const daemon = getDaemonStatus();+ if (daemon.running && daemon.pid) {+ console.log(chalk.cyan(`\n ⚿ Mercury is already running in the background (PID: ${daemon.pid}) — attaching.\n`));+ await runAttach();+ return;+ }console.log(chalk.cyan('\n Launching Mercury...\n'));await runAgent();} else {