Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(bots): close all five blocking findings from the adversarial merge review
Salman Qureshifed660ca38f3
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex b2dccd38..bd1c92cc 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -196,10 +196,9 @@ describe('Main-agent bots awareness (system prompt section)', () => {expect(section).toContain('/bots open <id>');});- it('empty fleet section still tells the agent how to onboard', () => {+ it('empty fleet produces NO prompt section (zero drift for botless users)', () => {const section = manager.getSystemPromptSection();- expect(section).toContain('no bots configured');- expect(section).toContain('/bots create');+ expect(section).toBe('');});it('dispatch_bot tool routes through the handler with name resolution', async () => {diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex badf2618..656b583f 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -65,6 +65,7 @@ type BotSchedulerLike = {addPersistedTask(m: { id: string; cron: string; description: string; prompt: string; botId?: string; createdAt: string }): void;persistSchedules(): void;getManifests(): Array<{ id: string; botId?: string }>;+ removeTask(id: string): void;};/**@@ -555,6 +556,37 @@ export class BotManager {this.registries.delete(botId);}+ /**+ * Full lifecycle delete: halt, purge durable queue state (jobs/mail/DLQ),+ * remove scheduler routines (zombie cron would fire forever), drop the+ * profile dir, and clear every in-memory cache — so a re-created bot with+ * the same id starts clean (no stale mail or resurrected routines).+ */+ async delete(botId: string): Promise<void> {+ await this.halt(botId);+ // Scheduler routines (bot:<id>:*) — both bot.yaml routines and+ // bot_schedule self-created ones; they must never fire again.+ if (this.scheduler) {+ for (const m of this.scheduler.getManifests()) {+ if (m.botId === botId) this.scheduler.removeTask(m.id);+ }+ this.scheduler.persistSchedules();+ }+ this.queue.purgeBot(botId);+ this.store.delete(botId);+ this.registries.delete(botId);+ this.journals.delete(botId);+ this.userMemories.delete(botId);+ this.queues.delete(botId);+ this.mailboxes.delete(botId);+ this.dailyTokens.delete(botId);+ this.activity.delete(botId);+ this.lastRun.delete(botId);+ this.needsYou.delete(botId);+ this.pausedForBudget.delete(botId);+ logger.info({ botId }, 'Bot deleted: queue/mail/DLQ purged, routines removed');+ }+/*** Register every enabled bot's cron routines with the main Scheduler* (manifest id `bot:<botId>:<name>`). Bot runs fire on the cron lane and@@ -690,7 +722,9 @@ export class BotManager {getSystemPromptSection(): string {const summaries = this.store.list();if (summaries.length === 0) {- return '\n\nMercury Bots: no bots configured. The user can create one with `/bots create <id> "Name" "Description"`.';+ // Empty fleet: no prompt section at all — zero-bots users must see+ // zero prompt/token drift (review A1).+ return '';}const lines: string[] = ['\n\nMercury Bots — the user maintains these persistent specialist agents (each has its own persona, model, memory, and permissions; they run OUTSIDE this conversation):',diff --git a/src/bots/queue.ts b/src/bots/queue.tsindex 266c207f..186d7136 100644--- a/src/bots/queue.ts+++ b/src/bots/queue.ts@@ -94,6 +94,8 @@ export interface BotQueueBackend {/** Durable bot-to-bot mailbox (§2.6: a handoff must survive a crash). */enqueueMail(mail: Omit<DurableMail, 'id'>): string;drainMail(botId: string): DurableMail[];+ /** Remove every trace of a bot: jobs, mail, DLQ rows (delete lifecycle). */+ purgeBot(botId: string): void;counts(): QueueCounts;}@@ -184,6 +186,10 @@ export class BotQueue {return this.backend.drainMail(botId);}+ purgeBot(botId: string): void {+ this.backend.purgeBot(botId);+ }+listDlq(botId?: string): DlqEntry[] {return this.backend.listDlq(botId);}@@ -359,6 +365,12 @@ export class SqliteQueueBackend implements BotQueueBackend {}));}+ purgeBot(botId: string): void {+ this.db.prepare(`DELETE FROM bot_jobs WHERE bot_id = ?`).run(botId);+ this.db.prepare(`DELETE FROM bot_mail WHERE bot_id = ?`).run(botId);+ this.db.prepare(`DELETE FROM bot_dlq WHERE bot_id = ?`).run(botId);+ }+listDlq(botId?: string): DlqEntry[] {const rows = botId? this.db.prepare(`SELECT * FROM bot_dlq WHERE bot_id = ? ORDER BY dead_at DESC`).all(botId) as any[]@@ -537,6 +549,14 @@ export class JsonFileQueueBackend implements BotQueueBackend {return drained;}+ purgeBot(botId: string): void {+ const before = this.data.jobs.length + this.data.dlq.length + this.data.mails.length;+ this.data.jobs = this.data.jobs.filter(j => j.botId !== botId);+ this.data.dlq = this.data.dlq.filter(j => j.botId !== botId);+ this.data.mails = this.data.mails.filter(m => m.botId !== botId);+ if (this.data.jobs.length + this.data.dlq.length + this.data.mails.length !== before) this.flush();+ }+listDlq(botId?: string): DlqEntry[] {return this.data.dlq.filter(j => !botId || j.botId === botId);}diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex c4eff44e..025c0ea4 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -647,7 +647,7 @@ export class CLIChannel extends BaseChannel {private appendBotMessage(botId: string, msg: ChatMessage): void {const existing = this.botTranscripts.get(botId) ?? [];- const updated = [...existing, msg];+ const updated = [...existing.slice(-CLIChannel.MAX_CHAT_MESSAGES + 1), msg];this.botTranscripts.set(botId, updated);if (this.activeBotId === botId) {this.trimAndSetMessages(updated, { isThinking: false, liveActivity: null });@@ -759,6 +759,12 @@ export class CLIChannel extends BaseChannel {}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.+ if (trimmed.startsWith('/')) {+ this.exitBotChat();+ }}if (trimmed === '/chat' || trimmed === '/c') {// Returning from Mercury Code must tear down its state (mouse mode,@@ -1106,7 +1112,12 @@ export class CLIChannel extends BaseChannel {// While a bot chat is open, main-agent traffic must not leak into the// bot's thread: non-bot sends land in the parked main transcript.if (this.activeBotId) {- this.mainTranscript = [...(this.mainTranscript ?? []), msg];+ // Parked main traffic is bounded by the same transcript cap as the+ // visible transcript (review I1 — daemon-in-bot-chat memory growth).+ this.mainTranscript = [+ ...(this.mainTranscript ?? []).slice(-CLIChannel.MAX_CHAT_MESSAGES + 1),+ msg,+ ];return;}this.trimAndSetMessages([...chat, msg], { isThinking: false, liveActivity: null });@@ -1453,6 +1464,18 @@ export class CLIChannel extends BaseChannel {}async stream(content: AsyncIterable<string>, _targetId?: string): Promise<string> {+ // While a bot chat is open, main-agent streaming must NEVER render into+ // the bot's transcript (review D1): consume silently and park the full+ // reply into the parked main transcript instead.+ if (this.activeBotId) {+ let parked = '';+ for await (const chunk of content) parked += chunk;+ this.mainTranscript = [+ ...(this.mainTranscript ?? []).slice(-CLIChannel.MAX_CHAT_MESSAGES + 1),+ { id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), role: 'agent', content: parked, timestamp: Date.now() },+ ];+ return parked;+ }const msgId = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);let full = '';let started = false;diff --git a/src/core/agent.ts b/src/core/agent.tsindex 88cc866e..a045ea67 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -656,7 +656,13 @@ export class Agent {// Telegram, web). Durable enqueue; the run's output is delivered back// to the requesting chat via the job's source (Telegram first).if (trimmed.startsWith('/bot ')) {- if (!this.botManager) return; // bots not wired — fall through as a normal message+ if (!this.botManager) {+ // Bots disabled: do NOT swallow the message — tell the user and stop.+ const channel = this.channels.getChannelForMessage(msg);+ void channel?.send('Bots are not enabled on this instance (set `bots.enabled: true` in mercury.yaml).', msg.channelId)+ .catch((err) => logger.warn({ err }, 'bots-disabled notice failed'));+ return;+ }const rest = trimmed.slice('/bot '.length).trim();const spaceIndex = rest.indexOf(' ');const rawTarget = (spaceIndex === -1 ? rest : rest.slice(0, spaceIndex)).toLowerCase();@@ -1104,7 +1110,7 @@ export class Agent {try {choice = await this.presentChoice(`Persona for **${manifest.name}** — how should it be saved?`,- ['Convert to template (recommended — structured, precise)', 'Save as-is'],+ ['Convert to template (recommended — structured, precise)', 'Save as-is', 'Cancel — that was a task, not a persona'],msg.channelId,channelType,);@@ -1112,6 +1118,15 @@ export class Agent {choice = 'template';}+ if (choice.startsWith('Cancel')) {+ // Escape hatch (review K1): the text was a real task — dispatch it,+ // touch nothing on disk, and drop the pending capture.+ this.pendingPersonaFor = null;+ this.pendingBudgetFor = null;+ await this.dispatchToBot(botId, raw, msg);+ return;+ }+let finalPersona = raw;if (choice.startsWith('Convert')) {const refined = await refinePersona(raw, manifest.name, this.providers.getDefault());@@ -1265,6 +1280,13 @@ export class Agent {if (resolved) parts[1] = resolved;}+ // Any explicit /bots command cancels pending onboarding capture — the+ // user has moved on; a later task in the bot chat must never be eaten+ // by the persona/budget state machine (review K1).+ if (this.pendingPersonaFor && action !== '') {+ this.pendingPersonaFor = null;+ }+const stateIcons: Record<string, string> = { idle: '⚪', queued: '🔵', running: '🟢', paused: '🟡', disabled: '⛔' };const runIcons: Record<string, string> = { completed: '✅', failed: '❌', halted: '⛔', paused: '⏸', denied: '🚫' };@@ -1310,7 +1332,7 @@ export class Agent {await channel.send('Usage: `/bots create <id> "Name" "Description" "persona (optional)"` — the bot starts with a fail-closed default profile you can refine via its profile files.', channelId);return;}- const rest = trimmed.slice(trimmed.indexOf(id) + id.length).trim();+ const rest = parts.slice(2).join(' ');const quoted = [...rest.matchAll(/"([^"]*)"/g)].map(m => m[1]);const name = quoted[0] ?? id.toUpperCase();const description = quoted[1];@@ -1342,7 +1364,7 @@ export class Agent {if (action === 'persona') {const target = parts[1]?.toLowerCase();- const personaText = trimmed.slice(trimmed.indexOf(target ?? '') + (target?.length ?? 0)).trim();+ const personaText = parts.slice(2).join(' ');if (!target || !personaText || !bm.store.exists(target)) {await channel.send('Usage: `/bots persona <id> <full persona text in one message>` — or open the bot chat (`/bots open <id>`) and type `/persona <text>`.', channelId);return;@@ -1353,7 +1375,7 @@ export class Agent {if (action === 'send') {const target = parts[1]?.toLowerCase();- const message = trimmed.slice(trimmed.indexOf(parts[1] ?? '') + (parts[1]?.length ?? 0)).trim();+ const message = parts.slice(2).join(' ');if (!target || !message) {await channel.send('Usage: `/bots send <id> <message>`', channelId);return;