From 02ad54ee9ac99f3211e7136987262d13665cf2b3 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:05:40 +0530 Subject: [PATCH 01/84] test(bots): expose held calls surviving work end and expiry --- tests/bots/botActions.test.ts | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 6cbd879bc0..b35a4d343b 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -976,3 +976,38 @@ it.each([true, false].flatMap(on => ['work', 'subagent'].map(caller => ({ on, ca } expect(t.calls).toEqual(on ? [] : [t.args]) }) + +// C3b inputs: open/approved/running, owner stop and engine end, wipes, +// forgotten card/request, changed permission/tool, expiry, repeat and owner intervention. +it.each(['open', 'approved'] as const)('withdraws %s calls atomically when work ends', async status => { + const t = await setup(true) + await t.call() + const a = f.bots.actions.forWork(t.workId)! + if (status === 'approved') f.bots.actions.transition(a.id, 'open', 'approved') + f.store.db.statement(`CREATE TRIGGER fail_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() + expect(() => f.store.moveActivation(t.workId, ['blocked'], 'cancelled')).toThrow('card failure') + expect(f.bots.actions.get(a.id)).toMatchObject({ status, exec_args: JSON.stringify(t.args) }) + expect(f.store.activation(t.workId)?.status).toBe('blocked') + f.store.db.statement('DROP TRIGGER fail_card').run() + await f.bots.stopWork(t.botId, t.workId) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe('Not sent') +}) + +it('expires on the due timer and carries its outcome until model output', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + expect(f.bots.nextDueAt(t.botId)).toBe(a.expires_at) + f.clock.now = Date.parse(a.expires_at) + f.timers.at(-1)!.fn() + await flush() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'expired', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe('Expired · not sent') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('expired') + expect(f.store.unreadWorkActions(t.workId)).toHaveLength(1) + const receiving = await start(f, t.workId, 2) + ;(receiving.prepared as any).modelOutput?.() + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) + expect(t.calls).toEqual([]) +}) From aacb963c8f76e6a0577c3bdfb1513288a0912edb Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:09:21 +0530 Subject: [PATCH 02/84] fix(bots): withdraw and expire held calls with their work --- src/mms/bots/actions/BotActions.ts | 78 ++++++++++++++++++++++++--- src/mms/bots/actions/lifecycle.ts | 10 ++++ src/mms/bots/activation/BotEngine.ts | 28 ++++++++-- src/mms/bots/memory/BotMemoryStore.ts | 2 + src/mms/bots/store/BotStore.ts | 2 + 5 files changed, 111 insertions(+), 9 deletions(-) create mode 100644 src/mms/bots/actions/lifecycle.ts diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index f09f454269..14aefa9c9d 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -1,3 +1,4 @@ +import { registerHeldCalls } from './lifecycle' import { randomUUID } from 'node:crypto' import type { MousseSettings } from '../../../shared/settings' import type { BotMcpTool } from '../../../shared/bots/personal/authority' @@ -157,6 +158,8 @@ export function actionContinuation(action: Pick): Promise } const pending = new Set(['open', 'approved', 'running']) @@ -178,7 +183,39 @@ export class BotActionChanged extends Error { readonly code = 'bot_action_change const changed = () => new BotActionChanged('This changed since you saw it. Redraw the action.') export class BotActions { private readonly executing = new Set() - constructor(private readonly host: Host) {} + constructor(private readonly host: Host) { + registerHeldCalls(host.store.db, { + endWork: id => this.withdrawWork(id), + forgetMessage: (botId, messageId) => { + if (!host.enabled()) return + const ids = host.store.all(`SELECT a.* FROM bot_actions a JOIN bot_activations w ON w.id = a.activation_id + WHERE a.bot_id = ? AND a.status IN ('open', 'approved') AND (a.message_id = ? OR json_extract(w.trigger_json, '$.replyTo') = ?)`, botId, messageId, messageId) + for (const action of ids) { + this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'The request was forgotten. Nothing was sent.' }) + const row = host.store.activation(String(action.activation_id)) + if (row && host.store.moveActivation(row.id, ['blocked'], 'cancelled', { endReason: 'forgotten', result: 'This work ended because its request was forgotten.' })) + host.post(row, `bm_${action.id}_forgotten`, 'This work ended because its request was forgotten.') + } + } + }) + } + withdrawWork(id: string): void { + if (!this.host.enabled()) return + for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND status IN ('open', 'approved')", id)) + this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'This work ended. Nothing was sent.' }) + } + expireDue(): void { + if (!this.host.enabled()) return + for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved') AND expires_at <= ?", this.host.store.now())) { + if (this.transition(String(a.id), String(a.status), 'expired', { text: 'This call expired. Carry on without it; do not try the same call again without a new reason.' })) this.finish(a as unknown as ActionRow) + } + } + withdrawChanged(): void { + if (!this.host.enabled()) return + for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved')")) { + if (!this.valid(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.finish(a as unknown as ActionRow) + } + } get(id: string): ActionRow | undefined { return this.host.store.get('SELECT * FROM bot_actions WHERE id = ?', id) as unknown as ActionRow | undefined } forWork(id: string): ActionRow | undefined { return this.host.store.get("SELECT * FROM bot_actions WHERE activation_id = ? ORDER BY rowid DESC LIMIT 1", id) as unknown as ActionRow | undefined @@ -195,6 +232,15 @@ export class BotActions { const callKey = JSON.stringify([row.id, dispatch, toolCallId]) const existing = this.host.store.get('SELECT id FROM bot_actions WHERE call_key = ?', callKey) if (existing) return { text: 'This call is held for your owner. End your turn now.' } + if (pending.has(this.forWork(row.id)?.status ?? '')) return { text: 'A call is already held for your owner. End your turn now.', isError: true } + const digest = actionDigest(args) + const refused = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND args_digest = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), digest)[0] + if (refused) { + const seq = Number(JSON.parse(String(refused.card_json ?? '{}')).ownerSeq ?? 0) + const note = this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND id > ? LIMIT 1', row.id, Number(JSON.parse(String(refused.card_json ?? '{}')).noteSeq ?? 0)) + if (this.host.store.ownerLastWroteSeq(row.botId) <= seq && !note) + return { text: 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.', isError: true } + } const binding = this.host.binding(row, tool) if (!binding) return { text: 'This tool changed. Carry on without it.', isError: true } if (containsCredential(args)) return { text: 'This contains something that looks like a secret. It is never sent through a tool this way. Send it without that value.', isError: true } @@ -213,6 +259,7 @@ export class BotActions { this.host.park(row) this.host.post(row, messageId, `${tool.serverName} · ${tool.tool}\n${review.hasHiddenValues ? 'Hidden values will be sent.\n' : ''}${JSON.stringify(review.args)}`) }) + this.host.held() return { text: 'This call is held for your owner. End your turn now.' } } /** The only status writer. Settlement clears executable arguments in the same statement. */ @@ -223,10 +270,15 @@ export class BotActions { ran_at = CASE WHEN ? IN ('running', 'done') THEN ? ELSE ran_at END WHERE id = ? AND status = ?`, to, pending.has(to) ? 1 : 0, result ? JSON.stringify(boundedActionResult(result)) : null, from, this.host.store.now(), to, this.host.store.now(), id, from) > 0 + if (moved && ['declined', 'expired'].includes(to)) { + const action = this.get(id)! + this.host.store.run(`UPDATE bot_actions SET card_json = json_set(COALESCE(card_json, '{}'), '$.ownerSeq', ?, '$.noteSeq', ?) WHERE id = ?`, + this.host.store.ownerLastWroteSeq(action.bot_id), Number(this.host.store.get('SELECT MAX(id) AS id FROM bot_work_notes WHERE activation_id = ?', action.activation_id)?.id ?? 0), id) + } if (moved && !pending.has(to)) { const action = this.get(id)! const row = this.host.store.activation(action.activation_id) - this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) + this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) if (row?.endReason === 'approval') this.host.store.moveActivation(row.id, ['blocked'], 'blocked', { endReason: 'approval_answered' }) } return moved @@ -240,8 +292,8 @@ export class BotActions { const args: unknown = JSON.parse(action.exec_args) if (containsCredential(args) || actionDigest(args) !== action.args_digest) return undefined const review = reviewArguments(args, this.host.schema(JSON.parse(action.target_json))) - if (canonicalJson(JSON.parse(action.args_json)) !== canonicalJson(review.args) - || Boolean(JSON.parse(action.card_json ?? '{}').hasHiddenValues) !== review.hasHiddenValues) return undefined + if (action.args_json !== '"[forgotten]"' && (canonicalJson(JSON.parse(action.args_json)) !== canonicalJson(review.args) + || Boolean(JSON.parse(action.card_json ?? '{}').hasHiddenValues) !== review.hasHiddenValues)) return undefined const binding = this.host.binding(row, JSON.parse(action.target_json)) return binding && canonicalJson(binding) === canonicalJson(JSON.parse(action.binding_json)) ? row : undefined } catch { return undefined } @@ -255,13 +307,24 @@ export class BotActions { if (!this.host.enabled()) throw new BotActionChanged('Asks first is not available while its switch is off.') await this.host.refresh() const action = this.get(input.actionId) + if (action && ['open', 'approved'].includes(action.status) && Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) { + this.expireDue() + throw new BotActionChanged('This call expired. Nothing was sent.') + } + if (action && input.answer === 'send' && this.host.store.registry(action.bot_id)?.pausedReason === 'owner') throw new BotActionChanged('Resume this bot before sending.') if (!action || action.status !== 'open' || action.args_digest !== input.digest || !this.valid(action)) throw changed() if (input.answer === 'not_now') { - if (!this.transition(action.id, 'open', 'declined', { text: 'Your owner chose not to send this: carry on without it and say what you skipped.' })) throw changed() + this.host.store.db.transaction(() => { + if (!this.transition(action.id, 'open', 'declined', { text: 'Your owner chose not to send this: carry on without it and say what you skipped.' })) throw changed() + this.host.ownerAnswered(this.host.store.activation(action.activation_id)!) + }) this.finish(action) return { status: 'declined' } } - if (!this.transition(action.id, 'open', 'approved')) throw changed() + this.host.store.db.transaction(() => { + if (!this.transition(action.id, 'open', 'approved')) throw changed() + this.host.ownerAnswered(this.host.store.activation(action.activation_id)!) + }) await this.runApproved(action.id) return { status: this.get(action.id)!.status } } @@ -295,8 +358,11 @@ export class BotActions { } async reconcile(): Promise { if (!this.host.enabled()) return + this.expireDue() const interrupted = this.host.store.all("SELECT id FROM bot_actions WHERE status IN ('running', 'approved')") await this.host.refresh() + this.withdrawChanged() + if (this.host.store.get("SELECT 1 FROM bot_actions WHERE status = 'open' LIMIT 1")) this.host.held() for (const a of interrupted) { const action = this.get(String(a.id)) if (!action || this.executing.has(action.id)) continue diff --git a/src/mms/bots/actions/lifecycle.ts b/src/mms/bots/actions/lifecycle.ts new file mode 100644 index 0000000000..807c61ae0e --- /dev/null +++ b/src/mms/bots/actions/lifecycle.ts @@ -0,0 +1,10 @@ +import type { BotStoreTx } from '../store/BotStore' + +/** Per open database, never persisted: a disabled feature installs no active behavior. */ +export interface HeldCallLifecycle { + endWork(id: string): void + forgetMessage(botId: string, messageId: string): void +} +const lifecycles = new WeakMap() +export function registerHeldCalls(db: BotStoreTx, lifecycle: HeldCallLifecycle): void { lifecycles.set(db, lifecycle) } +export function heldCalls(db: BotStoreTx): HeldCallLifecycle | undefined { return lifecycles.get(db) } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index c422754759..cbdba9a15e 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -599,6 +599,12 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { refresh: async () => { await this.host.mcp?.warm() }, park: (row) => { if (!this.park(row, 'approval')) throw new Error('work ended') }, enabled: () => botAsksFirst(this.host.settings?.get()), + ownerAnswered: row => { + this.resetWorkWaitChain(row.id) + const last = this.store.get('SELECT MAX(rowid) AS n FROM bot_reminders WHERE work_id = ?', row.id) + this.store.db.statement(`INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?) ON CONFLICT(bot_id, key) DO UPDATE SET value = excluded.value`).run(row.botId, `cursor:action-owner:${row.id}`, String(last?.n ?? 0)) + }, + held: () => { this.watchMcp(); this.armDue() }, schema: (tool) => this.host.mcp?.inputSchema?.(tool), binding: (row, tool) => { const grant = this.store.activeGrant(row.botId) @@ -2222,7 +2228,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { private readonly workWaitFacts: WorkWaitFacts = { approvalReady: (row) => this.store.lastMainDispatch(row.id)?.endedAt !== null && !this.live.has(row.id), - approvalExists: (row) => Boolean(this.actions.forWork(row.id)), + approvalExists: (row) => { const action = this.actions.forWork(row.id); return Boolean(action && (row.endReason === 'approval_answered' || ['open', 'approved', 'running'].includes(action.status))) }, timerExists: (row) => { const wait = this.store.workWait(row.id); return Boolean(wait && wait.status !== 'cancelled') }, usageResumable: (row) => this.usageResumable(row), questionExists: (row) => Boolean(this.store.workQuestion(row.id)), @@ -3108,6 +3114,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { fillMcpAsks(): void { const mcp = this.host.mcp if (!mcp || this.closed) return + this.actions.withdrawChanged() const waiting = this.store.escalations({ status: 'open' }).filter((row) => waitsForTools(row.permission)) if (!waiting.length) return let servers: BotMcpServer[] @@ -4653,6 +4660,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { this.store.db.transaction(() => { this.store.setPublished(botId, revision.revision!) this.store.approve(botId, digest, granted) + this.actions.withdrawChanged() if (switching) this.store.regrant(botId, grant.digest, digest, revision.revision!) for (const row of this.store.activationsIn(botId, ['queued', 'blocked'])) { if (row.status === 'blocked' && !workWaits(row)) continue @@ -7401,6 +7409,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { await this.endAll([...this.store.laneActivations(botId, 'chat', [...NOT_ENDED]), ...waiting], 'stopped', () => { this.store.withdrawAsks(botId) this.store.withdrawQuestions(botId) + if (botAsksFirst(this.host.settings?.get())) this.store.run("DELETE FROM bot_messages WHERE bot_id = ? AND id IN (SELECT message_id FROM bot_actions WHERE bot_id = ?)", botId, botId) }) // Deleted once the turns stopped, so a turn ending meanwhile adds no row to the cleared chat. this.store.deleteMessages(botId) @@ -7427,7 +7436,12 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } // The chat turn is stopped first, so it copies nothing more into the history once it is gone. await this.clearChat(botId) - const removed = memory.wipeHistory(botId) + const removed = this.store.db.transaction(() => { + const removed = memory.wipeHistory(botId) + if (botAsksFirst(this.host.settings?.get())) this.store.run(`UPDATE bot_actions SET args_json = ?, card_json = ?, bot_note = ?, result_json = ? WHERE bot_id = ?`, + '"[forgotten]"', '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId) + return removed + }) this.changed({ botId }) return removed } @@ -8132,7 +8146,9 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { */ private refuseWakeLoop(botId: string, brief: string, event: BotWakeEvent | null, workId?: string): void { const key = wakeLoopKey(brief, event) - const same = this.store.wakesSetSince(botId, this.store.ownerLastWroteAt(botId), workId).filter((wake) => wakeLoopKey(wake.text, wake.event) === key).length + const after = workId && botAsksFirst(this.host.settings?.get()) ? Number(this.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', botId, `cursor:action-owner:${workId}`)?.value ?? 0) : 0 + const same = after ? this.store.all('SELECT text, event_json FROM bot_reminders WHERE bot_id = ? AND work_id = ? AND rowid > ? AND created_at >= ?', botId, workId!, after, this.store.ownerLastWroteAt(botId)).filter(wake => wakeLoopKey(String(wake.text), wake.event_json ? JSON.parse(String(wake.event_json)) : null) === key).length + : this.store.wakesSetSince(botId, this.store.ownerLastWroteAt(botId), workId).filter((wake) => wakeLoopKey(wake.text, wake.event) === key).length if (same >= MAX_SAME_WAKES) throw new BotEngineError('wake_loop', `You have set this same wake-up ${same} times since your owner last wrote, with nothing new in it: that is a loop. Don't set it again: tell your owner where things stand and what you are waiting on, and carry on when they write. If something did change, say what in the brief.`) } @@ -8565,6 +8581,11 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { */ private dueAt(botId?: string, forTimer = false): number | undefined { const sources: Array<() => number | undefined> = [ + () => { + if (!botAsksFirst(this.host.settings?.get())) return undefined + const row = this.store.get("SELECT MIN(expires_at) AS at FROM bot_actions WHERE status IN ('open', 'approved') AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null) + return row?.at ? Date.parse(String(row.at)) : undefined + }, () => this.tellings.next(botId), () => { const row = this.store.nextReminder(botId) @@ -8629,6 +8650,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { // Never synchronous: the pass is held below before any of it runs, so its end always lets go of it. await Promise.resolve() try { + this.actions.expireDue() // Reminders cancelled, forgotten or purged since they failed are no longer tried. for (const id of this.reminderRetryAt.keys()) if (this.store.reminder(id)?.status !== 'waiting') this.reminderRetryAt.delete(id) for (const reminder of this.store.dueReminders(now.toISOString())) { diff --git a/src/mms/bots/memory/BotMemoryStore.ts b/src/mms/bots/memory/BotMemoryStore.ts index 926828bf90..e8279ce50f 100644 --- a/src/mms/bots/memory/BotMemoryStore.ts +++ b/src/mms/bots/memory/BotMemoryStore.ts @@ -1,3 +1,4 @@ +import { heldCalls } from '../actions/lifecycle' import { requestJournalRows } from './requestFrames' import { createHash } from 'node:crypto' import type { ProfileDatabase } from '../../run/db/ProfileDatabase' @@ -1345,6 +1346,7 @@ function redactQuestionCopies(tx: BotStoreTx, has: (table: string) => boolean, b } function defaultRedactMessage(tx: BotStoreTx, botId: string, messageId: string, text: string): void { + heldCalls(tx)?.forgetMessage(botId, messageId) const has = (table: string) => Boolean(tx.statement("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)) if (!has('bot_messages')) return tx.statement('UPDATE bot_messages SET text = ? WHERE id = ? AND bot_id = ?').run(text, messageId, botId) diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index 4c551088d0..8e760b8df1 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1,3 +1,4 @@ +import { heldCalls } from '../actions/lifecycle' import type { ActionRow } from '../actions/BotActions' import { readdirSync, rmSync } from 'node:fs' import { join } from 'node:path' @@ -1300,6 +1301,7 @@ export class BotStore { if (moved && to !== 'done') this.withdrawUnpostedQuestions(id) if (moved) { this.withdrawWorkQuestions(id) + heldCalls(this.db)?.endWork(id) this.run("UPDATE bot_reminders SET status = 'cancelled', delivered_at = ? WHERE work_id = ? AND status = 'waiting'", this.now(), id) } return moved From 5f096ac2f1bb3e4ed0687a871dd428631cfe0f24 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:15:30 +0530 Subject: [PATCH 03/84] fix(bots): owner answers reset waits and repeat cards need new input --- src/mms/bots/actions/BotActions.ts | 9 +- src/mms/bots/activation/BotEngine.ts | 5 +- tests/bots/botActions.test.ts | 200 ++++++++++++++++++++++- tests/bots/botContinuationMatrix.test.ts | 4 +- 4 files changed, 208 insertions(+), 10 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 14aefa9c9d..8b730dd03a 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -174,6 +174,7 @@ interface Host { binding(row: BotActivationRow, tool: BotMcpTool): unknown | undefined post(row: BotActivationRow, id: string, text: string): void settled(row: BotActivationRow): void + publish(messageId: string): void ownerAnswered(row: BotActivationRow): void held(): void execute(row: BotActivationRow, tool: BotMcpTool, args: Record): Promise @@ -213,7 +214,7 @@ export class BotActions { withdrawChanged(): void { if (!this.host.enabled()) return for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved')")) { - if (!this.valid(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.finish(a as unknown as ActionRow) + if (!this.valid(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.host.store.db.afterCommit(() => this.finish(a as unknown as ActionRow)) } } get(id: string): ActionRow | undefined { return this.host.store.get('SELECT * FROM bot_actions WHERE id = ?', id) as unknown as ActionRow | undefined } @@ -237,10 +238,11 @@ export class BotActions { const refused = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND args_digest = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), digest)[0] if (refused) { const seq = Number(JSON.parse(String(refused.card_json ?? '{}')).ownerSeq ?? 0) - const note = this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND id > ? LIMIT 1', row.id, Number(JSON.parse(String(refused.card_json ?? '{}')).noteSeq ?? 0)) + const note = Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', row.botId, `cursor:action-note:${row.id}`)?.value ?? 0) > Number(JSON.parse(String(refused.card_json ?? '{}')).noteSeq ?? 0) if (this.host.store.ownerLastWroteSeq(row.botId) <= seq && !note) return { text: 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.', isError: true } } + if (pending.has(this.forWork(row.id)?.status ?? '')) return { text: 'A call already waits for your owner. End your turn now.', isError: true } const binding = this.host.binding(row, tool) if (!binding) return { text: 'This tool changed. Carry on without it.', isError: true } if (containsCredential(args)) return { text: 'This contains something that looks like a secret. It is never sent through a tool this way. Send it without that value.', isError: true } @@ -273,13 +275,14 @@ export class BotActions { if (moved && ['declined', 'expired'].includes(to)) { const action = this.get(id)! this.host.store.run(`UPDATE bot_actions SET card_json = json_set(COALESCE(card_json, '{}'), '$.ownerSeq', ?, '$.noteSeq', ?) WHERE id = ?`, - this.host.store.ownerLastWroteSeq(action.bot_id), Number(this.host.store.get('SELECT MAX(id) AS id FROM bot_work_notes WHERE activation_id = ?', action.activation_id)?.id ?? 0), id) + this.host.store.ownerLastWroteSeq(action.bot_id), Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', action.bot_id, `cursor:action-note:${action.activation_id}`)?.value ?? 0), id) } if (moved && !pending.has(to)) { const action = this.get(id)! const row = this.host.store.activation(action.activation_id) this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) if (row?.endReason === 'approval') this.host.store.moveActivation(row.id, ['blocked'], 'blocked', { endReason: 'approval_answered' }) + this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) } return moved }) diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index cbdba9a15e..cc955e57f3 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -599,6 +599,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { refresh: async () => { await this.host.mcp?.warm() }, park: (row) => { if (!this.park(row, 'approval')) throw new Error('work ended') }, enabled: () => botAsksFirst(this.host.settings?.get()), + publish: id => { this.chat.republish(id) }, ownerAnswered: row => { this.resetWorkWaitChain(row.id) const last = this.store.get('SELECT MAX(rowid) AS n FROM bot_reminders WHERE work_id = ?', row.id) @@ -2228,7 +2229,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { private readonly workWaitFacts: WorkWaitFacts = { approvalReady: (row) => this.store.lastMainDispatch(row.id)?.endedAt !== null && !this.live.has(row.id), - approvalExists: (row) => { const action = this.actions.forWork(row.id); return Boolean(action && (row.endReason === 'approval_answered' || ['open', 'approved', 'running'].includes(action.status))) }, + approvalExists: (row) => { const action = this.actions.forWork(row.id); return Boolean(action && (!botAsksFirst(this.host.settings?.get()) || row.endReason === 'approval_answered' || ['open', 'approved', 'running'].includes(action.status))) }, timerExists: (row) => { const wait = this.store.workWait(row.id); return Boolean(wait && wait.status !== 'cancelled') }, usageResumable: (row) => this.usageResumable(row), questionExists: (row) => Boolean(this.store.workQuestion(row.id)), @@ -7960,6 +7961,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { // The note keeps the owner's message it came from (the chat turn's), so a forget of that message reaches it. if (from && this.store.activation(from) && ownerChatTurn(this.store.activation(from)!)) this.resetWorkWaitChain(workId) this.store.addWorkNote(workId, botId, text, from ? this.ownerMessageOf(from) : undefined) + if (botAsksFirst(this.host.settings?.get()) && (!from || (this.store.activation(from) && ownerChatTurn(this.store.activation(from)!)))) + this.store.run(`INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, '1') ON CONFLICT(bot_id, key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`, botId, `cursor:action-note:${workId}`) return 'noted' as const }) } diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index b35a4d343b..7a808031af 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -193,7 +193,7 @@ it.each(['approved', 'running'] as const)('restart clears arguments from an expi const a = f.bots.actions.forWork(t.workId)! f.bots.actions.transition(a.id, 'open', 'approved') if (state === 'running') f.bots.actions.transition(a.id, 'approved', 'running') - f.clock.now += 49 * 3600_000 + f.clock.now += 48 * 3600_000 + 1000 await f.bots.actions.reconcile() expect(t.calls).toEqual([]) expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'expired' : 'uncertain', exec_args: null }) @@ -202,8 +202,8 @@ it('an expired Send is refused', async () => { const t = await setup(true) await t.call() const a = f.bots.actions.forWork(t.workId)! - f.clock.now += 49 * 3600_000 - await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('changed since') + f.clock.now += 48 * 3600_000 + 1000 + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() expect(t.calls).toEqual([]) }) it('the app answer method reaches the held call and returns redraw for a repeated Send', async () => { @@ -985,7 +985,7 @@ it.each(['open', 'approved'] as const)('withdraws %s calls atomically when work const a = f.bots.actions.forWork(t.workId)! if (status === 'approved') f.bots.actions.transition(a.id, 'open', 'approved') f.store.db.statement(`CREATE TRIGGER fail_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() - expect(() => f.store.moveActivation(t.workId, ['blocked'], 'cancelled')).toThrow('card failure') + expect(() => f.store.moveActivation(t.workId, ['blocked'], 'cancelled')).toThrow() expect(f.bots.actions.get(a.id)).toMatchObject({ status, exec_args: JSON.stringify(t.args) }) expect(f.store.activation(t.workId)?.status).toBe('blocked') f.store.db.statement('DROP TRIGGER fail_card').run() @@ -1011,3 +1011,195 @@ it('expires on the due timer and carries its outcome until model output', async expect(f.store.unreadWorkActions(t.workId)).toEqual([]) expect(t.calls).toEqual([]) }) + +it.each(['declined', 'expired'] as const)('refuses an identical %s call without a new row; owner notes and changed arguments allow a card', async outcome => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (outcome === 'declined') await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + else { f.clock.now = Date.parse(a.expires_at); await f.bots.deliverDueReminders() } + await flush() + const next = await start(f, t.workId, 2) + const call = (args = t.args, id = 'repeat') => callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args, toolCallId: id, signal: new AbortController().signal }) + expect(await call()).toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(f.bots.noteWork(t.botId, t.workId, 'Please try it again')).toBe('noted') + expect(await call(t.args, 'after-note')).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) +}) + +it('allows a different argument after Not now, with only one outstanding card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush() + const next = await start(f, t.workId, 2) + const call = (body: string) => callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body }, toolCallId: body, signal: new AbortController().signal }) + expect(await call('new reason')).not.toMatchObject({ isError: true }) + expect(await call('another reason')).toMatchObject({ isError: true }) + expect(f.store.all("SELECT id FROM bot_actions WHERE status = 'open'")).toHaveLength(1) +}) + +it.each(['clear', 'reset', 'delete', 'forget history', 'permission', 'tool'] as const)('withdraws pending arguments on %s and preserves a running row', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + // A second work's running call is independent and must retain its run-once record. + f.store.run(`INSERT INTO bot_actions SELECT id || '_running', call_key || '_running', bot_id, activation_id, lane, kind, target_json, exec_args, args_json, args_digest, binding_json, place_json, card_json, bot_note, 'running', result_json, message_id, next_at, nudges, expires_at, answered_at, answered_device, created_at, ran_at FROM bot_actions WHERE id = ?`, a.id) + if (path === 'clear') await f.bots.clearChat(t.botId) + if (path === 'reset') await f.bots.resetBot(t.botId) + if (path === 'delete') await f.bots.remove(t.botId) + if (path === 'forget history') await f.bots.wipeMemory(t.botId, 'saved') + if (path === 'permission') f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + if (path === 'tool') { t.server.tools.splice(0); f.bots.fillMcpAsks() } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.bots.actions.get(`${a.id}_running`)).toMatchObject({ status: 'running', exec_args: JSON.stringify(t.args) }) + await f.bots.actions.reconcile() + expect(f.bots.actions.get(`${a.id}_running`)).toMatchObject({ status: 'uncertain', exec_args: null }) +}) + +it('keeps the card during an owner pause and refuses Send in plain words', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.bots.pauseBot(t.botId) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('Resume this bot') + expect(f.bots.actions.get(a.id)?.status).toBe('open') + expect(t.calls).toEqual([]) +}) + +it.each(['card', 'request'] as const)('Forget of the %s withdraws exact arguments in the redaction transaction', async which => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const request = f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0]! + const id = which === 'card' ? a.message_id : String(request.id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: which === 'card' ? 'notice' : 'owner_msg', who: which === 'card' ? 'bot' : 'owner', text: f.store.message(id)!.text })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + f.bots.afterForget() + await flush() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.store.activation(t.workId)?.status).toBe('cancelled') +}) + +it('forget history removes settled text and preserves the call key that prevents another execution', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await f.bots.wipeMemory(t.botId, 'saved') + const saved = f.bots.actions.get(a.id)! + expect(saved).toMatchObject({ call_key: a.call_key, status: 'declined', args_json: '"[forgotten]"', card_json: '"[forgotten]"', result_json: '{"text":"[forgotten]"}' }) + const result = f.bots.actions.hold(f.store.activation(t.workId)!, JSON.parse(a.call_key)[1], { server: 'mail', tool: 'send' } as never, t.args, 'runtime-call-1') + expect(result).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(t.calls).toEqual([]) +}) + +it.each(['restart', 'sleep', 'late Send'] as const)('expires at the written deadline after %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.clock.now = Date.parse(a.expires_at) + 1000 + if (path === 'restart') { f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() } + else if (path === 'sleep') await f.bots.deliverDueReminders() + else await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('expired') + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'expired', exec_args: null }) + expect(t.calls).toEqual([]) +}) + +it('an owner chat message lifts the identical-call refusal using its sequence', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush() + const next = await start(f, t.workId, 2) + await f.bots.service.chatSend({ botId: t.botId, text: 'Please try again', clientRequestId: 'retry-owner' }) + expect(await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'after-owner', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) +}) + +it('settled approval stranded before its readiness write ends with a line', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.store.run("UPDATE bot_actions SET status = 'withdrawn', exec_args = NULL WHERE id = ?", a.id) + f.bots.afterForget() + expect(f.store.activation(t.workId)).toMatchObject({ status: 'failed', endReason: 'action_gone' }) + expect(f.store.message(`bm_${t.workId}_ended`)?.text).toContain('nothing could let it carry on') +}) + +it.each(['stop', 'expiry', 'forget'] as const)('the disabled switch leaves held rows unchanged on %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.host.settings!.get().experimental.botAsksFirst = false + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (path === 'expiry') { f.clock.now = Date.parse(a.expires_at); await f.bots.deliverDueReminders() } + if (path === 'forget') { + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, kind: 'notice', sourceKey: `bm:${a.message_id}`, who: 'bot', text: 'Held call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'open', exec_args: JSON.stringify(t.args) }) +}) + +it.each(['send', 'not_now'] as const)('owner %s resets detection of repeated waits, as a question answer does', async answer => { + const t = await setup(true) + for (let round = 0; round < 4; round++) { + const current = f.store.activation(t.workId)! + const n = f.store.lastMainDispatch(t.workId)!.n + const runtime = round === 0 ? t.work : await start(f, t.workId, n) + await f.bots.tools.wakes!.wait!(t.botId, t.workId, { brief: 'Wait for mail evidence', dueAt: new Date(f.clock.now + 300_000).toISOString() }) + await finish(f, runtime.payload) + f.clock.now += 300_000 + await f.bots.deliverDueReminders(); await flush() + const next = await start(f, t.workId, n + 1) + await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: `mail ${round}` }, toolCallId: `mail-${round}`, signal: new AbortController().signal }) + await finish(f, next.payload) + const a = f.bots.actions.forWork(current.id)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer }) + await flush() + } +}) + +it('a tool withdrawal is delivered through unread updates and confirmed on completion', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + t.server.tools.splice(0) + f.bots.fillMcpAsks(); await flush() + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('This call was withdrawn') + expect(f.store.unreadWorkActions(t.workId).map(a => a.id)).toEqual([a.id]) + const next = await start(f, t.workId, 2) + await finish(f, next.payload) + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) +}) + +it.each(['clear', 'reset', 'delete', 'permission', 'forget'] as const)('%s rolls back withdrawal and its owning change together on a failed write', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const before = f.store.activation(t.workId)! + const grant = f.store.activeGrant(t.botId) + f.store.db.statement(`CREATE TRIGGER fail_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() + let change: () => unknown + if (path === 'clear') change = () => f.bots.clearChat(t.botId) + else if (path === 'reset') change = () => f.bots.resetBot(t.botId) + else if (path === 'delete') change = () => f.bots.remove(t.botId) + else if (path === 'permission') change = () => f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + else { + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, kind: 'notice', sourceKey: `bm:${a.message_id}`, who: 'bot', text: 'Held call' })! + change = () => memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + await expect(Promise.resolve().then(change)).rejects.toThrow() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'open', exec_args: JSON.stringify(t.args) }) + expect(f.store.activation(t.workId)).toEqual(before) + expect(f.store.activeGrant(t.botId)).toEqual(grant) + expect(f.store.registry(t.botId)?.deletedAt).toBeNull() + expect(f.store.message(a.message_id)?.text).not.toBe('Not sent') +}) diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 7e34c779b0..0738a86d92 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -57,8 +57,8 @@ const actionLines = [ ['failed', 'Nothing was sent. The call failed:'], ['tool_error', 'The tool reported an error. It may have done part of it: check before trying again. The tool answered:'], ['uncertain', 'It could not be confirmed whether this went through: check before trying again.'], - ['withdrawn', 'Nothing was sent. The call failed:'], - ['expired', 'Nothing was sent. The call failed:'] + ['withdrawn', 'This call was withdrawn. Nothing was sent.'], + ['expired', 'This call expired. Nothing was sent; do not try the same call again without a new reason.'] ] as const const actionCells = actionLines.flatMap(([status, line]) => [false, true].flatMap(hasWaited => [false, true].flatMap(cause => (['turn cap', 'permission allowed since refused'] as const).flatMap(reason => UPDATES.map(update => ({ status, line, hasWaited, cause, reason, update })))))) From 61ec56ecb3be7290a5007801d1fcbd20440efc3b Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:15:30 +0530 Subject: [PATCH 04/84] docs(bots): explain held call withdrawal expiry and repeat refusal --- docs/bots.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/bots.md b/docs/bots.md index e6fc088c9d..a4cca43f43 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -769,7 +769,7 @@ NULL `owner_set` means set before v10 (or by an older writer) and preserves toda ### Asks first -The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, granted tools run as before. Tool selection, the approval card, scheduled runs that wait, withdrawal and timed expiry are separate work before this can be switched on. +The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, granted tools run as before. Tool selection, the approval card and scheduled runs that wait are separate work before this can be switched on. A held call belongs to one piece of work and one runtime call in its dispatch. Mousse keeps its exact arguments in the action row until it settles; the chat, journal and export get a masked copy. Only unmistakable credential shapes are refused before a card is written: provider-prefixed keys, PEM private-key blocks, a password in a URL's userinfo, or a secret-named URL query value. Document IDs, base64 attachments, JWT-shaped page tokens and prose mentioning passwords remain reviewable. Values are not decoded or normalized to find more possible secrets: split or hex keys, upper-case `SK-` and a zero-width character inside `sk-` remain visible for the owner to judge. @@ -781,6 +781,14 @@ Mousse makes the stored call once, without asking the model to recreate it. It c Settled actions join the same ordered, timed updates as waits, notes and answers. An action that caused the resume leads with its outcome. Its id is kept on the dispatch. Work's stored updates (waits, action outcomes, notes and answers, including work without wait history) count as told only when a dispatch carrying them produces model output or completes. Nonempty model text or thinking, or a model tool-call start, confirms delivery; merely preparing or starting a request does not. A failed, interrupted or replaced dispatch without that evidence leaves its updates pending, including after a time-limit card. A repeated update is acceptable; losing one is not. Carried/read (`read_at` and `applied_at`, plus the dispatch's `workDelivery`) keeps its existing meaning for late taps, Forget and compaction. Confirmation is a separate fact used only to decide what the next prompt carries: `unreadWorkAnswers`, `unreadWorkQuestion` and `unreadWorkNotes` include carried-but-unconfirmed updates without clearing those read markers. New carrying dispatches start with `prompt.workTold = pending`; `BotStore.confirmWorkDelivery` changes only that marker to `output` or `completed`. Reads happen before any confirmation write transaction, so a dispatch with no updates never opens one. A failed confirmation is caught and logged once per dispatch; it never fails the runtime's turn, and the next continuation can carry the update again. Completion of a new dispatch is confirmed explicitly; older rows with no marker also accept a completed stored outcome. Startup recovers a completion written before settlement. A usage retry carries the previous prompt's update ids, so it confirms only what that prompt contained. A database written by master as of #1339 has `workDelivery` for work that waited but no confirmation marker. If its carrying dispatch ended at a wall, a deadline or a turn cap, its notes and answers can be told once more after upgrading (twice is acceptable; losing them is not). Their carried/read behavior is preserved. Earlier databases with no such delivery ids gain no retrospective replay. Approval parks before a time or event wait and has no idle or week exemption. +A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it when the catalogue changes. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting its card or request ends the parked work with a line. A work row stranded on a settled call without its continuation marker ends too. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. + +`/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, card metadata, bot note and stored result with fixed forgotten markers. Its call key, target, status and timestamps stay. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. + +An owner pause keeps a held card: a pause is not a refusal. Send says "Resume this bot before sending." while paused. A card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline again. + +After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row. A changed argument is a new review, as a changed wake brief is new progress under the wake loop rule: there is no fixed lifetime count of cards. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. + Hidden argument values of four to eight characters require an adjacent character outside `[A-Za-z0-9_]` only at an edge whose own character is an ASCII letter, digit or underscore. Other edges require no boundary; longer values are replaced wherever they occur. Values shorter than four characters are left alone. Replacement runs in the server's own text before Mousse frames it, including JSON-escaped string echoes and numeric echoes. Credential masking still applies to the result. Transformed echoes (for example encoded, upper-case or truncated values) are not caught by this exact-value replacement. The stored result is capped at 64 KiB in total; images are omitted with a note, never cut into invalid data. Journal key-name masking applies only to work with a held action; other work keeps master's tool input capture. Send is honoured from any device that may reach the bot, whatever that device's own permission limit, as an Allow of a permission is today (subject to the complete-card size check above). Executable arguments are cleared from the action row with every settled state. The model's own tool call, including its exact arguments, remains in the work's runtime transcript and the provider's session file. Mousse does not rewrite those transcripts; clearing the stored action arguments does not remove those copies. This covers Mousse's MCP calls, not commands, browser actions or actions on the owner's threads. From a91acfb44d99c0c3617a20a18dd44674892b3d32 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:20:33 +0530 Subject: [PATCH 05/84] test(bots): cover every withdrawal rollback and durable repeat refusals --- tests/bots/botActions.test.ts | 67 ++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 4 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 7a808031af..a4f6ff3f89 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1041,12 +1041,22 @@ it('allows a different argument after Not now, with only one outstanding card', expect(f.store.all("SELECT id FROM bot_actions WHERE status = 'open'")).toHaveLength(1) }) -it.each(['clear', 'reset', 'delete', 'forget history', 'permission', 'tool'] as const)('withdraws pending arguments on %s and preserves a running row', async path => { +it.each(['stop', 'failed', 'limits', 'week', 'clear', 'reset', 'delete', 'forget history', 'permission', 'allowed', 'tool', 'server', 'card', 'request'] as const)('withdraws pending arguments on %s and preserves a running row', async path => { const t = await setup(true) await t.call(); await finish(f, t.work.payload) const a = f.bots.actions.forWork(t.workId)! // A second work's running call is independent and must retain its run-once record. f.store.run(`INSERT INTO bot_actions SELECT id || '_running', call_key || '_running', bot_id, activation_id, lane, kind, target_json, exec_args, args_json, args_digest, binding_json, place_json, card_json, bot_note, 'running', result_json, message_id, next_at, nudges, expires_at, answered_at, answered_device, created_at, ran_at FROM bot_actions WHERE id = ?`, a.id) + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (['failed', 'limits', 'week'].includes(path)) f.store.moveActivation(t.workId, ['blocked'], 'failed', { endReason: path }) + if (path === 'allowed') f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: m.mcp.map(p => ({ ...p, level: 'allowed' as const })) })) + if (path === 'server') { vi.spyOn(t.mcp, 'binding').mockReturnValue(undefined); f.bots.fillMcpAsks() } + if (path === 'card' || path === 'request') { + const id = path === 'card' ? a.message_id : String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'request' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } if (path === 'clear') await f.bots.clearChat(t.botId) if (path === 'reset') await f.bots.resetBot(t.botId) if (path === 'delete') await f.bots.remove(t.botId) @@ -1179,7 +1189,7 @@ it('a tool withdrawal is delivered through unread updates and confirmed on compl expect(f.store.unreadWorkActions(t.workId)).toEqual([]) }) -it.each(['clear', 'reset', 'delete', 'permission', 'forget'] as const)('%s rolls back withdrawal and its owning change together on a failed write', async path => { +it.each(['stop', 'failed', 'limits', 'week', 'clear', 'reset', 'delete', 'forget history', 'permission', 'allowed', 'tool', 'server', 'card', 'request'] as const)('%s rolls back withdrawal and its owning change together on a failed write', async path => { const t = await setup(true) await t.call(); await finish(f, t.work.payload) const a = f.bots.actions.forWork(t.workId)! @@ -1187,13 +1197,23 @@ it.each(['clear', 'reset', 'delete', 'permission', 'forget'] as const)('%s rolls const grant = f.store.activeGrant(t.botId) f.store.db.statement(`CREATE TRIGGER fail_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() let change: () => unknown - if (path === 'clear') change = () => f.bots.clearChat(t.botId) + if (path === 'stop') change = () => f.bots.stopWork(t.botId, t.workId) + else if (['failed', 'limits', 'week'].includes(path)) change = () => f.store.moveActivation(t.workId, ['blocked'], 'failed', { endReason: path }) + else if (path === 'forget history') change = () => f.bots.wipeMemory(t.botId, 'saved') + else if (path === 'allowed') change = () => f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: m.mcp.map(p => ({ ...p, level: 'allowed' as const })) })) + else if (path === 'tool' || path === 'server') change = () => { + if (path === 'tool') t.server.tools.splice(0) + else vi.spyOn(t.mcp, 'binding').mockReturnValue(undefined) + f.bots.fillMcpAsks() + } + else if (path === 'clear') change = () => f.bots.clearChat(t.botId) else if (path === 'reset') change = () => f.bots.resetBot(t.botId) else if (path === 'delete') change = () => f.bots.remove(t.botId) else if (path === 'permission') change = () => f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) else { const memory = new BotMemoryStore({ db: f.store.db }) - const seq = memory.append({ botId: t.botId, kind: 'notice', sourceKey: `bm:${a.message_id}`, who: 'bot', text: 'Held call' })! + const id = path === 'request' ? String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) : a.message_id + const seq = memory.append({ botId: t.botId, kind: 'notice', sourceKey: `bm:${id}`, who: 'bot', text: 'Held call' })! change = () => memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) } await expect(Promise.resolve().then(change)).rejects.toThrow() @@ -1203,3 +1223,42 @@ it.each(['clear', 'reset', 'delete', 'permission', 'forget'] as const)('%s rolls expect(f.store.registry(t.botId)?.deletedAt).toBeNull() expect(f.store.message(a.message_id)?.text).not.toBe('Not sent') }) + + +it('a repeat refusal joins unread work updates without another action or card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + const next = await start(f, t.workId, 2) + ;(next.prepared as any).modelOutput?.() + await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'repeat-refused', signal: new AbortController().signal }) + expect(f.store.unreadWorkNotes(t.workId).map(n => n.text).join(' ')).toContain('Do not ask again') + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + await finish(f, next.payload, 'failed', { outcome: { error: 'network_error' } }) + await (f.bots as any).continueWith(t.workId, [f.store.activation(t.workId)!.status], { network: true }) + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('Do not ask again') + const receiving = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + ;(receiving.prepared as any).modelOutput?.() + expect(f.store.unreadWorkNotes(t.workId)).toEqual([]) +}) + +it('switch off keeps repeated and differing calls direct without cards or refusal notes', async () => { + const t = await setup(false) + for (const body of [t.args.body, t.args.body, 'different']) { + expect(await callForBot({ bot: t.work.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body }, toolCallId: body, signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + } + expect(t.calls).toHaveLength(3) + expect(f.store.all('SELECT id FROM bot_actions')).toEqual([]) + expect(f.store.unreadWorkNotes(t.workId)).toEqual([]) +}) + +it('switch off refuses card answers without resetting repeated-wait detection', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.host.settings!.get().experimental.botAsksFirst = false + for (const answer of ['send', 'not_now'] as const) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer })).rejects.toThrow('switch is off') + expect(f.store.all("SELECT * FROM bot_memory_state WHERE key LIKE 'cursor:action-owner:%'")).toEqual([]) +}) From 4cfb61133e9f6aac79b6423f8aa88680f7706aaf Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:21:01 +0530 Subject: [PATCH 06/84] test(bots): wait for the resumed dispatch before checking refusal delivery --- tests/bots/botActions.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index a4f6ff3f89..7a4da03bee 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1230,6 +1230,7 @@ it('a repeat refusal joins unread work updates without another action or card', await t.call(); await finish(f, t.work.payload) const a = f.bots.actions.forWork(t.workId)! await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush() const next = await start(f, t.workId, 2) ;(next.prepared as any).modelOutput?.() await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'repeat-refused', signal: new AbortController().signal }) From 61a9a31d366581a4366d52918ec8ea6498b00707 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:21:58 +0530 Subject: [PATCH 07/84] test(bots): include repeat refusals in the continuation matrix --- tests/bots/botContinuationMatrix.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 0738a86d92..5c9992cdab 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -90,3 +90,13 @@ it.each(['question answer', 'note and answer'] as const)('N3 a live wait plus a expect(prompt.split('Your wait is over.')).toHaveLength(2) expect(prompt).toContain('The owner allowed you to read pages') }) + + +it.each([false, true])('repeat refusal joins ordered updates with wait history=%s', hasWaited => { + const input = matrixInput('turn cap', 'note and answer', hasWaited) + const refusal = 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.' + input.workEvents.push({ at: '2026-11-07T09:04:00Z', text: refusal }) + const prompt: string = (f.bots as any).continuationPrompt(ROW, input) + expect(prompt.split(refusal)).toHaveLength(2) + expect(prompt.indexOf(NOTE)).toBeLessThan(prompt.indexOf(refusal)) +}) From 11aa0f844cd63e7229cd277eadea9eb07bca3324 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:22:33 +0530 Subject: [PATCH 08/84] fix(bots): preserve repeat refusals in ordered unread updates --- docs/bots.md | 2 +- src/mms/bots/actions/BotActions.ts | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/bots.md b/docs/bots.md index a4cca43f43..516fd51d53 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -787,7 +787,7 @@ A held call is withdrawn, with executable arguments cleared in the same transact An owner pause keeps a held card: a pause is not a refusal. Send says "Resume this bot before sending." while paused. A card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline again. -After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row. A changed argument is a new review, as a changed wake brief is new progress under the wake loop rule: there is no fixed lifetime count of cards. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. +After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a note in the same ordered update list preserves it for the next continuation. A changed argument is a new review, as a changed wake brief is new progress under the wake loop rule: there is no fixed lifetime count of cards. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. Hidden argument values of four to eight characters require an adjacent character outside `[A-Za-z0-9_]` only at an edge whose own character is an ASCII letter, digit or underscore. Other edges require no boundary; longer values are replaced wherever they occur. Values shorter than four characters are left alone. Replacement runs in the server's own text before Mousse frames it, including JSON-escaped string echoes and numeric echoes. Credential masking still applies to the result. Transformed echoes (for example encoded, upper-case or truncated values) are not caught by this exact-value replacement. The stored result is capped at 64 KiB in total; images are omitted with a note, never cut into invalid data. Journal key-name masking applies only to work with a held action; other work keeps master's tool input capture. diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 8b730dd03a..56a3861c73 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -239,10 +239,14 @@ export class BotActions { if (refused) { const seq = Number(JSON.parse(String(refused.card_json ?? '{}')).ownerSeq ?? 0) const note = Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', row.botId, `cursor:action-note:${row.id}`)?.value ?? 0) > Number(JSON.parse(String(refused.card_json ?? '{}')).noteSeq ?? 0) - if (this.host.store.ownerLastWroteSeq(row.botId) <= seq && !note) - return { text: 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.', isError: true } + if (this.host.store.ownerLastWroteSeq(row.botId) <= seq && !note) { + const text = 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.' + // Reuse notes in the ordered update list: a lost tool reply must not lose the refusal. + if (!this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND from_message = ? AND text = ?', row.id, refused.message_id, text)) + this.host.store.addWorkNote(row.id, row.botId, text, String(refused.message_id)) + return { text, isError: true } + } } - if (pending.has(this.forWork(row.id)?.status ?? '')) return { text: 'A call already waits for your owner. End your turn now.', isError: true } const binding = this.host.binding(row, tool) if (!binding) return { text: 'This tool changed. Carry on without it.', isError: true } if (containsCredential(args)) return { text: 'This contains something that looks like a secret. It is never sent through a tool this way. Send it without that value.', isError: true } From 0f23b30f4769ec0b331091501330a69176698e53 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:23:39 +0530 Subject: [PATCH 09/84] test(bots): build refusal matrix events for work without waits --- tests/bots/botContinuationMatrix.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 5c9992cdab..f459afc529 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -95,7 +95,7 @@ it.each(['question answer', 'note and answer'] as const)('N3 a live wait plus a it.each([false, true])('repeat refusal joins ordered updates with wait history=%s', hasWaited => { const input = matrixInput('turn cap', 'note and answer', hasWaited) const refusal = 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.' - input.workEvents.push({ at: '2026-11-07T09:04:00Z', text: refusal }) + input.workEvents = [...eventsOf(input), { at: '2026-11-07T09:04:00Z', text: refusal }] const prompt: string = (f.bots as any).continuationPrompt(ROW, input) expect(prompt.split(refusal)).toHaveLength(2) expect(prompt.indexOf(NOTE)).toBeLessThan(prompt.indexOf(refusal)) From 9563447050d8300f36b66301bd6a262f26ea98f7 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:29:37 +0530 Subject: [PATCH 10/84] fix(bots): bind the refusal message id as a database string --- src/mms/bots/actions/BotActions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 56a3861c73..68bff41e10 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -242,7 +242,7 @@ export class BotActions { if (this.host.store.ownerLastWroteSeq(row.botId) <= seq && !note) { const text = 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.' // Reuse notes in the ordered update list: a lost tool reply must not lose the refusal. - if (!this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND from_message = ? AND text = ?', row.id, refused.message_id, text)) + if (!this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND from_message = ? AND text = ?', row.id, String(refused.message_id), text)) this.host.store.addWorkNote(row.id, row.botId, text, String(refused.message_id)) return { text, isError: true } } From 5d38191b7187cac6403ea7a41da0eb34c1bea932 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:44:42 +0530 Subject: [PATCH 11/84] test(bots): keep held cards across temporary MCP listing gaps --- tests/bots/botActions.test.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 7a4da03bee..abf2ecd269 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1050,7 +1050,7 @@ it.each(['stop', 'failed', 'limits', 'week', 'clear', 'reset', 'delete', 'forget if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) if (['failed', 'limits', 'week'].includes(path)) f.store.moveActivation(t.workId, ['blocked'], 'failed', { endReason: path }) if (path === 'allowed') f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: m.mcp.map(p => ({ ...p, level: 'allowed' as const })) })) - if (path === 'server') { vi.spyOn(t.mcp, 'binding').mockReturnValue(undefined); f.bots.fillMcpAsks() } + if (path === 'server') { vi.spyOn(t.mcp, 'where').mockReturnValue({ state: 'gone' }); f.bots.fillMcpAsks() } if (path === 'card' || path === 'request') { const id = path === 'card' ? a.message_id : String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) const memory = new BotMemoryStore({ db: f.store.db }) @@ -1203,7 +1203,7 @@ it.each(['stop', 'failed', 'limits', 'week', 'clear', 'reset', 'delete', 'forget else if (path === 'allowed') change = () => f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: m.mcp.map(p => ({ ...p, level: 'allowed' as const })) })) else if (path === 'tool' || path === 'server') change = () => { if (path === 'tool') t.server.tools.splice(0) - else vi.spyOn(t.mcp, 'binding').mockReturnValue(undefined) + else vi.spyOn(t.mcp, 'where').mockReturnValue({ state: 'gone' }) f.bots.fillMcpAsks() } else if (path === 'clear') change = () => f.bots.clearChat(t.botId) @@ -1263,3 +1263,21 @@ it('switch off refuses card answers without resetting repeated-wait detection', await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer })).rejects.toThrow('switch is off') expect(f.store.all("SELECT * FROM bot_memory_state WHERE key LIKE 'cursor:action-owner:%'")).toEqual([]) }) + +it.each(['failing', 'starting', 'cold restart'] as const)('B1 keeps a live card through a %s listing and sends once after recovery', async state => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const tools = t.server.tools.splice(0) + if (state === 'failing') t.server.failing = true + if (state === 'starting') Object.assign(t.server, { starting: true }) + const listing = state === 'cold restart' ? vi.spyOn(t.mcp, 'where').mockReturnValue(undefined) : undefined + if (state === 'cold restart') { f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() } + else f.bots.fillMcpAsks() + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() + t.server.tools.push(...tools); t.server.failing = false; Object.assign(t.server, { starting: false }); listing?.mockRestore() + f.bots.fillMcpAsks() + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + expect(t.calls).toEqual([t.args]) +}) From 0b86f58b4801c0b63ae08e0bd4ee2b3f1bce756e Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:45:07 +0530 Subject: [PATCH 12/84] fix(bots): withdraw held calls only on positive MCP evidence --- src/mms/bots/actions/BotActions.ts | 3 ++- src/mms/bots/activation/BotEngine.ts | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 68bff41e10..e111f3eade 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -172,6 +172,7 @@ interface Host { park(row: BotActivationRow): void schema(tool: BotMcpTool): unknown binding(row: BotActivationRow, tool: BotMcpTool): unknown | undefined + obsolete(action: ActionRow): boolean post(row: BotActivationRow, id: string, text: string): void settled(row: BotActivationRow): void publish(messageId: string): void @@ -214,7 +215,7 @@ export class BotActions { withdrawChanged(): void { if (!this.host.enabled()) return for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved')")) { - if (!this.valid(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.host.store.db.afterCommit(() => this.finish(a as unknown as ActionRow)) + if (this.host.obsolete(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.host.store.db.afterCommit(() => this.finish(a as unknown as ActionRow)) } } get(id: string): ActionRow | undefined { return this.host.store.get('SELECT * FROM bot_actions WHERE id = ?', id) as unknown as ActionRow | undefined } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index cc955e57f3..21c1dee8b8 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -618,6 +618,21 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const revision = this.store.get('SELECT grant_id FROM bot_grants WHERE bot_id = ? AND revoked_at IS NULL ORDER BY grant_id DESC LIMIT 1', row.botId)?.grant_id return { ...server, grantRevision: revision, grantDigest: actionDigest(grant.manifest), deviceLimit: limit } }, + obsolete: action => { + const row = this.store.activation(action.activation_id) + const grant = this.store.activeGrant(action.bot_id) + const held = JSON.parse(action.binding_json) + const revision = this.store.get('SELECT grant_id FROM bot_grants WHERE bot_id = ? AND revoked_at IS NULL ORDER BY grant_id DESC LIMIT 1', action.bot_id)?.grant_id + if (!row || !grant || held.grantRevision !== revision || held.grantDigest !== actionDigest(grant.manifest)) return true + const tool = JSON.parse(action.target_json) as BotMcpTool + const where = this.host.mcp?.where?.(tool.server) + if (!where) return false // A cold catalogue is not evidence of removal. + if (where.state !== 'on') return true + if (where.server.failing || where.server.starting) return false + if (!where.server.tools.some(t => t.tool === tool.tool)) return true + const binding = this.host.mcp?.binding?.(tool) + return Boolean(binding && (binding.configDigest !== held.configDigest || binding.schemaDigest !== held.schemaDigest)) + }, post: (row, id, text) => this.chat.post({ id, botId: row.botId, author: 'bot', kind: 'notice', text, external: true, activationId: row.id, lane: 'run', ...(row.trigger.kind === 'work' && row.trigger.replyTo ? { replyTo: row.trigger.replyTo } : {}) }), settled: (row) => { this.chat.republish(this.actions.forWork(row.id)!.message_id); this.changed({ botId: row.botId }); this.pumpLater(row.botId) }, execute: async (row, target, args) => { From 61b5e6d21343622b11dfab81f9270139a81c1081 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:45:42 +0530 Subject: [PATCH 13/84] test(bots): Forget erases pending and settled action content --- tests/bots/botActions.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index abf2ecd269..48699b1c23 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1281,3 +1281,22 @@ it.each(['failing', 'starting', 'cold restart'] as const)('B1 keeps a live card await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) expect(t.calls).toEqual([t.args]) }) + +it.each(['card', 'request'].flatMap(which => ['open', 'declined', 'done'].map(status => ({ which, status }))))('B2 Forget $which erases $status call text from the record and export', async ({ which, status }) => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (status !== 'open') await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: status === 'done' ? 'send' : 'not_now' }) + const counters = JSON.parse(f.bots.actions.get(a.id)!.card_json!) + const request = f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0]! + const id = which === 'card' ? a.message_id : String(request.id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + const saved = f.bots.actions.get(a.id)! + expect(saved).toMatchObject({ args_json: '"[forgotten]"', result_json: '{"text":"[forgotten]"}' }) + expect(JSON.parse(saved.card_json!)).toMatchObject({ text: '[forgotten]', ownerSeq: counters.ownerSeq ?? 0, noteSeq: counters.noteSeq ?? 0 }) + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('Exact text') + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('one@example.test') + expect(saved.call_key).toBe(a.call_key) +}) From 5caf8ceeb438a4f5612526b899def82d3c03383f Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:45:58 +0530 Subject: [PATCH 14/84] test(bots): keep refusal counters when history is forgotten --- tests/bots/botActions.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 48699b1c23..6aff443700 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1300,3 +1300,13 @@ it.each(['card', 'request'].flatMap(which => ['open', 'declined', 'done'].map(st expect(JSON.stringify(memory.actions(t.botId))).not.toContain('one@example.test') expect(saved.call_key).toBe(a.call_key) }) + +it('B4 forget history keeps the refusal counters while erasing card text', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + const before = JSON.parse(f.bots.actions.get(a.id)!.card_json!) + await f.bots.wipeMemory(t.botId, 'saved') + expect(JSON.parse(f.bots.actions.get(a.id)!.card_json!)).toMatchObject({ text: '[forgotten]', ownerSeq: before.ownerSeq, noteSeq: before.noteSeq }) +}) From ffe45cbf35a530dbcc46642480e0289e681ec448 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:46:27 +0530 Subject: [PATCH 15/84] fix(bots): tombstone forgotten calls and retain refusal counters --- src/mms/bots/actions/BotActions.ts | 15 +++++++++++++-- src/mms/bots/activation/BotEngine.ts | 3 +-- tests/bots/botActions.test.ts | 2 +- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index e111f3eade..584b8530ec 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -191,9 +191,12 @@ export class BotActions { forgetMessage: (botId, messageId) => { if (!host.enabled()) return const ids = host.store.all(`SELECT a.* FROM bot_actions a JOIN bot_activations w ON w.id = a.activation_id - WHERE a.bot_id = ? AND a.status IN ('open', 'approved') AND (a.message_id = ? OR json_extract(w.trigger_json, '$.replyTo') = ?)`, botId, messageId, messageId) + WHERE a.bot_id = ? AND (a.message_id = ? OR json_extract(w.trigger_json, '$.replyTo') = ?)`, botId, messageId, messageId) for (const action of ids) { - this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'The request was forgotten. Nothing was sent.' }) + const pending = ['open', 'approved'].includes(String(action.status)) + if (pending) this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'The request was forgotten. Nothing was sent.' }) + this.forgetText(botId, String(action.id)) + if (!pending) continue const row = host.store.activation(String(action.activation_id)) if (row && host.store.moveActivation(row.id, ['blocked'], 'cancelled', { endReason: 'forgotten', result: 'This work ended because its request was forgotten.' })) host.post(row, `bm_${action.id}_forgotten`, 'This work ended because its request was forgotten.') @@ -201,6 +204,14 @@ export class BotActions { } }) } + /** Erase call content without erasing owner intervention facts or the run-once key. */ + forgetText(botId: string, actionId?: string): void { + if (!this.host.enabled()) return + this.host.store.run(`UPDATE bot_actions SET args_json = ?, + card_json = json_object('text', '[forgotten]', 'ownerSeq', COALESCE(json_extract(card_json, '$.ownerSeq'), 0), 'noteSeq', COALESCE(json_extract(card_json, '$.noteSeq'), 0)), + bot_note = ?, result_json = ? WHERE bot_id = ? AND (? IS NULL OR id = ?)`, + '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId, actionId ?? null, actionId ?? null) + } withdrawWork(id: string): void { if (!this.host.enabled()) return for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND status IN ('open', 'approved')", id)) diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 21c1dee8b8..9e166a87e5 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -7454,8 +7454,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { await this.clearChat(botId) const removed = this.store.db.transaction(() => { const removed = memory.wipeHistory(botId) - if (botAsksFirst(this.host.settings?.get())) this.store.run(`UPDATE bot_actions SET args_json = ?, card_json = ?, bot_note = ?, result_json = ? WHERE bot_id = ?`, - '"[forgotten]"', '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId) + this.actions.forgetText(botId) return removed }) this.changed({ botId }) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 6aff443700..d3b085eb09 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1101,7 +1101,7 @@ it('forget history removes settled text and preserves the call key that prevents await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) await f.bots.wipeMemory(t.botId, 'saved') const saved = f.bots.actions.get(a.id)! - expect(saved).toMatchObject({ call_key: a.call_key, status: 'declined', args_json: '"[forgotten]"', card_json: '"[forgotten]"', result_json: '{"text":"[forgotten]"}' }) + expect(saved).toMatchObject({ call_key: a.call_key, status: 'declined', args_json: '"[forgotten]"', result_json: '{"text":"[forgotten]"}' }) const result = f.bots.actions.hold(f.store.activation(t.workId)!, JSON.parse(a.call_key)[1], { server: 'mail', tool: 'send' } as never, t.args, 'runtime-call-1') expect(result).not.toMatchObject({ isError: true }) expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) From 3eb4b339c84d40b74b9143d7eee850ccc3339e2c Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:46:48 +0530 Subject: [PATCH 16/84] test(bots): forgetting a call removes its argument fingerprint --- tests/bots/botActions.test.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index d3b085eb09..48ab72dadf 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1310,3 +1310,22 @@ it('B4 forget history keeps the refusal counters while erasing card text', async await f.bots.wipeMemory(t.botId, 'saved') expect(JSON.parse(f.bots.actions.get(a.id)!.card_json!)).toMatchObject({ text: '[forgotten]', ownerSeq: before.ownerSeq, noteSeq: before.noteSeq }) }) + +it.each(['card', 'request', 'history'] as const)('B5 Forget %s erases the argument digest and keeps the call key', async which => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + if (which === 'history') await f.bots.wipeMemory(t.botId, 'saved') + else { + const id = which === 'card' ? a.message_id : String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ args_digest: '[forgotten]', call_key: a.call_key, status: 'declined' }) + f.bots.actions.hold(f.store.activation(t.workId)!, JSON.parse(a.call_key)[1], { server: 'mail', tool: 'send' } as never, t.args, 'runtime-call-1') + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(f.store.get('SELECT id FROM bot_actions WHERE args_digest = ?', a.args_digest)).toBeUndefined() + expect(t.calls).toEqual([]) +}) From 1b0435773b546382472e5468e0cc763d20b6a9d7 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:47:43 +0530 Subject: [PATCH 17/84] fix(bots): erase forgotten argument digests --- src/mms/bots/actions/BotActions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 584b8530ec..df852e00e0 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -207,7 +207,7 @@ export class BotActions { /** Erase call content without erasing owner intervention facts or the run-once key. */ forgetText(botId: string, actionId?: string): void { if (!this.host.enabled()) return - this.host.store.run(`UPDATE bot_actions SET args_json = ?, + this.host.store.run(`UPDATE bot_actions SET args_json = ?, args_digest = '[forgotten]', card_json = json_object('text', '[forgotten]', 'ownerSeq', COALESCE(json_extract(card_json, '$.ownerSeq'), 0), 'noteSeq', COALESCE(json_extract(card_json, '$.noteSeq'), 0)), bot_note = ?, result_json = ? WHERE bot_id = ? AND (? IS NULL OR id = ?)`, '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId, actionId ?? null, actionId ?? null) From 20724aac5c2e74989aadae288b230799083a6159 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:47:43 +0530 Subject: [PATCH 18/84] test(bots): three declined calls stop trivial argument loops --- tests/bots/botActions.test.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 48ab72dadf..25f1c260f0 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1329,3 +1329,28 @@ it.each(['card', 'request', 'history'] as const)('B5 Forget %s erases the argume expect(f.store.get('SELECT id FROM bot_actions WHERE args_digest = ?', a.args_digest)).toBeUndefined() expect(t.calls).toEqual([]) }) + +it.each([true, false])('B3 three declined cards stop changed calls until owner input, switch=%s', async on => { + const t = await setup(on, false, true) + let runtime = t.work + for (let n = 0; n < 20; n++) { + const outcome = await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: t.args.body + ' '.repeat(n) }, toolCallId: `loop-${n}`, signal: new AbortController().signal }) + if (!on) continue + if (n < 3) { + await finish(f, runtime.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush(); runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + } else expect(outcome).toMatchObject({ isError: true, text: expect.stringContaining('said no three times') }) + } + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(on ? 3 : 0) + if (!on) { expect(t.calls).toHaveLength(20); return } + expect(f.store.unreadWorkNotes(t.workId).map(n => n.text).join(' ')).toContain('said no three times') + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__other', args: t.args, toolCallId: 'another-tool', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + await finish(f, runtime.payload) + const other = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: other.id, digest: other.args_digest, answer: 'not_now' }) + await flush(); runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + f.bots.noteWork(t.botId, t.workId, 'Please try again') + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'try again' }, toolCallId: 'after-note', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) +}) From 144c5d09840460dbb4520e514f29fc3b21a30f76 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:48:37 +0530 Subject: [PATCH 19/84] fix(bots): stop a tool after three declined cards until owner input --- src/mms/bots/actions/BotActions.ts | 29 +++++++++++++++--------- tests/bots/botActions.test.ts | 4 ++-- tests/bots/botContinuationMatrix.test.ts | 6 +++-- 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index df852e00e0..b102c9c8a6 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -1,3 +1,4 @@ +import { MAX_SAME_WAKES } from '../../../shared/bots/personal/wakes' import { registerHeldCalls } from './lifecycle' import { randomUUID } from 'node:crypto' import type { MousseSettings } from '../../../shared/settings' @@ -240,25 +241,31 @@ export class BotActions { const dispatch = this.host.store.dispatches(activationId).find(d => d.clientRequestId === dispatchId) return dispatch && (dispatch.n === mainN || dispatch.mainN === mainN) ? action : undefined } + private ownerWroteAfter(action: ActionRow): boolean { + const card = JSON.parse(action.card_json ?? '{}') + const note = Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', action.bot_id, `cursor:action-note:${action.activation_id}`)?.value ?? 0) + return this.host.store.ownerLastWroteSeq(action.bot_id) > Number(card.ownerSeq ?? 0) || note > Number(card.noteSeq ?? 0) + } + private refuse(row: BotActivationRow, action: ActionRow, text: string): ToolOutcome { + // A lost tool reply must not lose the refusal: use the same ordered notes as other updates. + if (!this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND from_message = ? AND text = ?', row.id, action.message_id, text)) + this.host.store.addWorkNote(row.id, row.botId, text, action.message_id) + return { text, isError: true } + } hold(row: BotActivationRow, dispatch: string, tool: BotMcpTool, args: Record, toolCallId?: string): ToolOutcome { if (!toolCallId) return { text: 'This call cannot be held without its call id. Carry on without it.', isError: true } const callKey = JSON.stringify([row.id, dispatch, toolCallId]) const existing = this.host.store.get('SELECT id FROM bot_actions WHERE call_key = ?', callKey) if (existing) return { text: 'This call is held for your owner. End your turn now.' } if (pending.has(this.forWork(row.id)?.status ?? '')) return { text: 'A call is already held for your owner. End your turn now.', isError: true } + const declined = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND status = 'declined' ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool })) as unknown as ActionRow[] + const unanswered = declined.filter(action => !this.ownerWroteAfter(action)) + if (unanswered.length >= MAX_SAME_WAKES) + return this.refuse(row, unanswered[0], 'Your owner said no three times. Say what you need in your report and wait for them to write.') const digest = actionDigest(args) const refused = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND args_digest = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), digest)[0] - if (refused) { - const seq = Number(JSON.parse(String(refused.card_json ?? '{}')).ownerSeq ?? 0) - const note = Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', row.botId, `cursor:action-note:${row.id}`)?.value ?? 0) > Number(JSON.parse(String(refused.card_json ?? '{}')).noteSeq ?? 0) - if (this.host.store.ownerLastWroteSeq(row.botId) <= seq && !note) { - const text = 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.' - // Reuse notes in the ordered update list: a lost tool reply must not lose the refusal. - if (!this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND from_message = ? AND text = ?', row.id, String(refused.message_id), text)) - this.host.store.addWorkNote(row.id, row.botId, text, String(refused.message_id)) - return { text, isError: true } - } - } + if (refused && !this.ownerWroteAfter(refused as unknown as ActionRow)) + return this.refuse(row, refused as unknown as ActionRow, 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.') const binding = this.host.binding(row, tool) if (!binding) return { text: 'This tool changed. Carry on without it.', isError: true } if (containsCredential(args)) return { text: 'This contains something that looks like a secret. It is never sent through a tool this way. Send it without that value.', isError: true } diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 25f1c260f0..4ad394ab2c 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1158,7 +1158,7 @@ it.each(['stop', 'expiry', 'forget'] as const)('the disabled switch leaves held }) it.each(['send', 'not_now'] as const)('owner %s resets detection of repeated waits, as a question answer does', async answer => { - const t = await setup(true) + const t = await setup(true, false, true) for (let round = 0; round < 4; round++) { const current = f.store.activation(t.workId)! const n = f.store.lastMainDispatch(t.workId)!.n @@ -1168,7 +1168,7 @@ it.each(['send', 'not_now'] as const)('owner %s resets detection of repeated wai f.clock.now += 300_000 await f.bots.deliverDueReminders(); await flush() const next = await start(f, t.workId, n + 1) - await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: `mail ${round}` }, toolCallId: `mail-${round}`, signal: new AbortController().signal }) + await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: round % 2 ? 'Mail__other' : 'Mail__send', args: { ...t.args, body: `mail ${round}` }, toolCallId: `mail-${round}`, signal: new AbortController().signal }) await finish(f, next.payload) const a = f.bots.actions.forWork(current.id)! await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer }) diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index f459afc529..91d422b027 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -92,9 +92,11 @@ it.each(['question answer', 'note and answer'] as const)('N3 a live wait plus a }) -it.each([false, true])('repeat refusal joins ordered updates with wait history=%s', hasWaited => { +it.each([false, true].flatMap(hasWaited => [ + 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.', + 'Your owner said no three times. Say what you need in your report and wait for them to write.' +].map(refusal => ({ hasWaited, refusal }))))('refusal joins ordered updates with wait history=$hasWaited: $refusal', ({ hasWaited, refusal }) => { const input = matrixInput('turn cap', 'note and answer', hasWaited) - const refusal = 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.' input.workEvents = [...eventsOf(input), { at: '2026-11-07T09:04:00Z', text: refusal }] const prompt: string = (f.bots as any).continuationPrompt(ROW, input) expect(prompt.split(refusal)).toHaveLength(2) From 1dc107f0abca45bd652b2272ed8cf2bd4c79fab5 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:49:24 +0530 Subject: [PATCH 20/84] test(bots): only changes to the held MCP pair invalidate its card --- tests/bots/botActions.test.ts | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 4ad394ab2c..03c12b0c30 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -108,7 +108,7 @@ it('holds once, frees the slot, and Send executes exactly the stored arguments o // Actors: a second device, changed schema/configuration/grant/device ceiling, restart. // Orders: answer before/after turn end, double Send, Send versus Not now, approved/running crash. -it.each(['digest', 'schema', 'configuration', 'grant', 'device'] as const)('refuses a stale %s without making a call', async (change) => { +it.each(['digest', 'schema', 'configuration', 'device'] as const)('refuses a stale %s without making a call', async (change) => { const t = await setup(true) await t.call() await finish(f, t.work.payload) @@ -117,10 +117,6 @@ it.each(['digest', 'schema', 'configuration', 'grant', 'device'] as const)('refu if (change === 'digest') answer.digest = 'old-digest' if (change === 'schema') t.descriptor.inputSchema = { type: 'object', required: ['extra'] } as never if (change === 'configuration') t.server.configDigest = 'changed' - if (change === 'grant') { - const grant = f.store.activeGrant(t.botId)! - f.store.approve(t.botId, grant.digest, grant.manifest) - } if (change === 'device') f.store.narrowOwnerLimit(t.chatId, 'plan') await expect(f.bots.actions.answer(answer)).rejects.toThrow('changed since') expect(t.calls).toEqual([]) @@ -1354,3 +1350,28 @@ it.each([true, false])('B3 three declined cards stop changed calls until owner i f.bots.noteWork(t.botId, t.workId, 'Please try again') expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'try again' }, toolCallId: 'after-note', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) }) + +it.each(['unrelated permission', 'revision only'] as const)('B6 %s preserves an open card and Send executes once', async change => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (change === 'unrelated permission') f.bots.narrowGrant(t.botId, m => ({ ...m, appTools: [...m.appTools, 'web_search', 'web_fetch'] })) + else { const grant = f.store.activeGrant(t.botId)!; f.store.approve(t.botId, grant.digest, grant.manifest); f.bots.fillMcpAsks() } + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() + expect(t.calls).toEqual([t.args]) +}) + +it('B6 removal then re-grant of the pair cannot revive its old card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const pairs = f.store.activeGrant(t.botId)!.manifest.mcp + f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + expect(f.bots.actions.get(a.id)?.status).toBe('withdrawn') + f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: pairs })) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() + expect(f.bots.actions.get(a.id)?.status).toBe('withdrawn') + expect(t.calls).toEqual([]) +}) From 16b20f019276641fb090a9fbc9e2c656626efeb4 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:50:02 +0530 Subject: [PATCH 21/84] fix(bots): bind held approval to its MCP pair and permission level --- src/mms/bots/activation/BotEngine.ts | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 9e166a87e5..0aa05d89bb 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -594,6 +594,15 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { readonly chat: BotChatProjection /** The Bot UI's methods (`bots.*` v2). */ readonly actions: BotActions + /** A held call is authorized only for its own pair, independent of unrelated grant revisions. */ + private actionPair(row: BotActivationRow, tool: BotMcpTool): BotManifest['mcp'][number] | undefined { + const current = this.store.activation(row.id) + const grant = this.store.activeGrant(row.botId) + const definition = current && this.host.definitions.revision(row.botId, current.revision) + if (!current || !['running', 'blocked'].includes(current.status) || !grant || !definition) return undefined + const offered = this.effectiveManifest(current, definition.permissions, grant.manifest).mcp.some(p => p.serverId === tool.server && p.tool === tool.tool) + return offered ? grant.manifest.mcp.find(p => p.serverId === tool.server && p.tool === tool.tool) : undefined + } private createActions(): BotActions { return new BotActions({ store: this.host.store, refresh: async () => { await this.host.mcp?.warm() }, @@ -608,23 +617,20 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { held: () => { this.watchMcp(); this.armDue() }, schema: (tool) => this.host.mcp?.inputSchema?.(tool), binding: (row, tool) => { - const grant = this.store.activeGrant(row.botId) - const current = this.store.activation(row.id) - if (!grant || !current || !['running', 'blocked'].includes(current.status) || current.grantDigest !== grant.digest || !this.grantNow(row.id)?.mcp.some(p => p.serverId === tool.server && p.tool === tool.tool)) return undefined + const pair = this.actionPair(row, tool) + if (!pair) return undefined const server = this.host.mcp?.binding?.(tool) if (!server) return undefined const source = row.trigger.kind === 'work' ? this.store.activation(row.trigger.from) : row const limit = source?.trigger.kind === 'manual' ? source.trigger.owner?.limit ?? null : null - const revision = this.store.get('SELECT grant_id FROM bot_grants WHERE bot_id = ? AND revoked_at IS NULL ORDER BY grant_id DESC LIMIT 1', row.botId)?.grant_id - return { ...server, grantRevision: revision, grantDigest: actionDigest(grant.manifest), deviceLimit: limit } + return { ...server, pairLevel: pair.level ?? 'allowed', deviceLimit: limit } }, obsolete: action => { const row = this.store.activation(action.activation_id) - const grant = this.store.activeGrant(action.bot_id) const held = JSON.parse(action.binding_json) - const revision = this.store.get('SELECT grant_id FROM bot_grants WHERE bot_id = ? AND revoked_at IS NULL ORDER BY grant_id DESC LIMIT 1', action.bot_id)?.grant_id - if (!row || !grant || held.grantRevision !== revision || held.grantDigest !== actionDigest(grant.manifest)) return true const tool = JSON.parse(action.target_json) as BotMcpTool + const pair = row && this.actionPair(row, tool) + if (!pair || held.pairLevel !== (pair.level ?? 'allowed')) return true const where = this.host.mcp?.where?.(tool.server) if (!where) return false // A cold catalogue is not evidence of removal. if (where.state !== 'on') return true @@ -643,7 +649,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const actionId = this.actions.forWork(row.id)!.id return callForBot({ mcp: mcp as BotMcp, bot: { activationId: row.id, mcpTools: [tool], workspace: null, time: { signal, deadline: () => Number.MAX_SAFE_INTEGER }, - check: () => this.grantNow(row.id)?.mcp.some(p => p.serverId === target.server && p.tool === target.tool) ? { ok: true } : { ok: false, wall: { kind: 'revoked' } } + check: () => this.actionPair(row, target) ? { ok: true } : { ok: false, wall: { kind: 'revoked' } } }, name: tool.name, args, signal, heldAction: true, sanitizeResult: (result) => removeHiddenArguments(result, args, mcp.inputSchema?.(target)), assertDispatchActive: () => { this.actions.assertRunning(actionId) } }) From d058d30ea77745d67cb948cfcb7983fe0c81e756 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:50:14 +0530 Subject: [PATCH 22/84] test(bots): restart cannot send an approved call while paused --- tests/bots/botActions.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 03c12b0c30..8600086219 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1375,3 +1375,23 @@ it('B6 removal then re-grant of the pair cannot revive its old card', async () = expect(f.bots.actions.get(a.id)?.status).toBe('withdrawn') expect(t.calls).toEqual([]) }) + +it('restart never executes a previously approved call while its owner has paused the bot', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.bots.actions.transition(a.id, 'open', 'approved') + f.bots.pauseBot(t.botId) + f.bots.close(); f.bots = new BotEngine(f.host) + await f.bots.reconcileOnStartup() + expect(t.calls).toEqual([]) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe('Not sent') + expect(f.store.unreadWorkActions(t.workId).map(a => a.id)).toEqual([a.id]) + await f.bots.resumeBot(t.botId); await flush() + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('paused') + const next = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + ;(next.prepared as any).modelOutput?.() + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) + expect(t.calls).toEqual([]) +}) From a3b42db07cd70dc2cf88fb6a13a39a3323755ffc Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:50:50 +0530 Subject: [PATCH 23/84] fix(bots): settle approved calls without sending on a paused restart --- src/mms/bots/actions/BotActions.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index b102c9c8a6..7752c6ff72 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -357,6 +357,11 @@ export class BotActions { private async runApproved(id: string): Promise { const action = this.get(id) if (!action || action.status !== 'approved') return + if (this.host.store.registry(action.bot_id)?.pausedReason === 'owner') { + this.transition(id, 'approved', 'withdrawn', { text: 'This bot was paused by its owner. Nothing was sent; carry on without it when resumed.' }) + this.finish(action) + return + } const row = this.valid(action) if (!row) { this.transition(id, 'approved', Date.parse(action.expires_at) <= Date.parse(this.host.store.now()) ? 'expired' : 'withdrawn', { text: 'This changed since you saw it. Nothing was sent; carry on without it.' }) From f580d26bce25d3129f571b787e64f4ecfba21254 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:51:10 +0530 Subject: [PATCH 24/84] test(bots): distinguish cold approved calls from changed server configuration --- tests/bots/botActions.test.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 8600086219..f708b2da05 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1395,3 +1395,29 @@ it('restart never executes a previously approved call while its owner has paused expect(f.store.unreadWorkActions(t.workId)).toEqual([]) expect(t.calls).toEqual([]) }) + +it('B1 an approved row survives a cold restart and runs only after a successful listing', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.bots.actions.transition(a.id, 'open', 'approved') + const tools = t.server.tools.splice(0) + const where = vi.spyOn(t.mcp, 'where').mockReturnValue(undefined) + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + expect(f.bots.actions.get(a.id)?.status).toBe('approved') + expect(t.calls).toEqual([]) + t.server.tools.push(...tools); where.mockRestore() + f.bots.fillMcpAsks(); await flush() + expect(f.bots.actions.get(a.id)?.status).toBe('done') + expect(t.calls).toEqual([t.args]) +}) + +it('B1 a real configuration change withdraws even while the server listing fails', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + t.server.tools.splice(0); t.server.failing = true; t.server.configDigest = 'changed' + f.bots.fillMcpAsks() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(t.calls).toEqual([]) +}) From 5cf8e2263afd7dac00db330185b514747e32a97e Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:51:49 +0530 Subject: [PATCH 25/84] fix(bots): recover approved calls when MCP listings return --- src/mms/bots/actions/BotActions.ts | 8 +++++++- src/mms/bots/activation/BotEngine.ts | 3 +++ src/mms/bots/mcp/BotMcp.ts | 6 ++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 7752c6ff72..cf579914e8 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -364,6 +364,7 @@ export class BotActions { } const row = this.valid(action) if (!row) { + if (Date.parse(action.expires_at) > Date.parse(this.host.store.now()) && !this.host.obsolete(action)) return this.transition(id, 'approved', Date.parse(action.expires_at) <= Date.parse(this.host.store.now()) ? 'expired' : 'withdrawn', { text: 'This changed since you saw it. Nothing was sent; carry on without it.' }) this.finish(action) return @@ -387,13 +388,18 @@ export class BotActions { if (!row) return this.host.settled(row) } + async retryApproved(): Promise { + if (!this.host.enabled()) return + for (const action of this.host.store.all("SELECT id FROM bot_actions WHERE status = 'approved'")) + await this.runApproved(String(action.id)) + } async reconcile(): Promise { if (!this.host.enabled()) return this.expireDue() const interrupted = this.host.store.all("SELECT id FROM bot_actions WHERE status IN ('running', 'approved')") await this.host.refresh() this.withdrawChanged() - if (this.host.store.get("SELECT 1 FROM bot_actions WHERE status = 'open' LIMIT 1")) this.host.held() + if (this.host.store.get("SELECT 1 FROM bot_actions WHERE status IN ('open', 'approved') LIMIT 1")) this.host.held() for (const a of interrupted) { const action = this.get(String(a.id)) if (!action || this.executing.has(action.id)) continue diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 0aa05d89bb..218bf6d770 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -634,6 +634,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const where = this.host.mcp?.where?.(tool.server) if (!where) return false // A cold catalogue is not evidence of removal. if (where.state !== 'on') return true + const config = this.host.mcp?.configurationDigest?.(tool.server) + if (config && config !== held.configDigest) return true if (where.server.failing || where.server.starting) return false if (!where.server.tools.some(t => t.tool === tool.tool)) return true const binding = this.host.mcp?.binding?.(tool) @@ -3137,6 +3139,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const mcp = this.host.mcp if (!mcp || this.closed) return this.actions.withdrawChanged() + void this.actions.retryApproved().catch(error => console.warn('held calls could not be checked after a tool listing', error)) const waiting = this.store.escalations({ status: 'open' }).filter((row) => waitsForTools(row.permission)) if (!waiting.length) return let servers: BotMcpServer[] diff --git a/src/mms/bots/mcp/BotMcp.ts b/src/mms/bots/mcp/BotMcp.ts index f9eb8d772b..18cfd2a3ec 100644 --- a/src/mms/bots/mcp/BotMcp.ts +++ b/src/mms/bots/mcp/BotMcp.ts @@ -100,6 +100,8 @@ export interface BotMcpHost { /** Whether the servers were read since Mousse started: before that, `servers()` says nothing of a server being gone. */ listed?(): boolean inputSchema?(tool: BotMcpTool): unknown + /** Configuration evidence remains available when a server has no successful tool listing. */ + configurationDigest?(serverId: string): string | undefined binding?(tool: BotMcpTool): { serverId: string; tool: string; configDigest: string; schemaDigest: string } | undefined call?: BotMcp['call'] /** The granted tools (`::`) of servers set up now. */ @@ -292,6 +294,10 @@ export class BotMcp implements BotMcpHost { return this.deps.catalog.servers(undefined).find(s => s.installationId === installationOf(tool.server))?.tools.find(t => t.toolName === tool.tool)?.inputSchema } + configurationDigest(serverId: string): string | undefined { + return (this.deps.catalog.servers(undefined).find(s => s.installationId === installationOf(serverId)) as { configDigest?: string } | undefined)?.configDigest + } + binding(tool: BotMcpTool): { serverId: string; tool: string; configDigest: string; schemaDigest: string } | undefined { if (!this.deps.enabled()) return undefined const server = this.deps.catalog.servers(undefined).find(s => s.installationId === installationOf(tool.server)) From 679252e85fbbb46b1c3078381b4256f88eb3a5a1 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:52:25 +0530 Subject: [PATCH 26/84] test(bots): late tool results cannot restore a forgotten call --- tests/bots/botActions.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index f708b2da05..7bcf633360 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1421,3 +1421,23 @@ it('B1 a real configuration change withdraws even while the server listing fails expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) expect(t.calls).toEqual([]) }) + +it('B2 a running call cannot restore its forgotten content when its result arrives', async () => { + const t = await setup(true) + let release!: () => void + const result = new Promise(resolve => { release = resolve }) + vi.spyOn(t.manager, 'callTool').mockImplementationOnce(async () => { await result; return { content: [{ type: 'text', text: 'private delivered receipt' }] } as never }) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const sending = f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await flush() + expect(f.bots.actions.get(a.id)?.status).toBe('running') + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + const forgottenText = f.store.message(a.message_id)?.text + release(); await sending + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'done', exec_args: null, result_json: '{"text":"[forgotten]"}', args_digest: '[forgotten]' }) + expect(f.store.message(a.message_id)?.text).toBe(forgottenText) + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('private delivered receipt') +}) From 76e315534bb05ee2cc753a0eaafd25de40e38327 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:53:25 +0530 Subject: [PATCH 27/84] fix(bots): keep late results from restoring forgotten call content --- src/mms/bots/actions/BotActions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index cf579914e8..7302d41603 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -291,7 +291,7 @@ export class BotActions { transition(id: string, from: string, to: string, result?: BotMcpCallOutcome): boolean { return this.host.store.db.transaction(() => { const moved = this.host.store.run(`UPDATE bot_actions SET status = ?, exec_args = CASE WHEN ? THEN exec_args ELSE NULL END, - result_json = ?, answered_at = CASE WHEN ? = 'open' THEN ? ELSE answered_at END, + result_json = CASE WHEN args_json = '"[forgotten]"' THEN '{"text":"[forgotten]"}' ELSE ? END, answered_at = CASE WHEN ? = 'open' THEN ? ELSE answered_at END, ran_at = CASE WHEN ? IN ('running', 'done') THEN ? ELSE ran_at END WHERE id = ? AND status = ?`, to, pending.has(to) ? 1 : 0, result ? JSON.stringify(boundedActionResult(result)) : null, from, this.host.store.now(), to, this.host.store.now(), id, from) > 0 @@ -303,7 +303,7 @@ export class BotActions { if (moved && !pending.has(to)) { const action = this.get(id)! const row = this.host.store.activation(action.activation_id) - this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) + if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) if (row?.endReason === 'approval') this.host.store.moveActivation(row.id, ['blocked'], 'blocked', { endReason: 'approval_answered' }) this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) } From 6ab4cca11b15b7e1f13aab914aa29dad0e83de2e Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:53:25 +0530 Subject: [PATCH 28/84] fix(bots): defer only unavailable approved calls with intact arguments --- src/mms/bots/actions/BotActions.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 7302d41603..d9afefaeef 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -364,7 +364,10 @@ export class BotActions { } const row = this.valid(action) if (!row) { - if (Date.parse(action.expires_at) > Date.parse(this.host.store.now()) && !this.host.obsolete(action)) return + const current = this.host.store.activation(action.activation_id) + let intact = false + try { intact = Boolean(action.exec_args && action.exec_args.length <= ACTION_MAX_ARGUMENT_CHARS && !containsCredential(JSON.parse(action.exec_args)) && actionDigest(JSON.parse(action.exec_args)) === action.args_digest) } catch { /* Corrupt arguments are never recoverable. */ } + if (Date.parse(action.expires_at) > Date.parse(this.host.store.now()) && intact && current && !this.host.binding(current, JSON.parse(action.target_json)) && !this.host.obsolete(action)) return this.transition(id, 'approved', Date.parse(action.expires_at) <= Date.parse(this.host.store.now()) ? 'expired' : 'withdrawn', { text: 'This changed since you saw it. Nothing was sent; carry on without it.' }) this.finish(action) return From 3d37d86642c38085ce9a07cc32b9cf23b180860b Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:53:50 +0530 Subject: [PATCH 29/84] docs(bots): explain refusal loops forgotten content and pair-bound approval --- docs/bots.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/bots.md b/docs/bots.md index 516fd51d53..cd2b3a9071 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -775,19 +775,19 @@ A held call belongs to one piece of work and one runtime call in its dispatch. M A value is hidden by its key name only where the installed input schema declares that property, following `properties`, array `items`, local `$ref`, every `allOf`, `anyOf` and `oneOf` branch, `if`/`then`/`else`, `dependentSchemas` and indexed `prefixItems`. `$dynamicRef` is treated as unresolved. References have a cycle guard and a 32-step expansion limit. Under a broken, remote or depth-limited schema part, secret-named keys are hidden conservatively throughout that subtree; free-form keys elsewhere remain visible. Invented names in free-form objects stay visible, at every depth. The masked copy represents a hidden value as `{ "$mousse": "hidden", "text": "hidden · will be sent" }`; the exact value is sent unchanged on Send. Literal argument objects with a `$mousse` key are escaped as `{ "$mousse": "literal", "value": }`, recursively. Text saying "hidden · will be sent" is ordinary argument text. `card_json.hasHiddenValues` records whether a hidden value actually exists, for the card to say so beside its buttons. -Argument text is never cut from the review: at most 256,000 characters of serialized argument JSON are accepted in total, and larger calls are refused with a request to send less. Send names the action and the argument digest shown with it. It is bound to the installed server's configuration, the server id and tool name, the tool's schema, the grant revision and the starting device's permission limit. A changed or expired binding needs a fresh review. Until the bridge carries whole large cards, a device's Send is refused when the complete message and its reply envelope exceed its 56 KiB limit: "Open it on the computer to send." Not now still works. +Argument text is never cut from the review: at most 256,000 characters of serialized argument JSON are accepted in total, and larger calls are refused with a request to send less. Send names the action and the argument digest shown with it. It is bound to the installed server's configuration, the server id and tool name, the tool's schema, the held server/tool pair and its permission level, and the starting device's permission limit. Unrelated permissions and a grant revision bump leave that binding intact; removing or changing the pair withdraws its card, and granting it again does not revive the old card. A changed or expired binding needs a fresh review. Until the bridge carries whole large cards, a device's Send is refused when the complete message and its reply envelope exceed its 56 KiB limit: "Open it on the computer to send." Not now still works. Mousse makes the stored call once, without asking the model to recreate it. It commits approval and then the start of execution separately. After a restart, an approved call is checked again before running; a call whose execution had started becomes uncertain and is never repeated. A call that never left Mousse, or Not now, reads "Not sent". When the server answered with an error the row is `failed` but reads "The tool reported an error": the work gets its framed error and is told that the tool may have done part of it, so it must check before trying again. A request sent without an answer becomes `uncertain`, "Couldn't tell if it went through". Settled actions join the same ordered, timed updates as waits, notes and answers. An action that caused the resume leads with its outcome. Its id is kept on the dispatch. Work's stored updates (waits, action outcomes, notes and answers, including work without wait history) count as told only when a dispatch carrying them produces model output or completes. Nonempty model text or thinking, or a model tool-call start, confirms delivery; merely preparing or starting a request does not. A failed, interrupted or replaced dispatch without that evidence leaves its updates pending, including after a time-limit card. A repeated update is acceptable; losing one is not. Carried/read (`read_at` and `applied_at`, plus the dispatch's `workDelivery`) keeps its existing meaning for late taps, Forget and compaction. Confirmation is a separate fact used only to decide what the next prompt carries: `unreadWorkAnswers`, `unreadWorkQuestion` and `unreadWorkNotes` include carried-but-unconfirmed updates without clearing those read markers. New carrying dispatches start with `prompt.workTold = pending`; `BotStore.confirmWorkDelivery` changes only that marker to `output` or `completed`. Reads happen before any confirmation write transaction, so a dispatch with no updates never opens one. A failed confirmation is caught and logged once per dispatch; it never fails the runtime's turn, and the next continuation can carry the update again. Completion of a new dispatch is confirmed explicitly; older rows with no marker also accept a completed stored outcome. Startup recovers a completion written before settlement. A usage retry carries the previous prompt's update ids, so it confirms only what that prompt contained. A database written by master as of #1339 has `workDelivery` for work that waited but no confirmation marker. If its carrying dispatch ended at a wall, a deadline or a turn cap, its notes and answers can be told once more after upgrading (twice is acceptable; losing them is not). Their carried/read behavior is preserved. Earlier databases with no such delivery ids gain no retrospective replay. Approval parks before a time or event wait and has no idle or week exemption. -A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it when the catalogue changes. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting its card or request ends the parked work with a line. A work row stranded on a settled call without its continuation marker ends too. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. +A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An approved call recovered while its listing is unavailable waits for that listing to return. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting its card or request ends the parked work with a line. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. -`/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, card metadata, bot note and stored result with fixed forgotten markers. Its call key, target, status and timestamps stay. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. +`/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, argument digest, card metadata, bot note and stored result with fixed forgotten markers. The owner-message and work-note counters in its card metadata stay, as do its call key, target, status and timestamps. A forgotten row no longer matches an argument digest; the call key still prevents a second execution. A late result cannot restore forgotten content. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. -An owner pause keeps a held card: a pause is not a refusal. Send says "Resume this bot before sending." while paused. A card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline again. +An owner pause keeps a held card: a pause is not a refusal. Send says "Resume this bot before sending." while paused. An approved call recovered after a restart while owner-paused settles as not sent, and its outcome joins unread updates for Resume. A card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline again. -After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a note in the same ordered update list preserves it for the next continuation. A changed argument is a new review, as a changed wake brief is new progress under the wake loop rule: there is no fixed lifetime count of cards. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. +After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a note in the same ordered update list preserves it for the next continuation. Changed arguments may get a new review, but after three declined cards for the same tool in the same work since its owner last wrote, further calls are refused until the owner writes or notes the work; the work is told to say what it needs in its report and wait. This uses the wake loop rule’s count and owner-input fact; expired cards do not count as a no. Any owner row, including a tapped answer to a question, lifts these refusals, as it does for wake loops. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. Hidden argument values of four to eight characters require an adjacent character outside `[A-Za-z0-9_]` only at an edge whose own character is an ASCII letter, digit or underscore. Other edges require no boundary; longer values are replaced wherever they occur. Values shorter than four characters are left alone. Replacement runs in the server's own text before Mousse frames it, including JSON-escaped string echoes and numeric echoes. Credential masking still applies to the result. Transformed echoes (for example encoded, upper-case or truncated values) are not caught by this exact-value replacement. The stored result is capped at 64 KiB in total; images are omitted with a note, never cut into invalid data. Journal key-name masking applies only to work with a held action; other work keeps master's tool input capture. From 0e2baa0d9e5953f8e1b14538b123d868b51b9594 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:54:22 +0530 Subject: [PATCH 30/84] test(bots): expiry and forgetting cannot reset declined-card loops --- tests/bots/botActions.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 7bcf633360..8d15c94f54 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1441,3 +1441,30 @@ it('B2 a running call cannot restore its forgotten content when its result arriv expect(f.store.message(a.message_id)?.text).toBe(forgottenText) expect(JSON.stringify(memory.actions(t.botId))).not.toContain('private delivered receipt') }) + +it('B3 expiry is not a no and forgetting a declined card does not reset the loop', async () => { + const t = await setup(true) + let runtime = t.work + for (let n = 0; n < 3; n++) { + await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: `expires ${n}` }, toolCallId: `expires-${n}`, signal: new AbortController().signal }) + await finish(f, runtime.payload) + const a = f.bots.actions.forWork(t.workId)! + // Move just the card's deadline: advancing three real deadlines would also end the work's week. + f.store.run('UPDATE bot_actions SET expires_at = ? WHERE id = ?', f.store.now(), a.id) + await f.bots.deliverDueReminders(); await flush() + runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + } + for (let n = 0; n < 3; n++) { + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: `declined ${n}` }, toolCallId: `declined-${n}`, signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + await finish(f, runtime.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush(); runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + } + const a = f.bots.actions.forWork(t.workId)! + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'declined call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('said no three times') }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(6) +}) From 3e097d0526761f11747066a8330074ec6b9531e2 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:03:10 +0530 Subject: [PATCH 31/84] test(bots): refusal updates never impersonate owner notes or start reports --- tests/bots/botActions.test.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 8d15c94f54..0e9e2b99dd 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1468,3 +1468,25 @@ it('B3 expiry is not a no and forgetting a declined card does not reset the loop expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('said no three times') }) expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(6) }) + +it.each(['repeat', 'loop'] as const)('R2-1 %s refusal is a Mousse update and never starts an extra report', async reason => { + const t = await setup(true) + let runtime = t.work + for (let n = 0; n < (reason === 'loop' ? 3 : 1); n++) { + await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, ...(reason === 'loop' ? { body: `body ${n}` } : {}) }, toolCallId: `decline-${n}`, signal: new AbortController().signal }) + await finish(f, runtime.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }); await flush() + runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + ;(runtime.prepared as any).modelOutput?.() + } + const dispatches = f.store.dispatches(t.workId).length + const result = await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'refused', signal: new AbortController().signal }) + expect(result.isError).toBe(true) + expect(f.store.pendingWorkNotes(t.workId)).toEqual([]) + await finish(f, runtime.payload, 'completed', { text: 'Finished without sending.' }); await flush() + expect(f.store.dispatches(t.workId)).toHaveLength(dispatches) + expect(f.store.activation(t.workId)?.status).toBe('done') + expect(JSON.stringify(f.store.dispatches(t.workId))).not.toContain('owner added') + expect(f.store.all("SELECT id FROM bot_messages WHERE activation_id = ? AND kind = 'text'", t.workId)).toHaveLength(1) +}) From a7bb9f85d6f6f943860acc8b9b5f051e72b0dba0 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:03:55 +0530 Subject: [PATCH 32/84] fix(bots): carry refusals as confirmed Mousse updates instead of owner notes --- src/mms/bots/actions/BotActions.ts | 4 +--- src/mms/bots/activation/BotEngine.ts | 6 ++++++ src/mms/bots/store/BotStore.ts | 17 ++++++++++++++++- tests/bots/botActions.test.ts | 6 +++--- tests/bots/botContinuationMatrix.test.ts | 3 ++- 5 files changed, 28 insertions(+), 8 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index d9afefaeef..d6cd81c62c 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -247,9 +247,7 @@ export class BotActions { return this.host.store.ownerLastWroteSeq(action.bot_id) > Number(card.ownerSeq ?? 0) || note > Number(card.noteSeq ?? 0) } private refuse(row: BotActivationRow, action: ActionRow, text: string): ToolOutcome { - // A lost tool reply must not lose the refusal: use the same ordered notes as other updates. - if (!this.host.store.get('SELECT 1 FROM bot_work_notes WHERE activation_id = ? AND from_message = ? AND text = ?', row.id, action.message_id, text)) - this.host.store.addWorkNote(row.id, row.botId, text, action.message_id) + this.host.store.recordWorkRefusal(row.id, row.botId, `${action.id}:${text.startsWith('Your owner declined') ? 'repeat' : 'loop'}`, text) return { text, isError: true } } hold(row: BotActivationRow, dispatch: string, tool: BotMcpTool, args: Record, toolCallId?: string): ToolOutcome { diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 218bf6d770..254cc80673 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -5317,6 +5317,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } const waits = current.trigger.kind === 'work' ? this.store.unreadWorkWaits(current.id) : [] const actions = current.trigger.kind === 'work' ? this.store.unreadWorkActions(current.id) : [] + const refusals = this.workRefusalUpdates(current.id) const actionCaused = current.endReason === 'approval_answered' ? actions.at(-1) : undefined const waited = waits.length > 0 const n = this.store.nextDispatchN(row.id) @@ -5332,6 +5333,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const deliveryQuestion = input.usageRetry ? undefined : durableWork ? this.store.unreadWorkQuestion(current.id) : question const answered = deliveryQuestion?.status === 'answered' || deliveryQuestion?.status === 'defaulted' ? this.workAnswerOf(deliveryQuestion) : undefined const workEvents: WorkContinuationEvent[] | undefined = durableWork ? [ + ...refusals, ...actions.map(action => ({ at: (action.status === 'declined' ? action.answered_at : action.ran_at) ?? action.answered_at ?? current.createdAt, text: actionContinuation(action), actionId: action.id })), ...waits.map(wait => ({ at: wait.dueAt, text: workWaitInput(wait, clockTime) })), ...answers.map(answer => ({ at: answer.answeredAt ?? answer.createdAt, answer })), @@ -5342,10 +5344,12 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { if (answered) this.store.markAnswerSent(deliveryQuestion!.id, n, answered, !readAtStart) // A usage retry repeats the previous text, so only its carried ids may be confirmed by that retry. const delivery = input.usageRetry && previous ? { + ...(previous.prompt.workRefusalIds ? { workRefusalIds: previous.prompt.workRefusalIds } : {}), ...(previous.prompt.workActionIds ? { workActionIds: previous.prompt.workActionIds } : {}), ...(previous.prompt.workWaitIds ? { workWaitIds: previous.prompt.workWaitIds } : {}), ...(previous.prompt.workDelivery ? { workDelivery: previous.prompt.workDelivery } : {}) } : { + ...(refusals.length ? { workRefusalIds: refusals.map(event => event.id) } : {}), ...(actions.length ? { workActionIds: actions.map(action => action.id) } : {}), ...(waits.length ? { workWaitIds: waits.map(wait => wait.id) } : {}), ...(durableWork ? { workDelivery: { answers: answers.map(answer => answer.id), notes: notes?.ids ?? [], ...(answered ? { question: deliveryQuestion!.id } : {}) } } : {}) @@ -6416,6 +6420,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } /** Confirmation is advisory: a failed write means repeat the update, never fail the runtime's turn. */ + private workRefusalUpdates(workId: string) { return this.store.unreadWorkRefusals(workId) } + private confirmWorkDelivery(activationId: string, n: number, why: 'output' | 'completed'): void { try { this.store.confirmWorkDelivery(activationId, n, why) } catch (error) { diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index 8e760b8df1..8b6a7ad286 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -796,6 +796,7 @@ export interface BotDispatchRow { workTold?: 'pending' | 'output' | 'completed' workWaitIds?: string[] workActionIds?: string[] + workRefusalIds?: string[] /** Carried ids for replay; existing read/applied markers remain independent of confirmation. */ workDelivery?: { answers: string[]; notes: number[]; question?: string } } @@ -890,7 +891,7 @@ export interface BotCountersRow { const WORK_TOLD = "(COALESCE(json_extract(d.prompt_json, '$.workTold'), '') IN ('output', 'completed') OR (json_extract(d.prompt_json, '$.workTold') IS NULL AND d.outcome IS 'completed'))" const hasWorkUpdates = (prompt: BotDispatchRow['prompt']): boolean => Boolean( - prompt.workActionIds?.length || prompt.workWaitIds?.length || prompt.workDelivery?.notes.length || + prompt.workRefusalIds?.length || prompt.workActionIds?.length || prompt.workWaitIds?.length || prompt.workDelivery?.notes.length || prompt.workDelivery?.answers.length || prompt.workDelivery?.question ) @@ -2004,6 +2005,20 @@ export class BotStore { ORDER BY COALESCE(a.ran_at, a.answered_at, a.created_at), a.rowid`, workId) as unknown as ActionRow[] } + recordWorkRefusal(workId: string, botId: string, id: string, text: string): void { + this.run('INSERT OR IGNORE INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?)', botId, + `cursor:action-refusal:${workId}:${id}`, JSON.stringify({ at: this.now(), text })) + } + + /** Mousse updates are neither owner notes nor a reason to start another turn. */ + unreadWorkRefusals(workId: string): Array<{ id: string; at: string; text: string }> { + const prefix = `cursor:action-refusal:${workId}:` + return this.all(`SELECT s.key, s.value FROM bot_memory_state s WHERE substr(s.key, 1, ?) = ? + AND NOT EXISTS (SELECT 1 FROM bot_dispatches d, json_each(d.prompt_json, '$.workRefusalIds') told + WHERE d.activation_id = ? AND ${WORK_TOLD} AND told.value = s.key) ORDER BY s.rowid`, prefix.length, prefix, workId) + .map(row => ({ id: String(row.key), ...JSON.parse(String(row.value)) as { at: string; text: string } })) + } + /** Confirmation controls replay only; existing carried/read markers are not changed here. */ confirmWorkDelivery(activationId: string, n: number, why: 'output' | 'completed'): void { const needsConfirmation = (dispatch: BotDispatchRow | undefined): boolean => Boolean(dispatch && dispatch.startedAt !== null && diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 0e9e2b99dd..5df9ab8b44 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1230,14 +1230,14 @@ it('a repeat refusal joins unread work updates without another action or card', const next = await start(f, t.workId, 2) ;(next.prepared as any).modelOutput?.() await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'repeat-refused', signal: new AbortController().signal }) - expect(f.store.unreadWorkNotes(t.workId).map(n => n.text).join(' ')).toContain('Do not ask again') + expect(f.store.unreadWorkRefusals(t.workId).map(n => n.text).join(' ')).toContain('Do not ask again') expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) await finish(f, next.payload, 'failed', { outcome: { error: 'network_error' } }) await (f.bots as any).continueWith(t.workId, [f.store.activation(t.workId)!.status], { network: true }) expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('Do not ask again') const receiving = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) ;(receiving.prepared as any).modelOutput?.() - expect(f.store.unreadWorkNotes(t.workId)).toEqual([]) + expect(f.store.unreadWorkRefusals(t.workId)).toEqual([]) }) it('switch off keeps repeated and differing calls direct without cards or refusal notes', async () => { @@ -1341,7 +1341,7 @@ it.each([true, false])('B3 three declined cards stop changed calls until owner i } expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(on ? 3 : 0) if (!on) { expect(t.calls).toHaveLength(20); return } - expect(f.store.unreadWorkNotes(t.workId).map(n => n.text).join(' ')).toContain('said no three times') + expect(f.store.unreadWorkRefusals(t.workId).map(n => n.text).join(' ')).toContain('said no three times') expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__other', args: t.args, toolCallId: 'another-tool', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) await finish(f, runtime.payload) const other = f.bots.actions.forWork(t.workId)! diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 91d422b027..48709d4160 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -97,7 +97,8 @@ it.each([false, true].flatMap(hasWaited => [ 'Your owner said no three times. Say what you need in your report and wait for them to write.' ].map(refusal => ({ hasWaited, refusal }))))('refusal joins ordered updates with wait history=$hasWaited: $refusal', ({ hasWaited, refusal }) => { const input = matrixInput('turn cap', 'note and answer', hasWaited) - input.workEvents = [...eventsOf(input), { at: '2026-11-07T09:04:00Z', text: refusal }] + f.store.recordWorkRefusal(ROW.id, ROW.botId, 'matrix-refusal', refusal) + input.workEvents = [...eventsOf(input), ...(f.bots as any).workRefusalUpdates(ROW.id)] const prompt: string = (f.bots as any).continuationPrompt(ROW, input) expect(prompt.split(refusal)).toHaveLength(2) expect(prompt.indexOf(NOTE)).toBeLessThan(prompt.indexOf(refusal)) From 5f0d4b856c00133a1e93059895a6db7d0f2f3b96 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:04:38 +0530 Subject: [PATCH 33/84] test(bots): Forget continues a card and fully releases a forgotten request --- tests/bots/botActions.test.ts | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 5df9ab8b44..4278b2e456 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1,3 +1,4 @@ +import { existsSync, mkdirSync } from 'node:fs' import { afterEach, expect, it, vi } from 'vitest' import { remoteBotMethods } from '../../src/mms/bridge/remote/RemoteBots' import { setDiagSink } from '../../src/mms/log/diag' @@ -1488,5 +1489,32 @@ it.each(['repeat', 'loop'] as const)('R2-1 %s refusal is a Mousse update and nev expect(f.store.dispatches(t.workId)).toHaveLength(dispatches) expect(f.store.activation(t.workId)?.status).toBe('done') expect(JSON.stringify(f.store.dispatches(t.workId))).not.toContain('owner added') - expect(f.store.all("SELECT id FROM bot_messages WHERE activation_id = ? AND kind = 'text'", t.workId)).toHaveLength(1) + expect(f.store.all("SELECT id FROM bot_messages WHERE activation_id = ? AND kind = 'run_report'", t.workId)).toHaveLength(1) +}) + + +it.each(['card', 'request'] as const)('R2-2 forgetting the %s uses the appropriate continuation or normal end', async which => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const scratch = `${f.base}/forget-scratch`; mkdirSync(scratch) + f.store.run('UPDATE bot_activations SET scratch = ? WHERE id = ?', scratch, t.workId) + const browserEnd = vi.fn(); const progressEnd = vi.fn() + f.host.browser = { activationEnded: browserEnd } as never + f.host.progress = { finishProgress: progressEnd } as never + const id = which === 'card' ? a.message_id : String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }); await flush() + if (which === 'card') { + expect(f.store.activation(t.workId)?.status).toBe('running') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('withdrawn') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).not.toContain('request was forgotten') + } else { + expect(f.store.activation(t.workId)?.status).toBe('failed') + expect(f.journal.some(j => j.kind === 'run_end' && j.activationId === t.workId)).toBe(true) + expect(existsSync(scratch)).toBe(false) + expect(browserEnd).toHaveBeenCalledWith({ botId: t.botId, activationId: t.workId }) + expect(progressEnd).toHaveBeenCalledWith(t.botId, t.workId, false) + } }) From e5e4964f71ec93794b4c215712d380a60ea6bcb6 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:05:07 +0530 Subject: [PATCH 34/84] test(bots): chat approvals preserve cards and every grant removal withdraws them --- tests/bots/botActions.test.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 4278b2e456..2742c58325 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1518,3 +1518,28 @@ it.each(['card', 'request'] as const)('R2-2 forgetting the %s uses the appropria expect(progressEnd).toHaveBeenCalledWith(t.botId, t.workId, false) } }) + +it('R2-3 allowing use your threads from chat preserves a sendable card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.service.chatSend({ botId: t.botId, text: 'Use my threads', clientRequestId: 'allow-threads-with-card' }) + const chat = f.store.laneActivations(t.botId, 'chat', ['running'])[0]! + const asking = await start(f, chat.id) + asking.prepared.authority.escalate!({ permission: { tool: 'threads' }, reason: 'Help in threads' }) + await f.bots.service.answer(t.botId, f.store.openAsks(t.botId)[0].id, 'allow') + await finish(f, asking.payload) + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + expect(t.calls).toEqual([t.args]) +}) + +it('R2-3 every grant approval checks removal of the held pair in the grant transaction', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const grant = f.store.activeGrant(t.botId)! + const removed = { ...grant.manifest, mcp: [] } + f.store.approve(t.botId, botManifestDigest(removed), removed) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) +}) From 33ae3a7a7a30c1e5f0c03aef54ed04903b22a4e5 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:05:38 +0530 Subject: [PATCH 35/84] fix(bots): continue forgotten cards and end forgotten requests through the engine --- src/mms/bots/actions/BotActions.ts | 5 +++-- src/mms/bots/activation/BotEngine.ts | 4 ++++ tests/bots/botActions.test.ts | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index d6cd81c62c..9547a72980 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -179,6 +179,7 @@ interface Host { publish(messageId: string): void ownerAnswered(row: BotActivationRow): void held(): void + forgottenRequest(row: BotActivationRow): void execute(row: BotActivationRow, tool: BotMcpTool, args: Record): Promise } const pending = new Set(['open', 'approved', 'running']) @@ -199,8 +200,8 @@ export class BotActions { this.forgetText(botId, String(action.id)) if (!pending) continue const row = host.store.activation(String(action.activation_id)) - if (row && host.store.moveActivation(row.id, ['blocked'], 'cancelled', { endReason: 'forgotten', result: 'This work ended because its request was forgotten.' })) - host.post(row, `bm_${action.id}_forgotten`, 'This work ended because its request was forgotten.') + if (row && row.trigger.kind === 'work' && row.trigger.replyTo === messageId) host.forgottenRequest(row) + else host.store.db.afterCommit(() => this.finish(action as unknown as ActionRow)) } } }) diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 254cc80673..74579cfdb4 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -615,6 +615,10 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { this.store.db.statement(`INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?) ON CONFLICT(bot_id, key) DO UPDATE SET value = excluded.value`).run(row.botId, `cursor:action-owner:${row.id}`, String(last?.n ?? 0)) }, held: () => { this.watchMcp(); this.armDue() }, + forgottenRequest: row => { + const ended = this.endWaitingInTx(row, 'request_gone', 'This work ended because its request was forgotten.') + if (ended) this.store.db.afterCommit(() => this.afterEnd(ended)) + }, schema: (tool) => this.host.mcp?.inputSchema?.(tool), binding: (row, tool) => { const pair = this.actionPair(row, tool) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 2742c58325..a22900bf98 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1088,7 +1088,7 @@ it.each(['card', 'request'] as const)('Forget of the %s withdraws exact argument f.bots.afterForget() await flush() expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) - expect(f.store.activation(t.workId)?.status).toBe('cancelled') + expect(f.store.activation(t.workId)?.status).toBe(which === 'card' ? 'running' : 'failed') }) it('forget history removes settled text and preserves the call key that prevents another execution', async () => { From c1141d462eaf1b800810cac4dc0527ff16980dca Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:05:38 +0530 Subject: [PATCH 36/84] test(bots): expiry cannot overtake a timely accepted Send --- tests/bots/botActions.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index a22900bf98..8bb5db8691 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1543,3 +1543,21 @@ it('R2-3 every grant approval checks removal of the held pair in the grant trans f.store.approve(t.botId, botManifestDigest(removed), removed) expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) }) + +it('R2-5 a timely Send remains running when the deadline passes', async () => { + const t = await setup(true) + let release!: () => void + const waiting = new Promise(resolve => { release = resolve }) + vi.spyOn(t.manager, 'callTool').mockImplementationOnce(async () => { await waiting; return { content: [{ type: 'text', text: 'delivered' }] } as never }) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.clock.now = Date.parse(a.expires_at) - 1000 + const sending = f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await flush() + f.clock.now += 2000 + await f.bots.deliverDueReminders() + expect(f.bots.actions.get(a.id)?.status).toBe('running') + expect(() => f.bots.actions.assertRunning(a.id)).not.toThrow() + release(); await sending + expect(f.bots.actions.get(a.id)?.status).toBe('done') +}) From 295ffcb4f7c3ab2435b880175f4fae7908b302f5 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:05:54 +0530 Subject: [PATCH 37/84] test(bots): expired cards count toward the three unsent-card rule --- tests/bots/botActions.test.ts | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 8bb5db8691..da0e6c0694 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1338,11 +1338,11 @@ it.each([true, false])('B3 three declined cards stop changed calls until owner i const a = f.bots.actions.forWork(t.workId)! await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) await flush(); runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) - } else expect(outcome).toMatchObject({ isError: true, text: expect.stringContaining('said no three times') }) + } else expect(outcome).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) } expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(on ? 3 : 0) if (!on) { expect(t.calls).toHaveLength(20); return } - expect(f.store.unreadWorkRefusals(t.workId).map(n => n.text).join(' ')).toContain('said no three times') + expect(f.store.unreadWorkRefusals(t.workId).map(n => n.text).join(' ')).toContain('had three cards for this tool that were not sent') expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__other', args: t.args, toolCallId: 'another-tool', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) await finish(f, runtime.payload) const other = f.bots.actions.forWork(t.workId)! @@ -1443,7 +1443,7 @@ it('B2 a running call cannot restore its forgotten content when its result arriv expect(JSON.stringify(memory.actions(t.botId))).not.toContain('private delivered receipt') }) -it('B3 expiry is not a no and forgetting a declined card does not reset the loop', async () => { +it('R2-4 three expired cards refuse further calls without claiming the owner declined', async () => { const t = await setup(true) let runtime = t.work for (let n = 0; n < 3; n++) { @@ -1455,19 +1455,12 @@ it('B3 expiry is not a no and forgetting a declined card does not reset the loop await f.bots.deliverDueReminders(); await flush() runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) } - for (let n = 0; n < 3; n++) { - expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: `declined ${n}` }, toolCallId: `declined-${n}`, signal: new AbortController().signal })).not.toMatchObject({ isError: true }) - await finish(f, runtime.payload) - const a = f.bots.actions.forWork(t.workId)! - await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) - await flush(); runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) - } const a = f.bots.actions.forWork(t.workId)! const memory = new BotMemoryStore({ db: f.store.db }) const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'declined call' })! memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) - expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('said no three times') }) - expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(6) + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(3) }) it.each(['repeat', 'loop'] as const)('R2-1 %s refusal is a Mousse update and never starts an extra report', async reason => { From 4bffd93bf387b95e318526ea4e1a2eceb35f2ebd Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:06:34 +0530 Subject: [PATCH 38/84] test(bots): answer the chat permission after its message finishes --- tests/bots/botActions.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index da0e6c0694..f0d28194de 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1520,8 +1520,8 @@ it('R2-3 allowing use your threads from chat preserves a sendable card', async ( const chat = f.store.laneActivations(t.botId, 'chat', ['running'])[0]! const asking = await start(f, chat.id) asking.prepared.authority.escalate!({ permission: { tool: 'threads' }, reason: 'Help in threads' }) - await f.bots.service.answer(t.botId, f.store.openAsks(t.botId)[0].id, 'allow') await finish(f, asking.payload) + await f.bots.service.answer(t.botId, f.store.openAsks(t.botId)[0].id, 'allow') expect(f.bots.actions.get(a.id)?.status).toBe('open') await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) expect(t.calls).toEqual([t.args]) From a9a3aa4668508ed045615c42be025ce11d79d3a0 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:06:34 +0530 Subject: [PATCH 39/84] fix(bots): check held pairs inside every grant approval --- src/mms/bots/actions/BotActions.ts | 1 + src/mms/bots/actions/lifecycle.ts | 1 + src/mms/bots/store/BotStore.ts | 1 + 3 files changed, 3 insertions(+) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 9547a72980..271d35c6d2 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -190,6 +190,7 @@ export class BotActions { constructor(private readonly host: Host) { registerHeldCalls(host.store.db, { endWork: id => this.withdrawWork(id), + grantChanged: () => this.withdrawChanged(), forgetMessage: (botId, messageId) => { if (!host.enabled()) return const ids = host.store.all(`SELECT a.* FROM bot_actions a JOIN bot_activations w ON w.id = a.activation_id diff --git a/src/mms/bots/actions/lifecycle.ts b/src/mms/bots/actions/lifecycle.ts index 807c61ae0e..e4d204912b 100644 --- a/src/mms/bots/actions/lifecycle.ts +++ b/src/mms/bots/actions/lifecycle.ts @@ -3,6 +3,7 @@ import type { BotStoreTx } from '../store/BotStore' /** Per open database, never persisted: a disabled feature installs no active behavior. */ export interface HeldCallLifecycle { endWork(id: string): void + grantChanged(botId: string): void forgetMessage(botId: string, messageId: string): void } const lifecycles = new WeakMap() diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index 8b6a7ad286..c6d4585456 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1166,6 +1166,7 @@ export class BotStore { const at = this.now() this.run('UPDATE bot_grants SET revoked_at = ? WHERE bot_id = ? AND revoked_at IS NULL', at, botId) this.run('INSERT INTO bot_grants(bot_id, digest, manifest_json, approved_at) VALUES(?, ?, ?, ?)', botId, digest, JSON.stringify(manifest), at) + heldCalls(this.db)?.grantChanged(botId) return { botId, digest, manifest, approvedAt: at } }) } From 67901a087836bbef6d560f84bca476bfb18d930a Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:06:47 +0530 Subject: [PATCH 40/84] test(bots): existing held rows settle after asks-first is disabled --- tests/bots/botActions.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index f0d28194de..165a509faa 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1554,3 +1554,18 @@ it('R2-5 a timely Send remains running when the deadline passes', async () => { release(); await sending expect(f.bots.actions.get(a.id)?.status).toBe('done') }) + +it.each(['stop', 'expiry', 'forget'] as const)('R2-6 existing rows still settle after switch-off on %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.host.settings!.get().experimental.botAsksFirst = false + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (path === 'expiry') { f.clock.now = Date.parse(a.expires_at); f.timers.at(-1)!.fn(); await flush() } + if (path === 'forget') { + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: path === 'expiry' ? 'expired' : 'withdrawn', exec_args: null }) +}) From 3c9b6cd2e81fa85e60f5833d26a31f39ad5b2aa3 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:07:17 +0530 Subject: [PATCH 41/84] fix(bots): expire only unaccepted calls and honor timely Send --- src/mms/bots/actions/BotActions.ts | 6 +++--- src/mms/bots/activation/BotEngine.ts | 2 +- tests/bots/botActions.test.ts | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 271d35c6d2..601b78405c 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -222,7 +222,7 @@ export class BotActions { } expireDue(): void { if (!this.host.enabled()) return - for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved') AND expires_at <= ?", this.host.store.now())) { + for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status = 'open' AND expires_at <= ?", this.host.store.now())) { if (this.transition(String(a.id), String(a.status), 'expired', { text: 'This call expired. Carry on without it; do not try the same call again without a new reason.' })) this.finish(a as unknown as ActionRow) } } @@ -313,7 +313,7 @@ export class BotActions { private valid(action: ActionRow): BotActivationRow | undefined { const row = this.host.store.activation(action.activation_id) - if (!row || !action.exec_args || action.exec_args.length > ACTION_MAX_ARGUMENT_CHARS || Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) return undefined + if (!row || !action.exec_args || action.exec_args.length > ACTION_MAX_ARGUMENT_CHARS || (action.status === 'open' && Date.parse(action.expires_at) <= Date.parse(this.host.store.now()))) return undefined try { const args: unknown = JSON.parse(action.exec_args) if (containsCredential(args) || actionDigest(args) !== action.args_digest) return undefined @@ -333,7 +333,7 @@ export class BotActions { if (!this.host.enabled()) throw new BotActionChanged('Asks first is not available while its switch is off.') await this.host.refresh() const action = this.get(input.actionId) - if (action && ['open', 'approved'].includes(action.status) && Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) { + if (action && action.status === 'open' && Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) { this.expireDue() throw new BotActionChanged('This call expired. Nothing was sent.') } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 74579cfdb4..224ceed14b 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -8619,7 +8619,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const sources: Array<() => number | undefined> = [ () => { if (!botAsksFirst(this.host.settings?.get())) return undefined - const row = this.store.get("SELECT MIN(expires_at) AS at FROM bot_actions WHERE status IN ('open', 'approved') AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null) + const row = this.store.get("SELECT MIN(expires_at) AS at FROM bot_actions WHERE status = 'open' AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null) return row?.at ? Date.parse(String(row.at)) : undefined }, () => this.tellings.next(botId), diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 165a509faa..cbb87d419c 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -183,7 +183,7 @@ it('reload and internet-back continuations cannot pass an open card', async () = expect(f.store.lastMainDispatch(t.workId)?.n).toBe(1) expect(t.calls).toEqual([]) }) -it.each(['approved', 'running'] as const)('restart clears arguments from an expired %s row', async state => { +it.each(['approved', 'running'] as const)('restart preserves timely approval and settles a %s row', async state => { const t = await setup(true) await t.call() await finish(f, t.work.payload) @@ -192,8 +192,8 @@ it.each(['approved', 'running'] as const)('restart clears arguments from an expi if (state === 'running') f.bots.actions.transition(a.id, 'approved', 'running') f.clock.now += 48 * 3600_000 + 1000 await f.bots.actions.reconcile() - expect(t.calls).toEqual([]) - expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'expired' : 'uncertain', exec_args: null }) + expect(t.calls).toEqual(state === 'approved' ? [t.args] : []) + expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'done' : 'uncertain', exec_args: null }) }) it('an expired Send is refused', async () => { const t = await setup(true) From 1fefc4b88bd93657d0b937a912d181a061d97786 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:07:58 +0530 Subject: [PATCH 42/84] test(bots): work cursor state is private and removed at work end --- tests/bots/botActions.test.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index cbb87d419c..af682b7f25 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1,4 +1,5 @@ -import { existsSync, mkdirSync } from 'node:fs' +import { createBotMemoryAdmin } from '../../src/mms/bots/memory/admin' +import { existsSync, mkdirSync, readFileSync } from 'node:fs' import { afterEach, expect, it, vi } from 'vitest' import { remoteBotMethods } from '../../src/mms/bridge/remote/RemoteBots' import { setDiagSink } from '../../src/mms/log/diag' @@ -1569,3 +1570,22 @@ it.each(['stop', 'expiry', 'forget'] as const)('R2-6 existing rows still settle } expect(f.bots.actions.get(a.id)).toMatchObject({ status: path === 'expiry' ? 'expired' : 'withdrawn', exec_args: null }) }) + + +it.each(['stop', 'complete', 'purge'] as const)('R2-7 action cursors stay out of export and disappear on %s', async end => { + const t = await setup(true) + f.bots.noteWork(t.botId, t.workId, 'Owner note') + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }); await flush() + const keys = [`cursor:action-note:${t.workId}`, `cursor:action-owner:${t.workId}`] + expect(f.store.all('SELECT key FROM bot_memory_state WHERE key IN (?, ?)', ...keys)).toHaveLength(2) + const memory = new BotMemoryStore({ db: f.store.db }) + const exported = await createBotMemoryAdmin({ store: memory }).export(t.botId, f.base) + const text = exported.files.map(file => readFileSync(file, 'utf8')).join(' ') + for (const key of keys) expect(text).not.toContain(key) + if (end === 'purge') memory.purge(t.botId) + else if (end === 'stop') await f.bots.stopWork(t.botId, t.workId) + else { const runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n); (runtime.prepared as any).modelOutput?.(); await finish(f, runtime.payload) } + expect(f.store.all('SELECT key FROM bot_memory_state WHERE key IN (?, ?)', ...keys)).toEqual([]) +}) From e0f751801a6111870b2b93420b1efd30082da287 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:08:49 +0530 Subject: [PATCH 43/84] fix(bots): count expired cards toward the unsent-card loop rule --- src/mms/bots/actions/BotActions.ts | 4 ++-- tests/bots/botContinuationMatrix.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 601b78405c..e46bf91f81 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -258,10 +258,10 @@ export class BotActions { const existing = this.host.store.get('SELECT id FROM bot_actions WHERE call_key = ?', callKey) if (existing) return { text: 'This call is held for your owner. End your turn now.' } if (pending.has(this.forWork(row.id)?.status ?? '')) return { text: 'A call is already held for your owner. End your turn now.', isError: true } - const declined = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND status = 'declined' ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool })) as unknown as ActionRow[] + const declined = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool })) as unknown as ActionRow[] const unanswered = declined.filter(action => !this.ownerWroteAfter(action)) if (unanswered.length >= MAX_SAME_WAKES) - return this.refuse(row, unanswered[0], 'Your owner said no three times. Say what you need in your report and wait for them to write.') + return this.refuse(row, unanswered[0], 'You had three cards for this tool that were not sent. Say what you need in your report and wait for your owner to write.') const digest = actionDigest(args) const refused = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND args_digest = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), digest)[0] if (refused && !this.ownerWroteAfter(refused as unknown as ActionRow)) diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 48709d4160..20fb068ab9 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -94,7 +94,7 @@ it.each(['question answer', 'note and answer'] as const)('N3 a live wait plus a it.each([false, true].flatMap(hasWaited => [ 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.', - 'Your owner said no three times. Say what you need in your report and wait for them to write.' + 'You had three cards for this tool that were not sent. Say what you need in your report and wait for your owner to write.' ].map(refusal => ({ hasWaited, refusal }))))('refusal joins ordered updates with wait history=$hasWaited: $refusal', ({ hasWaited, refusal }) => { const input = matrixInput('turn cap', 'note and answer', hasWaited) f.store.recordWorkRefusal(ROW.id, ROW.botId, 'matrix-refusal', refusal) From 22ccba4210838f36f5c05ed96a2fb14efc55c4cf Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:08:49 +0530 Subject: [PATCH 44/84] fix(bots): settle existing held calls independently of the new-hold switch --- src/mms/bots/actions/BotActions.ts | 9 +-------- src/mms/bots/activation/BotEngine.ts | 13 ++++++------- tests/bots/botActions.test.ts | 13 ++----------- 3 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index e46bf91f81..f524675d72 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -192,7 +192,6 @@ export class BotActions { endWork: id => this.withdrawWork(id), grantChanged: () => this.withdrawChanged(), forgetMessage: (botId, messageId) => { - if (!host.enabled()) return const ids = host.store.all(`SELECT a.* FROM bot_actions a JOIN bot_activations w ON w.id = a.activation_id WHERE a.bot_id = ? AND (a.message_id = ? OR json_extract(w.trigger_json, '$.replyTo') = ?)`, botId, messageId, messageId) for (const action of ids) { @@ -209,25 +208,21 @@ export class BotActions { } /** Erase call content without erasing owner intervention facts or the run-once key. */ forgetText(botId: string, actionId?: string): void { - if (!this.host.enabled()) return this.host.store.run(`UPDATE bot_actions SET args_json = ?, args_digest = '[forgotten]', card_json = json_object('text', '[forgotten]', 'ownerSeq', COALESCE(json_extract(card_json, '$.ownerSeq'), 0), 'noteSeq', COALESCE(json_extract(card_json, '$.noteSeq'), 0)), bot_note = ?, result_json = ? WHERE bot_id = ? AND (? IS NULL OR id = ?)`, '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId, actionId ?? null, actionId ?? null) } withdrawWork(id: string): void { - if (!this.host.enabled()) return for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND status IN ('open', 'approved')", id)) this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'This work ended. Nothing was sent.' }) } expireDue(): void { - if (!this.host.enabled()) return for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status = 'open' AND expires_at <= ?", this.host.store.now())) { if (this.transition(String(a.id), String(a.status), 'expired', { text: 'This call expired. Carry on without it; do not try the same call again without a new reason.' })) this.finish(a as unknown as ActionRow) } } withdrawChanged(): void { - if (!this.host.enabled()) return for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved')")) { if (this.host.obsolete(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.host.store.db.afterCommit(() => this.finish(a as unknown as ActionRow)) } @@ -253,6 +248,7 @@ export class BotActions { return { text, isError: true } } hold(row: BotActivationRow, dispatch: string, tool: BotMcpTool, args: Record, toolCallId?: string): ToolOutcome { + if (!this.host.enabled()) return { text: 'Asks first is off.', isError: true } if (!toolCallId) return { text: 'This call cannot be held without its call id. Carry on without it.', isError: true } const callKey = JSON.stringify([row.id, dispatch, toolCallId]) const existing = this.host.store.get('SELECT id FROM bot_actions WHERE call_key = ?', callKey) @@ -330,7 +326,6 @@ export class BotActions { if (!action || action.status !== 'running' || !this.valid(action)) throw changed() } async answer(input: { actionId: string; digest: string; answer: 'send' | 'not_now' }): Promise<{ status: string }> { - if (!this.host.enabled()) throw new BotActionChanged('Asks first is not available while its switch is off.') await this.host.refresh() const action = this.get(input.actionId) if (action && action.status === 'open' && Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) { @@ -392,12 +387,10 @@ export class BotActions { this.host.settled(row) } async retryApproved(): Promise { - if (!this.host.enabled()) return for (const action of this.host.store.all("SELECT id FROM bot_actions WHERE status = 'approved'")) await this.runApproved(String(action.id)) } async reconcile(): Promise { - if (!this.host.enabled()) return this.expireDue() const interrupted = this.host.store.all("SELECT id FROM bot_actions WHERE status IN ('running', 'approved')") await this.host.refresh() diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 224ceed14b..d666a8d32b 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -2249,14 +2249,14 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } private approvalPending(id: string): boolean { - return botAsksFirst(this.host.settings?.get()) && ['open', 'approved', 'running'].includes(this.actions.forWork(id)?.status ?? '') + return ['open', 'approved', 'running'].includes(this.actions.forWork(id)?.status ?? '') } private readonly workWaitLookups: WorkWaitLookups = { store: () => this.store } private readonly workWaitFacts: WorkWaitFacts = { approvalReady: (row) => this.store.lastMainDispatch(row.id)?.endedAt !== null && !this.live.has(row.id), - approvalExists: (row) => { const action = this.actions.forWork(row.id); return Boolean(action && (!botAsksFirst(this.host.settings?.get()) || row.endReason === 'approval_answered' || ['open', 'approved', 'running'].includes(action.status))) }, + approvalExists: (row) => { const action = this.actions.forWork(row.id); return Boolean(action && (row.endReason === 'approval_answered' || ['open', 'approved', 'running'].includes(action.status))) }, timerExists: (row) => { const wait = this.store.workWait(row.id); return Boolean(wait && wait.status !== 'cancelled') }, usageResumable: (row) => this.usageResumable(row), questionExists: (row) => Boolean(this.store.workQuestion(row.id)), @@ -4833,7 +4833,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } else if (openWalls.length) { // The chat turn asked (`escalate`): it waits for the owner with every card on its message. this.store.moveActivation(row.id, ['running'], 'waiting_grant', { endReason: 'wall', ...(text !== undefined ? { result: text } : {}) }) - } else if (botAsksFirst(this.host.settings?.get()) && this.actions.pendingInTurn(row.id, main.n) && this.askedIn.get(row.id) === main.n) { + } else if (this.actions.pendingInTurn(row.id, main.n) && this.askedIn.get(row.id) === main.n) { if (!this.park(row, 'approval', ['running'], this.approvalPending(row.id) ? 'approval' : 'approval_answered')) return undefined } else if (this.store.workWait(row.id)?.status === 'waiting') { if (!this.park(row, 'waiting', ['running'])) return undefined @@ -7444,7 +7444,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { await this.endAll([...this.store.laneActivations(botId, 'chat', [...NOT_ENDED]), ...waiting], 'stopped', () => { this.store.withdrawAsks(botId) this.store.withdrawQuestions(botId) - if (botAsksFirst(this.host.settings?.get())) this.store.run("DELETE FROM bot_messages WHERE bot_id = ? AND id IN (SELECT message_id FROM bot_actions WHERE bot_id = ?)", botId, botId) + this.store.run("DELETE FROM bot_messages WHERE bot_id = ? AND id IN (SELECT message_id FROM bot_actions WHERE bot_id = ?)", botId, botId) }) // Deleted once the turns stopped, so a turn ending meanwhile adds no row to the cleared chat. this.store.deleteMessages(botId) @@ -7994,7 +7994,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { // The note keeps the owner's message it came from (the chat turn's), so a forget of that message reaches it. if (from && this.store.activation(from) && ownerChatTurn(this.store.activation(from)!)) this.resetWorkWaitChain(workId) this.store.addWorkNote(workId, botId, text, from ? this.ownerMessageOf(from) : undefined) - if (botAsksFirst(this.host.settings?.get()) && (!from || (this.store.activation(from) && ownerChatTurn(this.store.activation(from)!)))) + if ((botAsksFirst(this.host.settings?.get()) || this.actions.forWork(workId)) && (!from || (this.store.activation(from) && ownerChatTurn(this.store.activation(from)!)))) this.store.run(`INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, '1') ON CONFLICT(bot_id, key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`, botId, `cursor:action-note:${workId}`) return 'noted' as const }) @@ -8182,7 +8182,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { */ private refuseWakeLoop(botId: string, brief: string, event: BotWakeEvent | null, workId?: string): void { const key = wakeLoopKey(brief, event) - const after = workId && botAsksFirst(this.host.settings?.get()) ? Number(this.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', botId, `cursor:action-owner:${workId}`)?.value ?? 0) : 0 + const after = workId ? Number(this.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', botId, `cursor:action-owner:${workId}`)?.value ?? 0) : 0 const same = after ? this.store.all('SELECT text, event_json FROM bot_reminders WHERE bot_id = ? AND work_id = ? AND rowid > ? AND created_at >= ?', botId, workId!, after, this.store.ownerLastWroteAt(botId)).filter(wake => wakeLoopKey(String(wake.text), wake.event_json ? JSON.parse(String(wake.event_json)) : null) === key).length : this.store.wakesSetSince(botId, this.store.ownerLastWroteAt(botId), workId).filter((wake) => wakeLoopKey(wake.text, wake.event) === key).length if (same >= MAX_SAME_WAKES) @@ -8618,7 +8618,6 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { private dueAt(botId?: string, forTimer = false): number | undefined { const sources: Array<() => number | undefined> = [ () => { - if (!botAsksFirst(this.host.settings?.get())) return undefined const row = this.store.get("SELECT MIN(expires_at) AS at FROM bot_actions WHERE status = 'open' AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null) return row?.at ? Date.parse(String(row.at)) : undefined }, diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index af682b7f25..7933670082 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1140,7 +1140,7 @@ it('settled approval stranded before its readiness write ends with a line', asyn expect(f.store.message(`bm_${t.workId}_ended`)?.text).toContain('nothing could let it carry on') }) -it.each(['stop', 'expiry', 'forget'] as const)('the disabled switch leaves held rows unchanged on %s', async path => { +it.each(['stop', 'expiry', 'forget'] as const)('the disabled switch settles existing held rows on %s', async path => { const t = await setup(true) await t.call(); await finish(f, t.work.payload) const a = f.bots.actions.forWork(t.workId)! @@ -1152,7 +1152,7 @@ it.each(['stop', 'expiry', 'forget'] as const)('the disabled switch leaves held const seq = memory.append({ botId: t.botId, kind: 'notice', sourceKey: `bm:${a.message_id}`, who: 'bot', text: 'Held call' })! memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) } - expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'open', exec_args: JSON.stringify(t.args) }) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: path === 'expiry' ? 'expired' : 'withdrawn', exec_args: null }) }) it.each(['send', 'not_now'] as const)('owner %s resets detection of repeated waits, as a question answer does', async answer => { @@ -1252,15 +1252,6 @@ it('switch off keeps repeated and differing calls direct without cards or refusa expect(f.store.unreadWorkNotes(t.workId)).toEqual([]) }) -it('switch off refuses card answers without resetting repeated-wait detection', async () => { - const t = await setup(true) - await t.call(); await finish(f, t.work.payload) - const a = f.bots.actions.forWork(t.workId)! - f.host.settings!.get().experimental.botAsksFirst = false - for (const answer of ['send', 'not_now'] as const) - await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer })).rejects.toThrow('switch is off') - expect(f.store.all("SELECT * FROM bot_memory_state WHERE key LIKE 'cursor:action-owner:%'")).toEqual([]) -}) it.each(['failing', 'starting', 'cold restart'] as const)('B1 keeps a live card through a %s listing and sends once after recovery', async state => { const t = await setup(true) From e0a8e6c24ad5ab8dc5c1e1ed01e94f438ee834ea Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:09:17 +0530 Subject: [PATCH 45/84] fix(bots): remove action cursors and Mousse updates when work ends --- src/mms/bots/store/BotStore.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index c6d4585456..31aacbb4b4 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1304,6 +1304,8 @@ export class BotStore { if (moved) { this.withdrawWorkQuestions(id) heldCalls(this.db)?.endWork(id) + const prefix = `cursor:action-refusal:${id}:` + this.run('DELETE FROM bot_memory_state WHERE key IN (?, ?) OR substr(key, 1, ?) = ?', `cursor:action-note:${id}`, `cursor:action-owner:${id}`, prefix.length, prefix) this.run("UPDATE bot_reminders SET status = 'cancelled', delivered_at = ? WHERE work_id = ? AND status = 'waiting'", this.now(), id) } return moved From 37101b454d5d57c0e21080be91ccfeb8d72aed16 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:09:17 +0530 Subject: [PATCH 46/84] test(bots): publish the chat permission card before allowing it --- tests/bots/botActions.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 7933670082..8c3f0533fb 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1512,7 +1512,7 @@ it('R2-3 allowing use your threads from chat preserves a sendable card', async ( const chat = f.store.laneActivations(t.botId, 'chat', ['running'])[0]! const asking = await start(f, chat.id) asking.prepared.authority.escalate!({ permission: { tool: 'threads' }, reason: 'Help in threads' }) - await finish(f, asking.payload) + await finish(f, asking.payload, 'completed', { text: 'May I use your threads?' }) await f.bots.service.answer(t.botId, f.store.openAsks(t.botId)[0].id, 'allow') expect(f.bots.actions.get(a.id)?.status).toBe('open') await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) From c860ef4e0b8da9baa34df627cf81477522a98c0a Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:09:17 +0530 Subject: [PATCH 47/84] test(bots): Send distinguishes pause expiry withdrawal and binding changes --- tests/bots/botActions.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 8c3f0533fb..7b9e04673c 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1580,3 +1580,17 @@ it.each(['stop', 'complete', 'purge'] as const)('R2-7 action cursors stay out of else { const runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n); (runtime.prepared as any).modelOutput?.(); await finish(f, runtime.payload) } expect(f.store.all('SELECT key FROM bot_memory_state WHERE key IN (?, ?)', ...keys)).toEqual([]) }) + +it.each(['paused', 'expired', 'withdrawn', 'binding'] as const)('R2-8 Send reports its specific %s refusal code and sentence', async reason => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (reason === 'paused') f.bots.pauseBot(t.botId) + if (reason === 'expired') f.clock.now = Date.parse(a.expires_at) + 1000 + if (reason === 'withdrawn') await f.bots.stopWork(t.botId, t.workId) + if (reason === 'binding') t.server.configDigest = 'changed' + const code = reason === 'binding' ? 'bot_action_changed' : `bot_action_${reason}` + const sentence = reason === 'paused' ? `Resume ${f.bots.definitionOf(t.botId).name} to send this.` : reason === 'expired' ? 'This call expired. Nothing was sent.' : reason === 'withdrawn' ? 'This call was withdrawn. Nothing was sent.' : 'This changed since you saw it. Review it again.' + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code, message: sentence }) + expect(t.calls).toEqual([]) +}) From 8b7f81ec25ad6f6d7628aa3274547eecbc6c01fc Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:11:52 +0530 Subject: [PATCH 48/84] fix(bots): report distinct owner-facing Send refusal reasons --- src/mms/bots/actions/BotActions.ts | 13 +++++++++---- src/mms/bots/activation/BotEngine.ts | 1 + tests/bots/botActions.test.ts | 4 ++-- tests/bots/botContinuationMatrix.test.ts | 1 + 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index f524675d72..832199a100 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -169,6 +169,7 @@ export function actionContinuation(action: Pick park(row: BotActivationRow): void schema(tool: BotMcpTool): unknown @@ -183,8 +184,8 @@ interface Host { execute(row: BotActivationRow, tool: BotMcpTool, args: Record): Promise } const pending = new Set(['open', 'approved', 'running']) -export class BotActionChanged extends Error { readonly code = 'bot_action_changed' } -const changed = () => new BotActionChanged('This changed since you saw it. Redraw the action.') +export class BotActionChanged extends Error { constructor(message: string, readonly code = 'bot_action_changed') { super(message) } } +const changed = () => new BotActionChanged('This changed since you saw it. Review it again.') export class BotActions { private readonly executing = new Set() constructor(private readonly host: Host) { @@ -328,11 +329,15 @@ export class BotActions { async answer(input: { actionId: string; digest: string; answer: 'send' | 'not_now' }): Promise<{ status: string }> { await this.host.refresh() const action = this.get(input.actionId) + if (!action) throw new BotActionChanged('This call is no longer available.', 'bot_action_gone') + if (action.status === 'expired') throw new BotActionChanged('This call expired. Nothing was sent.', 'bot_action_expired') + if (action.status === 'withdrawn') throw new BotActionChanged('This call was withdrawn. Nothing was sent.', 'bot_action_withdrawn') + if (action.status !== 'open') throw new BotActionChanged('This call has already been answered.', 'bot_action_settled') if (action && action.status === 'open' && Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) { this.expireDue() - throw new BotActionChanged('This call expired. Nothing was sent.') + throw new BotActionChanged('This call expired. Nothing was sent.', 'bot_action_expired') } - if (action && input.answer === 'send' && this.host.store.registry(action.bot_id)?.pausedReason === 'owner') throw new BotActionChanged('Resume this bot before sending.') + if (action && input.answer === 'send' && this.host.store.registry(action.bot_id)?.pausedReason === 'owner') throw new BotActionChanged(`Resume ${this.host.name(action.bot_id)} to send this.`, 'bot_action_paused') if (!action || action.status !== 'open' || action.args_digest !== input.digest || !this.valid(action)) throw changed() if (input.answer === 'not_now') { this.host.store.db.transaction(() => { diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index d666a8d32b..17fcaf7cd4 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -607,6 +607,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { store: this.host.store, refresh: async () => { await this.host.mcp?.warm() }, park: (row) => { if (!this.park(row, 'approval')) throw new Error('work ended') }, + name: botId => this.definitionOf(botId).name, enabled: () => botAsksFirst(this.host.settings?.get()), publish: id => { this.chat.republish(id) }, ownerAnswered: row => { diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 7b9e04673c..2c9cd7c9e8 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -214,7 +214,7 @@ it('the app answer method reaches the held call and returns redraw for a repeate const context = { connection: { id: 'c', binding: { profileId: 'p1', epoch: 1 }, capabilities: new Set() } } as never const params = { actionId: a.id, digest: a.args_digest, answer: 'send' } expect(await domains.dispatch(context, 'bots.actions.answer', params)).toMatchObject({ status: 'done' }) - await expect(domains.dispatch(context, 'bots.actions.answer', params)).rejects.toMatchObject({ code: 'bot_action_changed' }) + await expect(domains.dispatch(context, 'bots.actions.answer', params)).rejects.toMatchObject({ code: 'bot_action_settled' }) expect(t.calls).toEqual([t.args]) }) it.each(['relay', 'pi'] as const)('%s holds through the common path, and journals masked arguments', async runtime => { @@ -1072,7 +1072,7 @@ it('keeps the card during an owner pause and refuses Send in plain words', async await t.call(); await finish(f, t.work.payload) const a = f.bots.actions.forWork(t.workId)! f.bots.pauseBot(t.botId) - await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('Resume this bot') + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('to send this.') expect(f.bots.actions.get(a.id)?.status).toBe('open') expect(t.calls).toEqual([]) }) diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 20fb068ab9..97fc2d3616 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -97,6 +97,7 @@ it.each([false, true].flatMap(hasWaited => [ 'You had three cards for this tool that were not sent. Say what you need in your report and wait for your owner to write.' ].map(refusal => ({ hasWaited, refusal }))))('refusal joins ordered updates with wait history=$hasWaited: $refusal', ({ hasWaited, refusal }) => { const input = matrixInput('turn cap', 'note and answer', hasWaited) + f.clock.now = Date.parse('2026-11-07T09:04:00Z') f.store.recordWorkRefusal(ROW.id, ROW.botId, 'matrix-refusal', refusal) input.workEvents = [...eventsOf(input), ...(f.bots as any).workRefusalUpdates(ROW.id)] const prompt: string = (f.bots as any).continuationPrompt(ROW, input) From d2c201c7628a5baee794e244d1f61b2c418a96bd Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:12:45 +0530 Subject: [PATCH 49/84] test(bots): accept timely Send before an asynchronous tool refresh --- tests/bots/botActions.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 2c9cd7c9e8..8c30a6e758 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1594,3 +1594,21 @@ it.each(['paused', 'expired', 'withdrawn', 'binding'] as const)('R2-8 Send repor await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code, message: sentence }) expect(t.calls).toEqual([]) }) + +it('R2-5 accepts Send before refreshing tools so the timer cannot overtake it', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.clock.now = Date.parse(a.expires_at) - 1000 + let release!: () => void + const refresh = new Promise(resolve => { release = resolve }) + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(() => refresh) + const sending = f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await flush() + expect(f.bots.actions.get(a.id)?.status).toBe('approved') + f.clock.now += 2000; await f.bots.deliverDueReminders() + expect(f.bots.actions.get(a.id)?.status).toBe('approved') + release(); await sending + expect(t.calls).toEqual([t.args]) + expect(f.bots.actions.get(a.id)?.status).toBe('done') +}) From a24b4447bbdb1974a49a449fffc1d49a9d015974 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:13:23 +0530 Subject: [PATCH 50/84] docs(bots): describe Mousse refusal updates and existing-row cleanup --- docs/bots.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/bots.md b/docs/bots.md index cd2b3a9071..feaad299e3 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -769,7 +769,7 @@ NULL `owner_set` means set before v10 (or by an older writer) and preserves toda ### Asks first -The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, granted tools run as before. Tool selection, the approval card and scheduled runs that wait are separate work before this can be switched on. +The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, new granted-tool calls run as before. Existing held rows still withdraw, expire, settle and clear their arguments. Tool selection, the approval card and scheduled runs that wait are separate work before this can be switched on. A held call belongs to one piece of work and one runtime call in its dispatch. Mousse keeps its exact arguments in the action row until it settles; the chat, journal and export get a masked copy. Only unmistakable credential shapes are refused before a card is written: provider-prefixed keys, PEM private-key blocks, a password in a URL's userinfo, or a secret-named URL query value. Document IDs, base64 attachments, JWT-shaped page tokens and prose mentioning passwords remain reviewable. Values are not decoded or normalized to find more possible secrets: split or hex keys, upper-case `SK-` and a zero-width character inside `sk-` remain visible for the owner to judge. @@ -781,13 +781,13 @@ Mousse makes the stored call once, without asking the model to recreate it. It c Settled actions join the same ordered, timed updates as waits, notes and answers. An action that caused the resume leads with its outcome. Its id is kept on the dispatch. Work's stored updates (waits, action outcomes, notes and answers, including work without wait history) count as told only when a dispatch carrying them produces model output or completes. Nonempty model text or thinking, or a model tool-call start, confirms delivery; merely preparing or starting a request does not. A failed, interrupted or replaced dispatch without that evidence leaves its updates pending, including after a time-limit card. A repeated update is acceptable; losing one is not. Carried/read (`read_at` and `applied_at`, plus the dispatch's `workDelivery`) keeps its existing meaning for late taps, Forget and compaction. Confirmation is a separate fact used only to decide what the next prompt carries: `unreadWorkAnswers`, `unreadWorkQuestion` and `unreadWorkNotes` include carried-but-unconfirmed updates without clearing those read markers. New carrying dispatches start with `prompt.workTold = pending`; `BotStore.confirmWorkDelivery` changes only that marker to `output` or `completed`. Reads happen before any confirmation write transaction, so a dispatch with no updates never opens one. A failed confirmation is caught and logged once per dispatch; it never fails the runtime's turn, and the next continuation can carry the update again. Completion of a new dispatch is confirmed explicitly; older rows with no marker also accept a completed stored outcome. Startup recovers a completion written before settlement. A usage retry carries the previous prompt's update ids, so it confirms only what that prompt contained. A database written by master as of #1339 has `workDelivery` for work that waited but no confirmation marker. If its carrying dispatch ended at a wall, a deadline or a turn cap, its notes and answers can be told once more after upgrading (twice is acceptable; losing them is not). Their carried/read behavior is preserved. Earlier databases with no such delivery ids gain no retrospective replay. Approval parks before a time or event wait and has no idle or week exemption. -A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An approved call recovered while its listing is unavailable waits for that listing to return. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting its card or request ends the parked work with a line. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. +A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An approved call recovered while its listing is unavailable waits for that listing to return. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting only its card withdraws and forgets the call, then continues the work with the withdrawn outcome. Forgetting its request ends the work through the normal engine ending, with its journal entry and release of scratch, browser, progress and live status. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. `/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, argument digest, card metadata, bot note and stored result with fixed forgotten markers. The owner-message and work-note counters in its card metadata stay, as do its call key, target, status and timestamps. A forgotten row no longer matches an argument digest; the call key still prevents a second execution. A late result cannot restore forgotten content. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. -An owner pause keeps a held card: a pause is not a refusal. Send says "Resume this bot before sending." while paused. An approved call recovered after a restart while owner-paused settles as not sent, and its outcome joins unread updates for Resume. A card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline again. +An owner pause keeps a held card: a pause is not a refusal. Send says "Resume to send this." while paused. An approved call recovered after a restart while owner-paused settles as not sent, and its outcome joins unread updates for Resume. An open card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline before accepting the approval. A timely accepted Send is not expired while its tool refresh or execution is in progress. -After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a note in the same ordered update list preserves it for the next continuation. Changed arguments may get a new review, but after three declined cards for the same tool in the same work since its owner last wrote, further calls are refused until the owner writes or notes the work; the work is told to say what it needs in its report and wait. This uses the wake loop rule’s count and owner-input fact; expired cards do not count as a no. Any owner row, including a tapped answer to a question, lifts these refusals, as it does for wake loops. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. +After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a Mousse update in the same ordered list preserves it for the next continuation. It is not an owner note: it neither steers the work as owner words nor starts another turn or report. Its delivery is confirmed on model output or completion, as for settled calls. Changed arguments may get a new review, but after three declined or expired cards for the same tool in the same work since its owner last wrote, further calls are refused until the owner writes or notes the work; the work is told to say what it needs in its report and wait. This uses the wake loop rule’s count and owner-input fact; the sentence says three cards were not sent, without treating expiry as an owner refusal. Any owner row, including a tapped answer to a question, lifts these refusals, as it does for wake loops. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. Hidden argument values of four to eight characters require an adjacent character outside `[A-Za-z0-9_]` only at an edge whose own character is an ASCII letter, digit or underscore. Other edges require no boundary; longer values are replaced wherever they occur. Values shorter than four characters are left alone. Replacement runs in the server's own text before Mousse frames it, including JSON-escaped string echoes and numeric echoes. Credential masking still applies to the result. Transformed echoes (for example encoded, upper-case or truncated values) are not caught by this exact-value replacement. The stored result is capped at 64 KiB in total; images are omitted with a note, never cut into invalid data. Journal key-name masking applies only to work with a held action; other work keeps master's tool input capture. From 4168699393e712e8f784110d5c4e2d012a29fc02 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:15:22 +0530 Subject: [PATCH 51/84] fix(bots): accept timely Send before refreshing its execution binding --- src/mms/bots/actions/BotActions.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 832199a100..5e6285bcfe 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -327,7 +327,6 @@ export class BotActions { if (!action || action.status !== 'running' || !this.valid(action)) throw changed() } async answer(input: { actionId: string; digest: string; answer: 'send' | 'not_now' }): Promise<{ status: string }> { - await this.host.refresh() const action = this.get(input.actionId) if (!action) throw new BotActionChanged('This call is no longer available.', 'bot_action_gone') if (action.status === 'expired') throw new BotActionChanged('This call expired. Nothing was sent.', 'bot_action_expired') @@ -351,10 +350,11 @@ export class BotActions { if (!this.transition(action.id, 'open', 'approved')) throw changed() this.host.ownerAnswered(this.host.store.activation(action.activation_id)!) }) - await this.runApproved(action.id) + await this.runApproved(action.id, true) return { status: this.get(action.id)!.status } } - private async runApproved(id: string): Promise { + private async runApproved(id: string, refresh = false): Promise { + if (refresh) await this.host.refresh() const action = this.get(id) if (!action || action.status !== 'approved') return if (this.host.store.registry(action.bot_id)?.pausedReason === 'owner') { From 263488bae3f4a1abf4259d305c86bab17bc5b2b3 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:15:22 +0530 Subject: [PATCH 52/84] test(bots): preserve specific refusal codes through the chat service --- tests/bots/botActions.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 8c30a6e758..ae7c2ce663 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1591,7 +1591,7 @@ it.each(['paused', 'expired', 'withdrawn', 'binding'] as const)('R2-8 Send repor if (reason === 'binding') t.server.configDigest = 'changed' const code = reason === 'binding' ? 'bot_action_changed' : `bot_action_${reason}` const sentence = reason === 'paused' ? `Resume ${f.bots.definitionOf(t.botId).name} to send this.` : reason === 'expired' ? 'This call expired. Nothing was sent.' : reason === 'withdrawn' ? 'This call was withdrawn. Nothing was sent.' : 'This changed since you saw it. Review it again.' - await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code, message: sentence }) + await expect(f.bots.service.answerAction({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code, message: sentence }) expect(t.calls).toEqual([]) }) From e4c8da62ea48b02b9a245d5ac43c469a3f6b3a06 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:15:46 +0530 Subject: [PATCH 53/84] fix(bots): retain untold Mousse updates until output confirmation --- src/mms/bots/store/BotStore.ts | 4 ++-- tests/bots/botActions.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index 31aacbb4b4..ee9770a74a 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1304,8 +1304,7 @@ export class BotStore { if (moved) { this.withdrawWorkQuestions(id) heldCalls(this.db)?.endWork(id) - const prefix = `cursor:action-refusal:${id}:` - this.run('DELETE FROM bot_memory_state WHERE key IN (?, ?) OR substr(key, 1, ?) = ?', `cursor:action-note:${id}`, `cursor:action-owner:${id}`, prefix.length, prefix) + this.run('DELETE FROM bot_memory_state WHERE key IN (?, ?)', `cursor:action-note:${id}`, `cursor:action-owner:${id}`) this.run("UPDATE bot_reminders SET status = 'cancelled', delivered_at = ? WHERE work_id = ? AND status = 'waiting'", this.now(), id) } return moved @@ -2031,6 +2030,7 @@ export class BotStore { this.db.transaction(() => { if (!needsConfirmation(this.dispatch(activationId, n))) return this.run("UPDATE bot_dispatches SET prompt_json = json_set(prompt_json, '$.workTold', ?) WHERE activation_id = ? AND n = ?", why, activationId, n) + for (const id of this.dispatch(activationId, n)?.prompt.workRefusalIds ?? []) this.run('DELETE FROM bot_memory_state WHERE key = ?', id) }) } diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index ae7c2ce663..60035b5bdc 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -451,7 +451,7 @@ it('R5-words gives by-hand runs and disabled answers their own refusal', async ( expect(result.text).toContain('run started by hand') expect(result.text).not.toContain('scheduled') f.host.settings!.get().experimental.botAsksFirst = false - await expect(f.bots.service.answerAction({ actionId: 'missing', digest: 'missing', answer: 'send' })).rejects.toThrow(/not available/i) + await expect(f.bots.service.answerAction({ actionId: 'missing', digest: 'missing', answer: 'send' })).rejects.toThrow(/no longer available/i) }) it('R5-time transports the sent instant instead of a UTC clock string', async () => { const t = await setup(true) From 8c0ae1859596b06cb209113fc9b896b0fbbbe879 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:16:21 +0530 Subject: [PATCH 54/84] fix(bots): preserve Send refusal reasons at the chat service boundary --- src/mms/bots/chat/BotChatService.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mms/bots/chat/BotChatService.ts b/src/mms/bots/chat/BotChatService.ts index a51b0f3be5..7182cb799e 100644 --- a/src/mms/bots/chat/BotChatService.ts +++ b/src/mms/bots/chat/BotChatService.ts @@ -410,7 +410,7 @@ export class BotChatService { const action = this.engine.actions.get(input.actionId) if (input.botId && action?.bot_id !== input.botId) throw new BotEngineError('not_found', 'No held action here.') try { return await this.engine.actions.answer(input) } catch (error) { - if (error instanceof BotActionChanged) throw new BotEngineError('bot_action_changed', error.message) + if (error instanceof BotActionChanged) throw new BotEngineError(error.code, error.message) throw error } } From 79c847385b1d6e3d3cc09daf1dbd190bd8a56977 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:16:50 +0530 Subject: [PATCH 55/84] test(bots): accepted approvals never expire during a cold restart --- tests/bots/botActions.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 60035b5bdc..330ae07cbf 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1389,13 +1389,14 @@ it('restart never executes a previously approved call while its owner has paused expect(t.calls).toEqual([]) }) -it('B1 an approved row survives a cold restart and runs only after a successful listing', async () => { +it.each([false, true])('B1 an approved row survives a cold restart, past deadline=%s, and runs after listing', async late => { const t = await setup(true) await t.call(); await finish(f, t.work.payload) const a = f.bots.actions.forWork(t.workId)! f.bots.actions.transition(a.id, 'open', 'approved') const tools = t.server.tools.splice(0) const where = vi.spyOn(t.mcp, 'where').mockReturnValue(undefined) + if (late) f.clock.now = Date.parse(a.expires_at) + 1000 f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() expect(f.bots.actions.get(a.id)?.status).toBe('approved') expect(t.calls).toEqual([]) From 4f78494985c9ea62cf94437bd065faa742cbec14 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:17:23 +0530 Subject: [PATCH 56/84] fix(bots): preserve accepted approvals until recovery or withdrawal --- src/mms/bots/actions/BotActions.ts | 4 ++-- src/mms/bots/actions/lifecycle.ts | 2 +- src/mms/bots/activation/BotEngine.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 5e6285bcfe..1bf7f8b201 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -367,8 +367,8 @@ export class BotActions { const current = this.host.store.activation(action.activation_id) let intact = false try { intact = Boolean(action.exec_args && action.exec_args.length <= ACTION_MAX_ARGUMENT_CHARS && !containsCredential(JSON.parse(action.exec_args)) && actionDigest(JSON.parse(action.exec_args)) === action.args_digest) } catch { /* Corrupt arguments are never recoverable. */ } - if (Date.parse(action.expires_at) > Date.parse(this.host.store.now()) && intact && current && !this.host.binding(current, JSON.parse(action.target_json)) && !this.host.obsolete(action)) return - this.transition(id, 'approved', Date.parse(action.expires_at) <= Date.parse(this.host.store.now()) ? 'expired' : 'withdrawn', { text: 'This changed since you saw it. Nothing was sent; carry on without it.' }) + if (intact && current && !this.host.binding(current, JSON.parse(action.target_json)) && !this.host.obsolete(action)) return + this.transition(id, 'approved', 'withdrawn', { text: 'This changed since you saw it. Nothing was sent; carry on without it.' }) this.finish(action) return } diff --git a/src/mms/bots/actions/lifecycle.ts b/src/mms/bots/actions/lifecycle.ts index e4d204912b..70e948fc45 100644 --- a/src/mms/bots/actions/lifecycle.ts +++ b/src/mms/bots/actions/lifecycle.ts @@ -1,6 +1,6 @@ import type { BotStoreTx } from '../store/BotStore' -/** Per open database, never persisted: a disabled feature installs no active behavior. */ +/** Per open database: existing held rows settle even when new holds are disabled. */ export interface HeldCallLifecycle { endWork(id: string): void grantChanged(botId: string): void diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 17fcaf7cd4..b1fcb63bbf 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -1,5 +1,5 @@ import { WORK_WAIT_RULES, workWaitInput, workWaitRule, workReadiness, workWaitLine, parkedNeedsOwner, type WorkWaitLookups, type WorkWaitFacts, type WorkWaitReason } from './workWaiting' -import { BotActions, BotActionChanged, actionContinuation, removeHiddenArguments, botAsksFirst, actionDigest, maskedActionData } from '../actions/BotActions' +import { BotActions, BotActionChanged, actionContinuation, removeHiddenArguments, botAsksFirst, maskedActionData } from '../actions/BotActions' import { callForBot, type BotMcp } from '../mcp/BotMcp' import { isQuietHours } from '../../../shared/settings' import { BotTellings } from '../chat/BotTellings' From b6c266a909d6221c07805bfbba906ae42015cc3f Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:17:23 +0530 Subject: [PATCH 57/84] docs(bots): explain private action cursors and their cleanup --- docs/bots.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/bots.md b/docs/bots.md index feaad299e3..407cc46342 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -789,6 +789,8 @@ An owner pause keeps a held card: a pause is not a refusal. Send says "Resume ` and `cursor:action-owner:`. These survive restarts without a database-version change and are deleted in the transaction that ends the work. Pending Mousse refusal updates use `cursor:action-refusal::…`; their ids travel in `workRefusalIds` and they are removed when output or completion confirms delivery. Unconfirmed updates survive an interrupted continuation, as settled calls do. All of this state stays out of the memory export and is removed by the bot's purge. The numeric owner/message facts in a tombstoned card remain for refusal decisions. + Hidden argument values of four to eight characters require an adjacent character outside `[A-Za-z0-9_]` only at an edge whose own character is an ASCII letter, digit or underscore. Other edges require no boundary; longer values are replaced wherever they occur. Values shorter than four characters are left alone. Replacement runs in the server's own text before Mousse frames it, including JSON-escaped string echoes and numeric echoes. Credential masking still applies to the result. Transformed echoes (for example encoded, upper-case or truncated values) are not caught by this exact-value replacement. The stored result is capped at 64 KiB in total; images are omitted with a note, never cut into invalid data. Journal key-name masking applies only to work with a held action; other work keeps master's tool input capture. Send is honoured from any device that may reach the bot, whatever that device's own permission limit, as an Allow of a permission is today (subject to the complete-card size check above). Executable arguments are cleared from the action row with every settled state. The model's own tool call, including its exact arguments, remains in the work's runtime transcript and the provider's session file. Mousse does not rewrite those transcripts; clearing the stored action arguments does not remove those copies. This covers Mousse's MCP calls, not commands, browser actions or actions on the owner's threads. From 29904f964c49380314142d46fab7a52730a7164d Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:18:20 +0530 Subject: [PATCH 58/84] test(bots): grant revocation and held-call withdrawal roll back together --- tests/bots/botActions.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 330ae07cbf..cdf1956024 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1613,3 +1613,17 @@ it('R2-5 accepts Send before refreshing tools so the timer cannot overtake it', expect(t.calls).toEqual([t.args]) expect(f.bots.actions.get(a.id)?.status).toBe('done') }) + +it('R2-3 revoking a grant withdraws its held pair in the same transaction', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const grant = f.store.activeGrant(t.botId)! + f.store.db.statement(`CREATE TRIGGER fail_revoke_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() + expect(() => f.store.revoke(t.botId)).toThrow() + expect(f.store.activeGrant(t.botId)).toEqual(grant) + expect(f.bots.actions.get(a.id)?.status).toBe('open') + f.store.db.statement('DROP TRIGGER fail_revoke_card').run() + f.store.revoke(t.botId) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) +}) From 5fa31e4bf00c2c636ccf40067173d14355276e2c Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:18:56 +0530 Subject: [PATCH 59/84] fix(bots): withdraw held calls transactionally when their grant is revoked --- src/mms/bots/store/BotStore.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index ee9770a74a..377afec055 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1172,7 +1172,11 @@ export class BotStore { } revoke(botId: string): boolean { - return this.run('UPDATE bot_grants SET revoked_at = ? WHERE bot_id = ? AND revoked_at IS NULL', this.now(), botId) > 0 + return this.db.transaction(() => { + const revoked = this.run('UPDATE bot_grants SET revoked_at = ? WHERE bot_id = ? AND revoked_at IS NULL', this.now(), botId) > 0 + if (revoked) heldCalls(this.db)?.grantChanged(botId) + return revoked + }) } // -- Threads --------------------------------------------------------------------------------- From 2959ab37ffb2ad235d5381ccbed3cea3b701072e Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:34:13 +0530 Subject: [PATCH 60/84] test(bots): accepted Send has a ten-minute window from the tap --- tests/bots/botActions.test.ts | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index cdf1956024..a9658fc364 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1627,3 +1627,52 @@ it('R2-3 revoking a grant withdraws its held pair in the same transaction', asyn f.store.revoke(t.botId) expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) }) + +it.each([9, 11])('R3-1 accepted Send recovers at %s minutes only within its tap window', async minutes => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + const deadline = f.clock.now + 10 * 60_000 + expect(f.bots.nextDueAt(t.botId)).toBe(new Date(deadline).toISOString()) + expect(f.bots.isIdle(t.botId)).toBe(false) + expect(f.store.message(a.message_id)?.text).toBe('Waiting for Mail…') + f.clock.now += minutes * 60_000 + if (minutes === 11) { f.timers.at(-1)!.fn(); await flush() } + t.server.tools.push(t.descriptor); t.server.failing = false + f.bots.fillMcpAsks(); await flush() + if (minutes === 9) { expect(t.calls).toEqual([t.args]); expect(f.bots.actions.get(a.id)?.status).toBe('done'); return } + expect(t.calls).toEqual([]) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'failed', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe("Mail couldn't be reached, so nothing was sent.") + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain("Mail couldn't be reached") + expect(f.store.unreadWorkActions(t.workId).map(a => a.id)).toEqual([a.id]) + const next = await start(f, t.workId, 2) + ;(next.prepared as any).modelOutput?.() + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) + expect(await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'after-send-timeout', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) +}) + +it.each(['inside two restarts', 'outside two restarts', 'sleep', 'card deadline'] as const)('R3-1 tap deadline survives %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (path === 'card deadline') f.clock.now = Date.parse(a.expires_at) - 1000 + const tapped = f.clock.now + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + expect(f.bots.nextDueAt(t.botId)).toBe(new Date(tapped + 600_000).toISOString()) + if (path.includes('restarts')) { + for (const elapsed of [240_000, path.startsWith('inside') ? 540_000 : 660_000]) { + f.clock.now = tapped + elapsed + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + } + } else { f.clock.now = tapped + (path === 'sleep' ? 660_000 : 540_000); f.timers.at(-1)!.fn(); await flush() } + t.server.tools.push(t.descriptor); t.server.failing = false + f.bots.fillMcpAsks(); await flush() + const sent = path === 'inside two restarts' || path === 'card deadline' + expect(t.calls).toEqual(sent ? [t.args] : []) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: sent ? 'done' : 'failed', exec_args: null }) +}) From e7cb705fa5b5796edce16fe52dbc6bb68c74ee45 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:35:09 +0530 Subject: [PATCH 61/84] test(bots): forgotten cards block the tool until owner input --- tests/bots/botActions.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index a9658fc364..b5086dc71d 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1676,3 +1676,30 @@ it.each(['inside two restarts', 'outside two restarts', 'sleep', 'card deadline' expect(t.calls).toEqual(sent ? [t.args] : []) expect(f.bots.actions.get(a.id)).toMatchObject({ status: sent ? 'done' : 'failed', exec_args: null }) }) + +it('R3-2 Forget blocks the tool until owner input without retaining call content', async () => { + const t = await setup(true, false, true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }); await flush() + const prompt = f.store.lastMainDispatch(t.workId)!.prompt.text + expect(prompt).toContain('Your owner removed this request') + expect(prompt).not.toContain('[forgotten]') + let next = await start(f, t.workId, 2) + const call = (body: string, name = 'Mail__send') => callForBot({ bot: next.prepared.authority, mcp: t.mcp, name, args: { ...t.args, body }, toolCallId: body, signal: new AbortController().signal }) + expect(await call(t.args.body)).toMatchObject({ isError: true }) + expect(await call('changed')).toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(await call('other', 'Mail__other')).not.toMatchObject({ isError: true }) + await finish(f, next.payload) + const other = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: other.id, digest: other.args_digest, answer: 'not_now' }); await flush() + next = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + f.bots.noteWork(t.botId, t.workId, 'Please try again') + expect(await call('after-owner')).not.toMatchObject({ isError: true }) + const saved = f.bots.actions.get(a.id)! + expect(saved).toMatchObject({ args_json: '"[forgotten]"', args_digest: '[forgotten]', exec_args: null, result_json: '{"text":"[forgotten]"}' }) + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('Exact text') +}) From fe9fef93d936d1e9823afd7237664a795cde9dc1 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:36:13 +0530 Subject: [PATCH 62/84] fix(bots): time out accepted Send ten minutes after the owner tap --- src/mms/bots/actions/BotActions.ts | 39 +++++++++++++++++++++++++--- src/mms/bots/activation/BotEngine.ts | 7 ++--- src/mms/bots/mcp/BotMcp.ts | 2 +- tests/bots/botActions.test.ts | 14 +++++----- 4 files changed, 46 insertions(+), 16 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 1bf7f8b201..61edd2f112 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -1,3 +1,5 @@ +/** Longest an accepted Send may wait before transport dispatch, counted from the owner's tap. */ +export const APPROVED_SEND_WINDOW_MS = 10 * 60_000 import { MAX_SAME_WAKES } from '../../../shared/bots/personal/wakes' import { registerHeldCalls } from './lifecycle' import { randomUUID } from 'node:crypto' @@ -57,7 +59,7 @@ export function removeHiddenArguments(result: ToolOutcome, args: unknown, schema function boundedActionResult(result: BotMcpCallOutcome): BotMcpCallOutcome { const note = result.images?.length ? `\n[${result.images.length} image(s) left out of the stored result.]` : '' const text = String(maskedActionData(result.text, Infinity)) - const build = (end: number): BotMcpCallOutcome => ({ text: `${text.slice(0, end)}${end < text.length ? '\n[Result cut to fit stored size.]' : ''}${note}`, ...(result.isError ? { isError: true } : {}), ...(result.toolReportedError ? { toolReportedError: true } : {}) }) + const build = (end: number): BotMcpCallOutcome => ({ text: `${text.slice(0, end)}${end < text.length ? '\n[Result cut to fit stored size.]' : ''}${note}`, ...(result.isError ? { isError: true } : {}), ...(result.toolReportedError ? { toolReportedError: true } : {}), ...(result.notSentInTime ? { notSentInTime: true } : {}) }) let low = 0, high = Math.min(text.length, 32_000) while (low < high) { const mid = Math.ceil((low + high) / 2) @@ -157,6 +159,7 @@ export interface ActionRow { /** Stored outcomes are timed updates, assembled with all other work updates at dispatch. */ export function actionContinuation(action: Pick): string { const result = action.result_json ? JSON.parse(action.result_json) as BotMcpCallOutcome : undefined + if (result?.notSentInTime) return `${result.text} Nothing left Mousse. Decide whether a new request is needed.` const line = action.status === 'done' ? 'Your owner sent it. The tool answered:' : action.status === 'declined' ? 'Your owner chose not to send this: carry on without it and say what you skipped.' : action.status === 'expired' ? 'This call expired. Nothing was sent; do not try the same call again without a new reason.' @@ -218,10 +221,26 @@ export class BotActions { for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND status IN ('open', 'approved')", id)) this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'This work ended. Nothing was sent.' }) } + private approvedDeadline(action: Pick): number { + return action.answered_at ? Date.parse(action.answered_at) + APPROVED_SEND_WINDOW_MS : 0 + } + nextDueAt(botId?: string): number | undefined { + const times = (this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved') AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null) as unknown as ActionRow[]) + .map(action => action.status === 'approved' ? this.approvedDeadline(action) : Date.parse(action.expires_at)) + return times.length ? Math.min(...times) : undefined + } + private sendTimeout(action: ActionRow): boolean { + const service = JSON.parse(action.card_json ?? '{}').serverName ?? 'The service' + const moved = this.transition(action.id, action.status, 'failed', { isError: true, notSentInTime: true, text: `${service} couldn't be reached, so nothing was sent.` }) + if (moved) this.finish(action) + return moved + } expireDue(): void { for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status = 'open' AND expires_at <= ?", this.host.store.now())) { if (this.transition(String(a.id), String(a.status), 'expired', { text: 'This call expired. Carry on without it; do not try the same call again without a new reason.' })) this.finish(a as unknown as ActionRow) } + for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE status = 'approved'") as unknown as ActionRow[]) + if (this.approvedDeadline(action) <= Date.parse(this.host.store.now())) this.sendTimeout(action) } withdrawChanged(): void { for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved')")) { @@ -276,7 +295,7 @@ export class BotActions { this.host.store.run(`INSERT INTO bot_actions(id, call_key, bot_id, activation_id, lane, kind, target_json, exec_args, args_json, args_digest, binding_json, card_json, status, message_id, expires_at, created_at) VALUES(?, ?, ?, ?, 'run', 'mcp', ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`, - id, callKey, row.botId, row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), exact, JSON.stringify(review.args), actionDigest(JSON.parse(exact)), JSON.stringify(binding), JSON.stringify({ hasHiddenValues: review.hasHiddenValues }), messageId, + id, callKey, row.botId, row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), exact, JSON.stringify(review.args), actionDigest(JSON.parse(exact)), JSON.stringify(binding), JSON.stringify({ hasHiddenValues: review.hasHiddenValues, serverName: tool.serverName }), messageId, new Date(Date.parse(this.host.store.now()) + 48 * 3600_000).toISOString(), this.host.store.now()) this.host.park(row) this.host.post(row, messageId, `${tool.serverName} · ${tool.tool}\n${review.hasHiddenValues ? 'Hidden values will be sent.\n' : ''}${JSON.stringify(review.args)}`) @@ -292,6 +311,13 @@ export class BotActions { ran_at = CASE WHEN ? IN ('running', 'done') THEN ? ELSE ran_at END WHERE id = ? AND status = ?`, to, pending.has(to) ? 1 : 0, result ? JSON.stringify(boundedActionResult(result)) : null, from, this.host.store.now(), to, this.host.store.now(), id, from) > 0 + if (moved && result?.notSentInTime) this.host.store.run("UPDATE bot_actions SET card_json = json_set(card_json, '$.settledAt', ?) WHERE id = ?", this.host.store.now(), id) + if (moved && ['approved', 'running'].includes(to)) { + const action = this.get(id)! + const service = JSON.parse(action.card_json ?? '{}').serverName ?? 'the service' + this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'approved' ? `Waiting for ${service}…` : 'Sending…', action.message_id) + this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) + } if (moved && ['declined', 'expired'].includes(to)) { const action = this.get(id)! this.host.store.run(`UPDATE bot_actions SET card_json = json_set(COALESCE(card_json, '{}'), '$.ownerSeq', ?, '$.noteSeq', ?) WHERE id = ?`, @@ -300,7 +326,7 @@ export class BotActions { if (moved && !pending.has(to)) { const action = this.get(id)! const row = this.host.store.activation(action.activation_id) - if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) + if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', result?.notSentInTime ? result.text : to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) if (row?.endReason === 'approval') this.host.store.moveActivation(row.id, ['blocked'], 'blocked', { endReason: 'approval_answered' }) this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) } @@ -324,11 +350,16 @@ export class BotActions { assertRunning(id: string): void { const action = this.get(id) + if (action?.status === 'running' && this.approvedDeadline(action) <= Date.parse(this.host.store.now())) { + this.sendTimeout(action) + throw new BotActionChanged(JSON.parse(this.get(id)!.result_json!).text, 'bot_action_unreachable') + } if (!action || action.status !== 'running' || !this.valid(action)) throw changed() } async answer(input: { actionId: string; digest: string; answer: 'send' | 'not_now' }): Promise<{ status: string }> { const action = this.get(input.actionId) if (!action) throw new BotActionChanged('This call is no longer available.', 'bot_action_gone') + if (action.result_json && JSON.parse(action.result_json).notSentInTime) throw new BotActionChanged(JSON.parse(action.result_json).text, 'bot_action_unreachable') if (action.status === 'expired') throw new BotActionChanged('This call expired. Nothing was sent.', 'bot_action_expired') if (action.status === 'withdrawn') throw new BotActionChanged('This call was withdrawn. Nothing was sent.', 'bot_action_withdrawn') if (action.status !== 'open') throw new BotActionChanged('This call has already been answered.', 'bot_action_settled') @@ -350,6 +381,7 @@ export class BotActions { if (!this.transition(action.id, 'open', 'approved')) throw changed() this.host.ownerAnswered(this.host.store.activation(action.activation_id)!) }) + this.host.held() await this.runApproved(action.id, true) return { status: this.get(action.id)!.status } } @@ -357,6 +389,7 @@ export class BotActions { if (refresh) await this.host.refresh() const action = this.get(id) if (!action || action.status !== 'approved') return + if (this.approvedDeadline(action) <= Date.parse(this.host.store.now())) { this.sendTimeout(action); return } if (this.host.store.registry(action.bot_id)?.pausedReason === 'owner') { this.transition(id, 'approved', 'withdrawn', { text: 'This bot was paused by its owner. Nothing was sent; carry on without it when resumed.' }) this.finish(action) diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index b1fcb63bbf..a20d026941 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -5339,7 +5339,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const answered = deliveryQuestion?.status === 'answered' || deliveryQuestion?.status === 'defaulted' ? this.workAnswerOf(deliveryQuestion) : undefined const workEvents: WorkContinuationEvent[] | undefined = durableWork ? [ ...refusals, - ...actions.map(action => ({ at: (action.status === 'declined' ? action.answered_at : action.ran_at) ?? action.answered_at ?? current.createdAt, text: actionContinuation(action), actionId: action.id })), + ...actions.map(action => ({ at: JSON.parse(action.card_json ?? '{}').settledAt ?? (action.status === 'declined' ? action.answered_at : action.ran_at) ?? action.answered_at ?? current.createdAt, text: actionContinuation(action), actionId: action.id })), ...waits.map(wait => ({ at: wait.dueAt, text: workWaitInput(wait, clockTime) })), ...answers.map(answer => ({ at: answer.answeredAt ?? answer.createdAt, answer })), ...(notes?.events ?? []), @@ -8618,10 +8618,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { */ private dueAt(botId?: string, forTimer = false): number | undefined { const sources: Array<() => number | undefined> = [ - () => { - const row = this.store.get("SELECT MIN(expires_at) AS at FROM bot_actions WHERE status = 'open' AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null) - return row?.at ? Date.parse(String(row.at)) : undefined - }, + () => this.actions.nextDueAt(botId), () => this.tellings.next(botId), () => { const row = this.store.nextReminder(botId) diff --git a/src/mms/bots/mcp/BotMcp.ts b/src/mms/bots/mcp/BotMcp.ts index 18cfd2a3ec..b8113217d8 100644 --- a/src/mms/bots/mcp/BotMcp.ts +++ b/src/mms/bots/mcp/BotMcp.ts @@ -225,7 +225,7 @@ export function failureText(serverName: string, error: unknown, signal?: AbortSi return `${serverName} couldn't run this call. ${carryOn}` } -export type BotMcpCallOutcome = ToolOutcome & { callState?: 'failed' | 'uncertain'; toolReportedError?: true } +export type BotMcpCallOutcome = ToolOutcome & { callState?: 'failed' | 'uncertain'; toolReportedError?: true; notSentInTime?: true } export class BotMcp implements BotMcpHost { constructor(private readonly deps: BotMcpDeps) {} diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index b5086dc71d..0344ea35ba 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -156,8 +156,8 @@ it.each(['approved', 'running'] as const)('restart after %s never repeats a call f.bots = new BotEngine(f.host) await f.bots.reconcileOnStartup() await f.bots.actions.reconcile() - expect(t.calls).toEqual(state === 'approved' ? [t.args] : []) - expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'done' : 'uncertain', exec_args: null }) + expect(t.calls).toEqual([]) + expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'failed' : 'uncertain', exec_args: null }) }) it('answering before the old turn ends does not dispatch a second turn early', async () => { const t = await setup(true) @@ -193,8 +193,8 @@ it.each(['approved', 'running'] as const)('restart preserves timely approval and if (state === 'running') f.bots.actions.transition(a.id, 'approved', 'running') f.clock.now += 48 * 3600_000 + 1000 await f.bots.actions.reconcile() - expect(t.calls).toEqual(state === 'approved' ? [t.args] : []) - expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'done' : 'uncertain', exec_args: null }) + expect(t.calls).toEqual([]) + expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'failed' : 'uncertain', exec_args: null }) }) it('an expired Send is refused', async () => { const t = await setup(true) @@ -1398,12 +1398,12 @@ it.each([false, true])('B1 an approved row survives a cold restart, past deadlin const where = vi.spyOn(t.mcp, 'where').mockReturnValue(undefined) if (late) f.clock.now = Date.parse(a.expires_at) + 1000 f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() - expect(f.bots.actions.get(a.id)?.status).toBe('approved') + expect(f.bots.actions.get(a.id)?.status).toBe(late ? 'failed' : 'approved') expect(t.calls).toEqual([]) t.server.tools.push(...tools); where.mockRestore() f.bots.fillMcpAsks(); await flush() - expect(f.bots.actions.get(a.id)?.status).toBe('done') - expect(t.calls).toEqual([t.args]) + expect(f.bots.actions.get(a.id)?.status).toBe(late ? 'failed' : 'done') + expect(t.calls).toEqual(late ? [] : [t.args]) }) it('B1 a real configuration change withdraws even while the server listing fails', async () => { From 7a577b49b6cd6c4a4709e48eceb084a70712470f Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:37:17 +0530 Subject: [PATCH 63/84] fix(bots): remember forgotten-card refusal by tool without its content --- src/mms/bots/actions/BotActions.ts | 16 ++++++++++++---- tests/bots/botActions.test.ts | 4 ++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 61edd2f112..1e83a2a045 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -157,8 +157,10 @@ export interface ActionRow { answered_at: string | null; ran_at: string | null; args_json: string; card_json: string | null; message_id: string; expires_at: string; result_json: string | null } /** Stored outcomes are timed updates, assembled with all other work updates at dispatch. */ -export function actionContinuation(action: Pick): string { +export function actionContinuation(action: Pick & Partial>): string { const result = action.result_json ? JSON.parse(action.result_json) as BotMcpCallOutcome : undefined + if (JSON.parse(action.card_json ?? '{}').ownerRemoved) return 'Your owner removed this request. Do not ask for it again unless they write.' + if (result?.text === '[forgotten]') return 'The saved details of this outcome were removed.' if (result?.notSentInTime) return `${result.text} Nothing left Mousse. Decide whether a new request is needed.` const line = action.status === 'done' ? 'Your owner sent it. The tool answered:' : action.status === 'declined' ? 'Your owner chose not to send this: carry on without it and say what you skipped.' @@ -202,6 +204,9 @@ export class BotActions { const pending = ['open', 'approved'].includes(String(action.status)) if (pending) this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'The request was forgotten. Nothing was sent.' }) this.forgetText(botId, String(action.id)) + if (action.message_id === messageId) this.host.store.run(`UPDATE bot_actions SET card_json = json_set(card_json, + '$.ownerRemoved', json('true'), '$.removedOwnerSeq', ?, '$.removedNoteSeq', ?) WHERE id = ?`, + host.store.ownerLastWroteSeq(botId), Number(host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', botId, `cursor:action-note:${action.activation_id}`)?.value ?? 0), String(action.id)) if (!pending) continue const row = host.store.activation(String(action.activation_id)) if (row && row.trigger.kind === 'work' && row.trigger.replyTo === messageId) host.forgottenRequest(row) @@ -213,7 +218,8 @@ export class BotActions { /** Erase call content without erasing owner intervention facts or the run-once key. */ forgetText(botId: string, actionId?: string): void { this.host.store.run(`UPDATE bot_actions SET args_json = ?, args_digest = '[forgotten]', - card_json = json_object('text', '[forgotten]', 'ownerSeq', COALESCE(json_extract(card_json, '$.ownerSeq'), 0), 'noteSeq', COALESCE(json_extract(card_json, '$.noteSeq'), 0)), + card_json = json_object('text', '[forgotten]', 'ownerSeq', COALESCE(json_extract(card_json, '$.ownerSeq'), 0), 'noteSeq', COALESCE(json_extract(card_json, '$.noteSeq'), 0), + 'ownerRemoved', json_extract(card_json, '$.ownerRemoved'), 'removedOwnerSeq', json_extract(card_json, '$.removedOwnerSeq'), 'removedNoteSeq', json_extract(card_json, '$.removedNoteSeq')), bot_note = ?, result_json = ? WHERE bot_id = ? AND (? IS NULL OR id = ?)`, '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId, actionId ?? null, actionId ?? null) } @@ -258,10 +264,10 @@ export class BotActions { const dispatch = this.host.store.dispatches(activationId).find(d => d.clientRequestId === dispatchId) return dispatch && (dispatch.n === mainN || dispatch.mainN === mainN) ? action : undefined } - private ownerWroteAfter(action: ActionRow): boolean { + private ownerWroteAfter(action: ActionRow, removed = false): boolean { const card = JSON.parse(action.card_json ?? '{}') const note = Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', action.bot_id, `cursor:action-note:${action.activation_id}`)?.value ?? 0) - return this.host.store.ownerLastWroteSeq(action.bot_id) > Number(card.ownerSeq ?? 0) || note > Number(card.noteSeq ?? 0) + return this.host.store.ownerLastWroteSeq(action.bot_id) > Number((removed ? card.removedOwnerSeq : card.ownerSeq) ?? 0) || note > Number((removed ? card.removedNoteSeq : card.noteSeq) ?? 0) } private refuse(row: BotActivationRow, action: ActionRow, text: string): ToolOutcome { this.host.store.recordWorkRefusal(row.id, row.botId, `${action.id}:${text.startsWith('Your owner declined') ? 'repeat' : 'loop'}`, text) @@ -274,6 +280,8 @@ export class BotActions { const existing = this.host.store.get('SELECT id FROM bot_actions WHERE call_key = ?', callKey) if (existing) return { text: 'This call is held for your owner. End your turn now.' } if (pending.has(this.forWork(row.id)?.status ?? '')) return { text: 'A call is already held for your owner. End your turn now.', isError: true } + const removed = (this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND json_extract(card_json, '$.ownerRemoved') = 1 ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool })) as unknown as ActionRow[]).find(action => !this.ownerWroteAfter(action, true)) + if (removed) return this.refuse(row, removed, 'Your owner removed this request. Do not ask for it again unless they write.') const declined = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool })) as unknown as ActionRow[] const unanswered = declined.filter(action => !this.ownerWroteAfter(action)) if (unanswered.length >= MAX_SAME_WAKES) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 0344ea35ba..ebb11d65a5 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -156,8 +156,8 @@ it.each(['approved', 'running'] as const)('restart after %s never repeats a call f.bots = new BotEngine(f.host) await f.bots.reconcileOnStartup() await f.bots.actions.reconcile() - expect(t.calls).toEqual([]) - expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'failed' : 'uncertain', exec_args: null }) + expect(t.calls).toEqual(state === 'approved' ? [t.args] : []) + expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'done' : 'uncertain', exec_args: null }) }) it('answering before the old turn ends does not dispatch a second turn early', async () => { const t = await setup(true) From 6eb593a3e45a1cc8989afd00880f79deea2f9a6c Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:38:50 +0530 Subject: [PATCH 64/84] test(bots): owner refusal sentences use the card voice --- tests/bots/botActions.test.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index ebb11d65a5..b448fd8d5a 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1591,7 +1591,7 @@ it.each(['paused', 'expired', 'withdrawn', 'binding'] as const)('R2-8 Send repor if (reason === 'withdrawn') await f.bots.stopWork(t.botId, t.workId) if (reason === 'binding') t.server.configDigest = 'changed' const code = reason === 'binding' ? 'bot_action_changed' : `bot_action_${reason}` - const sentence = reason === 'paused' ? `Resume ${f.bots.definitionOf(t.botId).name} to send this.` : reason === 'expired' ? 'This call expired. Nothing was sent.' : reason === 'withdrawn' ? 'This call was withdrawn. Nothing was sent.' : 'This changed since you saw it. Review it again.' + const sentence = reason === 'paused' ? `Resume ${f.bots.definitionOf(t.botId).name} to send this.` : reason === 'expired' ? 'This expired, so nothing was sent.' : reason === 'withdrawn' ? 'No longer needed, so nothing was sent.' : 'This changed since you saw it. Check it again before sending.' await expect(f.bots.service.answerAction({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code, message: sentence }) expect(t.calls).toEqual([]) }) @@ -1703,3 +1703,21 @@ it('R3-2 Forget blocks the tool until owner input without retaining call content expect(saved).toMatchObject({ args_json: '"[forgotten]"', args_digest: '[forgotten]', exec_args: null, result_json: '{"text":"[forgotten]"}' }) expect(JSON.stringify(memory.actions(t.botId))).not.toContain('Exact text') }) + + +it.each(['gone', 'settled', 'unreachable'] as const)('R3-3 owner wording for %s reaches the service unchanged', async reason => { + const t = await setup(true) + let id = 'missing', digest = 'missing' + if (reason !== 'gone') { + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)!; id = a.id; digest = a.args_digest + if (reason === 'settled') await f.bots.actions.answer({ actionId: id, digest, answer: 'not_now' }) + else { + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: id, digest, answer: 'send' }) + f.clock.now += 11 * 60_000; await f.bots.deliverDueReminders() + } + } + const sentence = reason === 'gone' ? "This can't be sent any more." : reason === 'settled' ? 'This was already answered.' : "Mail couldn't be reached, so nothing was sent." + await expect(f.bots.service.answerAction({ actionId: id, digest, answer: 'send' })).rejects.toMatchObject({ code: `bot_action_${reason}`, message: sentence }) +}) From c3a0f9459b646af335436c5ec543ec631b7a3a82 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:39:15 +0530 Subject: [PATCH 65/84] test(bots): grant changes cannot inspect another bot failing card --- tests/bots/botActions.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index b448fd8d5a..6da72e4513 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1721,3 +1721,23 @@ it.each(['gone', 'settled', 'unreachable'] as const)('R3-3 owner wording for %s const sentence = reason === 'gone' ? "This can't be sent any more." : reason === 'settled' ? 'This was already answered.' : "Mail couldn't be reached, so nothing was sent." await expect(f.bots.service.answerAction({ actionId: id, digest, answer: 'send' })).rejects.toMatchObject({ code: `bot_action_${reason}`, message: sentence }) }) + +it('R3-3 a failing card of another bot cannot undo this bot grant change', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const b = await createBot(f, { reply: 'Hello' }) + const definition = f.bots.definitionOf(b.botId) + const revision = f.host.definitions.publishRevision({ ...definition, permissions: { ...definition.permissions, mcp: [{ serverId: 'mail', tool: 'send', level: 'asks_first' }] } }) + f.store.setPublished(b.botId, revision.revision!) + f.store.approve(b.botId, botManifestDigest(revision.permissions), revision.permissions) + const workB = await f.bots.activate({ botId: b.botId, input: 'Work B', clientRequestId: 'work-b' }) + await start(f, workB.id) + f.store.run(`INSERT INTO bot_actions(id, call_key, bot_id, activation_id, lane, kind, target_json, exec_args, args_json, args_digest, binding_json, card_json, status, message_id, expires_at, created_at) + SELECT id || '_b', call_key || '_b', ?, ?, lane, kind, target_json, exec_args, args_json, args_digest, 'null', card_json, status, message_id, expires_at, created_at FROM bot_actions WHERE id = ?`, b.botId, workB.id, a.id) + // Positive control: reading B's corrupt but valid-JSON binding really fails. + expect(() => f.bots.actions.withdrawChanged()).toThrow() + const grant = f.store.activeGrant(t.botId)! + expect(() => f.store.approve(t.botId, grant.digest, grant.manifest)).not.toThrow() + expect(f.bots.actions.get(a.id)?.status).toBe('open') +}) From 5477330bf8d903fef05f0fbbfd21da8d1a01e85c Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:39:52 +0530 Subject: [PATCH 66/84] test(bots): refusal records end when work cannot be continued --- tests/bots/botActions.test.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 6da72e4513..0385530f5b 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1234,8 +1234,10 @@ it('a repeat refusal joins unread work updates without another action or card', await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'repeat-refused', signal: new AbortController().signal }) expect(f.store.unreadWorkRefusals(t.workId).map(n => n.text).join(' ')).toContain('Do not ask again') expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) - await finish(f, next.payload, 'failed', { outcome: { error: 'network_error' } }) - await (f.bots as any).continueWith(t.workId, [f.store.activation(t.workId)!.status], { network: true }) + await f.bots.tools.wakes!.wait!(t.botId, t.workId, { brief: 'Wait for progress', dueAt: new Date(f.clock.now + 300_000).toISOString() }) + await finish(f, next.payload) + expect(f.store.unreadWorkRefusals(t.workId)).toHaveLength(1) + f.clock.now += 300_000; await f.bots.deliverDueReminders(); await flush() expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('Do not ask again') const receiving = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) ;(receiving.prepared as any).modelOutput?.() @@ -1741,3 +1743,18 @@ it('R3-3 a failing card of another bot cannot undo this bot grant change', async expect(() => f.store.approve(t.botId, grant.digest, grant.manifest)).not.toThrow() expect(f.bots.actions.get(a.id)?.status).toBe('open') }) + + +it.each(['done', 'failed', 'cancelled', 'purge'] as const)('R3-3 refusal records end with work %s', async end => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }); await flush() + const next = await start(f, t.workId, 2) + await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'refused', signal: new AbortController().signal }) + expect(f.store.unreadWorkRefusals(t.workId)).toHaveLength(1) + if (end === 'cancelled') await f.bots.stopWork(t.botId, t.workId) + else if (end === 'purge') new BotMemoryStore({ db: f.store.db }).purge(t.botId) + else await finish(f, next.payload, end === 'done' ? 'completed' : 'failed', { outcome: end === 'failed' ? { error: 'fatal' } : undefined }) + expect(f.store.all("SELECT key FROM bot_memory_state WHERE key LIKE 'cursor:action-refusal:%'")).toEqual([]) +}) From 5344d4cc8dc14784a2355cd8a68129a791280a15 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:40:25 +0530 Subject: [PATCH 67/84] test(bots): owner pause ends accepted waiting calls before their deadline --- tests/bots/botActions.test.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 0385530f5b..4188db948c 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1758,3 +1758,24 @@ it.each(['done', 'failed', 'cancelled', 'purge'] as const)('R3-3 refusal records else await finish(f, next.payload, end === 'done' ? 'completed' : 'failed', { outcome: end === 'failed' ? { error: 'fatal' } : undefined }) expect(f.store.all("SELECT key FROM bot_memory_state WHERE key LIKE 'cursor:action-refusal:%'")).toEqual([]) }) + +it.each(['stop', 'forget', 'pause', 'grant', 'delete'] as const)('R3-1 accepted waiting call ends early on %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (path === 'pause') f.bots.pauseBot(t.botId) + if (path === 'grant') f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + if (path === 'delete') await f.bots.remove(t.botId) + if (path === 'forget') { + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + t.server.tools.push(t.descriptor); t.server.failing = false + f.bots.fillMcpAsks(); await flush() + expect(t.calls).toEqual([]) +}) From 54a06a601568c385043b209f228faacaf49423da Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:41:11 +0530 Subject: [PATCH 68/84] fix(bots): use owner-facing sentences for Send refusals --- src/mms/bots/actions/BotActions.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 1e83a2a045..25dc10fa45 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -165,7 +165,7 @@ export function actionContinuation(action: Pick new BotActionChanged('This changed since you saw it. Review it again.') +const changed = () => new BotActionChanged('This changed since you saw it. Check it again before sending.') export class BotActions { private readonly executing = new Set() constructor(private readonly host: Host) { @@ -366,14 +366,14 @@ export class BotActions { } async answer(input: { actionId: string; digest: string; answer: 'send' | 'not_now' }): Promise<{ status: string }> { const action = this.get(input.actionId) - if (!action) throw new BotActionChanged('This call is no longer available.', 'bot_action_gone') + if (!action) throw new BotActionChanged("This can't be sent any more.", 'bot_action_gone') if (action.result_json && JSON.parse(action.result_json).notSentInTime) throw new BotActionChanged(JSON.parse(action.result_json).text, 'bot_action_unreachable') - if (action.status === 'expired') throw new BotActionChanged('This call expired. Nothing was sent.', 'bot_action_expired') - if (action.status === 'withdrawn') throw new BotActionChanged('This call was withdrawn. Nothing was sent.', 'bot_action_withdrawn') - if (action.status !== 'open') throw new BotActionChanged('This call has already been answered.', 'bot_action_settled') + if (action.status === 'expired') throw new BotActionChanged('This expired, so nothing was sent.', 'bot_action_expired') + if (action.status === 'withdrawn') throw new BotActionChanged('No longer needed, so nothing was sent.', 'bot_action_withdrawn') + if (action.status !== 'open') throw new BotActionChanged('This was already answered.', 'bot_action_settled') if (action && action.status === 'open' && Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) { this.expireDue() - throw new BotActionChanged('This call expired. Nothing was sent.', 'bot_action_expired') + throw new BotActionChanged('This expired, so nothing was sent.', 'bot_action_expired') } if (action && input.answer === 'send' && this.host.store.registry(action.bot_id)?.pausedReason === 'owner') throw new BotActionChanged(`Resume ${this.host.name(action.bot_id)} to send this.`, 'bot_action_paused') if (!action || action.status !== 'open' || action.args_digest !== input.digest || !this.valid(action)) throw changed() From c18027014e91cdd986b2d56ddfed0deff692e77f Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:41:11 +0530 Subject: [PATCH 69/84] fix(bots): scope grant checks to the bot whose permissions changed --- src/mms/bots/actions/BotActions.ts | 6 +++--- src/mms/bots/activation/BotEngine.ts | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 25dc10fa45..50f41ab6b8 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -196,7 +196,7 @@ export class BotActions { constructor(private readonly host: Host) { registerHeldCalls(host.store.db, { endWork: id => this.withdrawWork(id), - grantChanged: () => this.withdrawChanged(), + grantChanged: botId => this.withdrawChanged(botId), forgetMessage: (botId, messageId) => { const ids = host.store.all(`SELECT a.* FROM bot_actions a JOIN bot_activations w ON w.id = a.activation_id WHERE a.bot_id = ? AND (a.message_id = ? OR json_extract(w.trigger_json, '$.replyTo') = ?)`, botId, messageId, messageId) @@ -248,8 +248,8 @@ export class BotActions { for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE status = 'approved'") as unknown as ActionRow[]) if (this.approvedDeadline(action) <= Date.parse(this.host.store.now())) this.sendTimeout(action) } - withdrawChanged(): void { - for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved')")) { + withdrawChanged(botId?: string): void { + for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved') AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null)) { if (this.host.obsolete(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.host.store.db.afterCommit(() => this.finish(a as unknown as ActionRow)) } } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index a20d026941..9687a13fbd 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -4690,7 +4690,6 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { this.store.db.transaction(() => { this.store.setPublished(botId, revision.revision!) this.store.approve(botId, digest, granted) - this.actions.withdrawChanged() if (switching) this.store.regrant(botId, grant.digest, digest, revision.revision!) for (const row of this.store.activationsIn(botId, ['queued', 'blocked'])) { if (row.status === 'blocked' && !workWaits(row)) continue From 156d10b895b9fb9f1a2b2c9b4dff20af950f3938 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:41:11 +0530 Subject: [PATCH 70/84] fix(bots): owner pause withdraws accepted calls still waiting for service --- src/mms/bots/actions/BotActions.ts | 6 ++++++ src/mms/bots/activation/BotEngine.ts | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 50f41ab6b8..58bc4d4962 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -227,6 +227,12 @@ export class BotActions { for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND status IN ('open', 'approved')", id)) this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'This work ended. Nothing was sent.' }) } + withdrawPaused(botId: string): void { + for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE bot_id = ? AND status = 'approved'", botId)) { + if (this.transition(String(action.id), 'approved', 'withdrawn', { text: 'This bot was paused by its owner. Nothing was sent; carry on without it when resumed.' })) + this.host.store.db.afterCommit(() => this.finish(action as unknown as ActionRow)) + } + } private approvedDeadline(action: Pick): number { return action.answered_at ? Date.parse(action.answered_at) + APPROVED_SEND_WINDOW_MS : 0 } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 9687a13fbd..ad0efd43d2 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -7330,7 +7330,10 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { /** `bots.personal.pause`: the owner pauses the bot's schedules. Chat still works. */ pauseBot(botId: string): void { this.entry(botId) - this.store.setPaused(botId, 'owner') + this.store.db.transaction(() => { + this.store.setPaused(botId, 'owner') + this.actions.withdrawPaused(botId) + }) // A paused bot runs nothing in the background either. this.stopWatchersOf(botId) this.changed({ botId }) From f1736997192f2974254762da00bb62bd67ecbe28 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:41:30 +0530 Subject: [PATCH 71/84] test(bots): startup drops refusal records for work that cannot be told --- tests/bots/botActions.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 4188db948c..8b3d4ae40d 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1779,3 +1779,11 @@ it.each(['stop', 'forget', 'pause', 'grant', 'delete'] as const)('R3-1 accepted f.bots.fillMcpAsks(); await flush() expect(t.calls).toEqual([]) }) + +it('R3-3 restart removes refusal records left by ended or missing work', async () => { + const t = await setup(true) + await finish(f, t.work.payload) + for (const workId of [t.workId, 'missing-work']) f.store.run('INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?)', t.botId, `cursor:action-refusal:${workId}:old`, JSON.stringify({ at: f.store.now(), text: 'old refusal' })) + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + expect(f.store.all("SELECT key FROM bot_memory_state WHERE key LIKE 'cursor:action-refusal:%'")).toEqual([]) +}) From 6aabf093aa5ba77e3c5c43f9085965f4e32147eb Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:42:28 +0530 Subject: [PATCH 72/84] test(bots): legacy whole-grant approvals withdraw on upgrade --- tests/bots/botActions.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 8b3d4ae40d..4fe1cd1951 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1787,3 +1787,17 @@ it('R3-3 restart removes refusal records left by ended or missing work', async ( f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() expect(f.store.all("SELECT key FROM bot_memory_state WHERE key LIKE 'cursor:action-refusal:%'")).toEqual([]) }) + +it.each(['open', 'approved'] as const)('R3-3 legacy #1340 %s cards withdraw on upgrade', async status => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const oldBinding = { ...JSON.parse(a.binding_json), grantRevision: 1, grantDigest: 'old-whole-grant' } + delete oldBinding.pairLevel + f.store.run('UPDATE bot_actions SET binding_json = ? WHERE id = ?', JSON.stringify(oldBinding), a.id) + if (status === 'approved') f.bots.actions.transition(a.id, 'open', 'approved') + f.clock.now += 11 * 60_000 + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(t.calls).toEqual([]) +}) From 1d2fbeff93af0f2b37d1c9b43f58ec42e1f77101 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:42:50 +0530 Subject: [PATCH 73/84] fix(bots): remove refusal records when their work can no longer be told --- src/mms/bots/actions/BotActions.ts | 1 + src/mms/bots/store/BotStore.ts | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 58bc4d4962..d30fde5253 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -443,6 +443,7 @@ export class BotActions { await this.runApproved(String(action.id)) } async reconcile(): Promise { + this.host.store.pruneWorkRefusals() this.expireDue() const interrupted = this.host.store.all("SELECT id FROM bot_actions WHERE status IN ('running', 'approved')") await this.host.refresh() diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index 377afec055..abf6340c02 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1308,7 +1308,8 @@ export class BotStore { if (moved) { this.withdrawWorkQuestions(id) heldCalls(this.db)?.endWork(id) - this.run('DELETE FROM bot_memory_state WHERE key IN (?, ?)', `cursor:action-note:${id}`, `cursor:action-owner:${id}`) + const refusalPrefix = `cursor:action-refusal:${id}:` + this.run('DELETE FROM bot_memory_state WHERE key IN (?, ?) OR substr(key, 1, ?) = ?', `cursor:action-note:${id}`, `cursor:action-owner:${id}`, refusalPrefix.length, refusalPrefix) this.run("UPDATE bot_reminders SET status = 'cancelled', delivered_at = ? WHERE work_id = ? AND status = 'waiting'", this.now(), id) } return moved @@ -2011,6 +2012,14 @@ export class BotStore { ORDER BY COALESCE(a.ran_at, a.answered_at, a.created_at), a.rowid`, workId) as unknown as ActionRow[] } + pruneWorkRefusals(): void { + const prefix = 'cursor:action-refusal:' + if (!this.get('SELECT 1 FROM bot_memory_state WHERE substr(key, 1, ?) = ? LIMIT 1', prefix.length, prefix)) return + this.run(`DELETE FROM bot_memory_state AS s WHERE substr(s.key, 1, ?) = ? AND NOT EXISTS ( + SELECT 1 FROM bot_activations a WHERE a.bot_id = s.bot_id AND a.status NOT IN ('done', 'failed', 'cancelled') + AND substr(s.key, 1, length(? || a.id || ':')) = ? || a.id || ':')`, prefix.length, prefix, prefix, prefix) + } + recordWorkRefusal(workId: string, botId: string, id: string, text: string): void { this.run('INSERT OR IGNORE INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?)', botId, `cursor:action-refusal:${workId}:${id}`, JSON.stringify({ at: this.now(), text })) From d1723544dc8c3c0ac1758de8d85944b9de506677 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:43:04 +0530 Subject: [PATCH 74/84] fix(bots): withdraw legacy bindings before recovering accepted calls --- src/mms/bots/actions/BotActions.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index d30fde5253..224e921b67 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -444,6 +444,7 @@ export class BotActions { } async reconcile(): Promise { this.host.store.pruneWorkRefusals() + this.withdrawChanged() this.expireDue() const interrupted = this.host.store.all("SELECT id FROM bot_actions WHERE status IN ('running', 'approved')") await this.host.refresh() From 8b291d2f1a238f006a63649200c325f8fcaed24d Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:38 +0530 Subject: [PATCH 75/84] test(bots): cover timeout and owner-removal continuations without forgotten text --- tests/bots/botActions.test.ts | 9 +++++---- tests/bots/botContinuationMatrix.test.ts | 11 +++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 4fe1cd1951..c01db1a2f1 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -451,7 +451,7 @@ it('R5-words gives by-hand runs and disabled answers their own refusal', async ( expect(result.text).toContain('run started by hand') expect(result.text).not.toContain('scheduled') f.host.settings!.get().experimental.botAsksFirst = false - await expect(f.bots.service.answerAction({ actionId: 'missing', digest: 'missing', answer: 'send' })).rejects.toThrow(/no longer available/i) + await expect(f.bots.service.answerAction({ actionId: 'missing', digest: 'missing', answer: 'send' })).rejects.toThrow(/can.t be sent any more/i) }) it('R5-time transports the sent instant instead of a UTC clock string', async () => { const t = await setup(true) @@ -1180,7 +1180,7 @@ it('a tool withdrawal is delivered through unread updates and confirmed on compl const a = f.bots.actions.forWork(t.workId)! t.server.tools.splice(0) f.bots.fillMcpAsks(); await flush() - expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('This call was withdrawn') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('No longer needed') expect(f.store.unreadWorkActions(t.workId).map(a => a.id)).toEqual([a.id]) const next = await start(f, t.workId, 2) await finish(f, next.payload) @@ -1450,11 +1450,12 @@ it('R2-4 three expired cards refuse further calls without claiming the owner dec await f.bots.deliverDueReminders(); await flush() runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) } + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'before-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) const a = f.bots.actions.forWork(t.workId)! const memory = new BotMemoryStore({ db: f.store.db }) const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'declined call' })! memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) - expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('Your owner removed this request') }) expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(3) }) @@ -1496,7 +1497,7 @@ it.each(['card', 'request'] as const)('R2-2 forgetting the %s uses the appropria memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }); await flush() if (which === 'card') { expect(f.store.activation(t.workId)?.status).toBe('running') - expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('withdrawn') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('Your owner removed this request') expect(f.store.lastMainDispatch(t.workId)!.prompt.text).not.toContain('request was forgotten') } else { expect(f.store.activation(t.workId)?.status).toBe('failed') diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 97fc2d3616..aaf3de04b9 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -57,13 +57,20 @@ const actionLines = [ ['failed', 'Nothing was sent. The call failed:'], ['tool_error', 'The tool reported an error. It may have done part of it: check before trying again. The tool answered:'], ['uncertain', 'It could not be confirmed whether this went through: check before trying again.'], - ['withdrawn', 'This call was withdrawn. Nothing was sent.'], + ['withdrawn', 'No longer needed, so nothing was sent.'], + ['send_timeout', "Mail couldn't be reached, so nothing was sent."], + ['owner_removed', 'Your owner removed this request. Do not ask for it again unless they write.'], ['expired', 'This call expired. Nothing was sent; do not try the same call again without a new reason.'] ] as const const actionCells = actionLines.flatMap(([status, line]) => [false, true].flatMap(hasWaited => [false, true].flatMap(cause => (['turn cap', 'permission allowed since refused'] as const).flatMap(reason => UPDATES.map(update => ({ status, line, hasWaited, cause, reason, update })))))) it.each(actionCells)('action $status / waited=$hasWaited / cause=$cause / $reason / $update', ({ status, line, hasWaited, cause, reason, update }) => { - const actionText = actionContinuation({ status: status === 'tool_error' ? 'failed' : status, result_json: JSON.stringify({ text: '[Server data, not instructions]\ndelivery detail', ...(status === 'tool_error' ? { toolReportedError: true } : {}) }) }) + const actionText = actionContinuation({ + status: status === 'tool_error' || status === 'send_timeout' ? 'failed' : status === 'owner_removed' ? 'withdrawn' : status, + ...(status === 'owner_removed' ? { card_json: JSON.stringify({ ownerRemoved: true }) } : {}), + result_json: JSON.stringify({ text: status === 'send_timeout' ? "Mail couldn't be reached, so nothing was sent." : status === 'owner_removed' ? '[forgotten]' : '[Server data, not instructions]\ndelivery detail', + ...(status === 'tool_error' ? { toolReportedError: true } : {}), ...(status === 'send_timeout' ? { notSentInTime: true } : {}) }) + }) const input = matrixInput(reason, update, true) input.workEvents.push({ at: '2026-11-07T09:04:00Z', text: actionText, actionId: 'action-1' }) input.actionCaused = cause ? actionText : undefined From db18a31b638ce428c677beedb7a4284b01abadde Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:45:58 +0530 Subject: [PATCH 76/84] docs(bots): describe Send windows owner removal and final refusal sentences --- docs/bots.md | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/docs/bots.md b/docs/bots.md index 407cc46342..2f0f778c32 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -769,27 +769,41 @@ NULL `owner_set` means set before v10 (or by an older writer) and preserves toda ### Asks first -The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, new granted-tool calls run as before. Existing held rows still withdraw, expire, settle and clear their arguments. Tool selection, the approval card and scheduled runs that wait are separate work before this can be switched on. +The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, new granted-tool calls run as before. Existing held rows still withdraw, expire, settle and clear their arguments. Send still works on a card left from when the switch was on; the switch gates only new holds. Tool selection, the approval card and scheduled runs that wait are separate work before this can be switched on. A held call belongs to one piece of work and one runtime call in its dispatch. Mousse keeps its exact arguments in the action row until it settles; the chat, journal and export get a masked copy. Only unmistakable credential shapes are refused before a card is written: provider-prefixed keys, PEM private-key blocks, a password in a URL's userinfo, or a secret-named URL query value. Document IDs, base64 attachments, JWT-shaped page tokens and prose mentioning passwords remain reviewable. Values are not decoded or normalized to find more possible secrets: split or hex keys, upper-case `SK-` and a zero-width character inside `sk-` remain visible for the owner to judge. A value is hidden by its key name only where the installed input schema declares that property, following `properties`, array `items`, local `$ref`, every `allOf`, `anyOf` and `oneOf` branch, `if`/`then`/`else`, `dependentSchemas` and indexed `prefixItems`. `$dynamicRef` is treated as unresolved. References have a cycle guard and a 32-step expansion limit. Under a broken, remote or depth-limited schema part, secret-named keys are hidden conservatively throughout that subtree; free-form keys elsewhere remain visible. Invented names in free-form objects stay visible, at every depth. The masked copy represents a hidden value as `{ "$mousse": "hidden", "text": "hidden · will be sent" }`; the exact value is sent unchanged on Send. Literal argument objects with a `$mousse` key are escaped as `{ "$mousse": "literal", "value": }`, recursively. Text saying "hidden · will be sent" is ordinary argument text. `card_json.hasHiddenValues` records whether a hidden value actually exists, for the card to say so beside its buttons. -Argument text is never cut from the review: at most 256,000 characters of serialized argument JSON are accepted in total, and larger calls are refused with a request to send less. Send names the action and the argument digest shown with it. It is bound to the installed server's configuration, the server id and tool name, the tool's schema, the held server/tool pair and its permission level, and the starting device's permission limit. Unrelated permissions and a grant revision bump leave that binding intact; removing or changing the pair withdraws its card, and granting it again does not revive the old card. A changed or expired binding needs a fresh review. Until the bridge carries whole large cards, a device's Send is refused when the complete message and its reply envelope exceed its 56 KiB limit: "Open it on the computer to send." Not now still works. +Argument text is never cut from the review: at most 256,000 characters of serialized argument JSON are accepted in total, and larger calls are refused with a request to send less. Send names the action and the argument digest shown with it. It is bound to the installed server's configuration, the server id and tool name, the tool's schema, the held server/tool pair and its permission level, and the starting device's permission limit. Unrelated permissions and a grant revision bump leave that binding intact; removing or changing the pair withdraws its card, and granting it again does not revive the old card. A changed or expired binding needs a fresh review. Cards held by the #1340 build use the older whole-grant binding and are withdrawn on upgrade. These are development profiles only; the upgrade fails safe. Until the bridge carries whole large cards, a device's Send is refused when the complete message and its reply envelope exceed its 56 KiB limit: "Open it on the computer to send." Not now still works. Mousse makes the stored call once, without asking the model to recreate it. It commits approval and then the start of execution separately. After a restart, an approved call is checked again before running; a call whose execution had started becomes uncertain and is never repeated. A call that never left Mousse, or Not now, reads "Not sent". When the server answered with an error the row is `failed` but reads "The tool reported an error": the work gets its framed error and is told that the tool may have done part of it, so it must check before trying again. A request sent without an answer becomes `uncertain`, "Couldn't tell if it went through". Settled actions join the same ordered, timed updates as waits, notes and answers. An action that caused the resume leads with its outcome. Its id is kept on the dispatch. Work's stored updates (waits, action outcomes, notes and answers, including work without wait history) count as told only when a dispatch carrying them produces model output or completes. Nonempty model text or thinking, or a model tool-call start, confirms delivery; merely preparing or starting a request does not. A failed, interrupted or replaced dispatch without that evidence leaves its updates pending, including after a time-limit card. A repeated update is acceptable; losing one is not. Carried/read (`read_at` and `applied_at`, plus the dispatch's `workDelivery`) keeps its existing meaning for late taps, Forget and compaction. Confirmation is a separate fact used only to decide what the next prompt carries: `unreadWorkAnswers`, `unreadWorkQuestion` and `unreadWorkNotes` include carried-but-unconfirmed updates without clearing those read markers. New carrying dispatches start with `prompt.workTold = pending`; `BotStore.confirmWorkDelivery` changes only that marker to `output` or `completed`. Reads happen before any confirmation write transaction, so a dispatch with no updates never opens one. A failed confirmation is caught and logged once per dispatch; it never fails the runtime's turn, and the next continuation can carry the update again. Completion of a new dispatch is confirmed explicitly; older rows with no marker also accept a completed stored outcome. Startup recovers a completion written before settlement. A usage retry carries the previous prompt's update ids, so it confirms only what that prompt contained. A database written by master as of #1339 has `workDelivery` for work that waited but no confirmation marker. If its carrying dispatch ended at a wall, a deadline or a turn cap, its notes and answers can be told once more after upgrading (twice is acceptable; losing them is not). Their carried/read behavior is preserved. Earlier databases with no such delivery ids gain no retrospective replay. Approval parks before a time or event wait and has no idle or week exemption. -A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An approved call recovered while its listing is unavailable waits for that listing to return. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting only its card withdraws and forgets the call, then continues the work with the withdrawn outcome. Forgetting its request ends the work through the normal engine ending, with its journal entry and release of scratch, browser, progress and live status. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. +A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An approved call recovered while its listing is unavailable waits for that listing to return. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting only its card withdraws and forgets the call, then continues the work told: "Your owner removed this request. Do not ask for it again unless they write." No tombstone text is read back to the work. Forgetting its request ends the work through the normal engine ending, with its journal entry and release of scratch, browser, progress and live status. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. `/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, argument digest, card metadata, bot note and stored result with fixed forgotten markers. The owner-message and work-note counters in its card metadata stay, as do its call key, target, status and timestamps. A forgotten row no longer matches an argument digest; the call key still prevents a second execution. A late result cannot restore forgotten content. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. -An owner pause keeps a held card: a pause is not a refusal. Send says "Resume to send this." while paused. An approved call recovered after a restart while owner-paused settles as not sent, and its outcome joins unread updates for Resume. An open card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline before accepting the approval. A timely accepted Send is not expired while its tool refresh or execution is in progress. +An owner pause keeps a held card: a pause is not a refusal. Send says `Resume to send this.` while paused. Pausing also withdraws an approved call still waiting for its service; recovery while owner-paused settles it as not sent, and its outcome joins unread updates for Resume. An open card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline before accepting the approval. An accepted Send must reach the service within ten minutes of the owner's tap (`APPROVED_SEND_WINDOW_MS`, from `answered_at`), independent of the card's original deadline. The due timer includes that deadline, so restart, sleep or a missing listing cannot leave it waiting indefinitely. Before dispatch the row stays `approved`, with message text "Waiting for …"; execution changes it to `running`, "Sending…". Past the ten minutes it settles `failed`, clears executable arguments, and says " couldn't be reached, so nothing was sent." The work gets that outcome once through the ordered update list and may decide to ask again. This timeout is neither a declined nor an expired card: it does not count toward the three-card rule or the identical-call refusal. Once dispatched, a running call settles normally or becomes uncertain after restart. + +Forgetting a card blocks further calls of that tool in that piece of work until the owner writes or notes the work, including calls with changed arguments. Another tool is unaffected. This uses a content-free owner-removal marker and owner-input numbers in the tombstoned card metadata; no digest or call content is kept for it. After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a Mousse update in the same ordered list preserves it for the next continuation. It is not an owner note: it neither steers the work as owner words nor starts another turn or report. Its delivery is confirmed on model output or completion, as for settled calls. Changed arguments may get a new review, but after three declined or expired cards for the same tool in the same work since its owner last wrote, further calls are refused until the owner writes or notes the work; the work is told to say what it needs in its report and wait. This uses the wake loop rule’s count and owner-input fact; the sentence says three cards were not sent, without treating expiry as an owner refusal. Any owner row, including a tapped answer to a question, lifts these refusals, as it does for wake loops. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. -The engine keeps its action-note and action-owner counters in `bot_memory_state` under `cursor:action-note:` and `cursor:action-owner:`. These survive restarts without a database-version change and are deleted in the transaction that ends the work. Pending Mousse refusal updates use `cursor:action-refusal::…`; their ids travel in `workRefusalIds` and they are removed when output or completion confirms delivery. Unconfirmed updates survive an interrupted continuation, as settled calls do. All of this state stays out of the memory export and is removed by the bot's purge. The numeric owner/message facts in a tombstoned card remain for refusal decisions. +The engine keeps its action-note and action-owner counters in `bot_memory_state` under `cursor:action-note:` and `cursor:action-owner:`. These survive restarts without a database-version change and are deleted in the transaction that ends the work. Pending Mousse refusal updates use `cursor:action-refusal::…`; their ids travel in `workRefusalIds` and they are removed when output or completion confirms delivery. Unconfirmed updates survive an interrupted continuation while work remains resumable (for example running, waiting or paused). They are deleted in the same transaction that makes the work terminal (`done`, `failed` or `cancelled`); startup also removes entries for already ended or missing work. All of this state stays out of the memory export and is removed by the bot's purge. The numeric owner/message facts in a tombstoned card remain for refusal decisions. + +Send refusals use these owner-facing sentences, preserved by the chat service: + +| Code | Sentence | +| --- | --- | +| `bot_action_expired` | This expired, so nothing was sent. | +| `bot_action_withdrawn` | No longer needed, so nothing was sent. | +| `bot_action_changed` | This changed since you saw it. Check it again before sending. | +| `bot_action_settled` | This was already answered. | +| `bot_action_gone` | This can't be sent any more. | +| `bot_action_paused` | `Resume to send this.` | +| `bot_action_unreachable` | ` couldn't be reached, so nothing was sent.` | Hidden argument values of four to eight characters require an adjacent character outside `[A-Za-z0-9_]` only at an edge whose own character is an ASCII letter, digit or underscore. Other edges require no boundary; longer values are replaced wherever they occur. Values shorter than four characters are left alone. Replacement runs in the server's own text before Mousse frames it, including JSON-escaped string echoes and numeric echoes. Credential masking still applies to the result. Transformed echoes (for example encoded, upper-case or truncated values) are not caught by this exact-value replacement. The stored result is capped at 64 KiB in total; images are omitted with a note, never cut into invalid data. Journal key-name masking applies only to work with a held action; other work keeps master's tool input capture. From 0a9c3528b6788bb5716afb5cfa4df0f5163e8640 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:46:53 +0530 Subject: [PATCH 77/84] docs(bots): keep service placeholders literal in the Send contract --- docs/bots.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/bots.md b/docs/bots.md index 2f0f778c32..e78f2e84fa 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -785,7 +785,7 @@ A held call is withdrawn, with executable arguments cleared in the same transact `/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, argument digest, card metadata, bot note and stored result with fixed forgotten markers. The owner-message and work-note counters in its card metadata stay, as do its call key, target, status and timestamps. A forgotten row no longer matches an argument digest; the call key still prevents a second execution. A late result cannot restore forgotten content. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. -An owner pause keeps a held card: a pause is not a refusal. Send says `Resume to send this.` while paused. Pausing also withdraws an approved call still waiting for its service; recovery while owner-paused settles it as not sent, and its outcome joins unread updates for Resume. An open card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline before accepting the approval. An accepted Send must reach the service within ten minutes of the owner's tap (`APPROVED_SEND_WINDOW_MS`, from `answered_at`), independent of the card's original deadline. The due timer includes that deadline, so restart, sleep or a missing listing cannot leave it waiting indefinitely. Before dispatch the row stays `approved`, with message text "Waiting for …"; execution changes it to `running`, "Sending…". Past the ten minutes it settles `failed`, clears executable arguments, and says " couldn't be reached, so nothing was sent." The work gets that outcome once through the ordered update list and may decide to ask again. This timeout is neither a declined nor an expired card: it does not count toward the three-card rule or the identical-call refusal. Once dispatched, a running call settles normally or becomes uncertain after restart. +An owner pause keeps a held card: a pause is not a refusal. Send says `Resume to send this.` while paused. Pausing also withdraws an approved call still waiting for its service; recovery while owner-paused settles it as not sent, and its outcome joins unread updates for Resume. An open card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline before accepting the approval. An accepted Send must reach the service within ten minutes of the owner's tap (`APPROVED_SEND_WINDOW_MS`, from `answered_at`), independent of the card's original deadline. The due timer includes that deadline, so restart, sleep or a missing listing cannot leave it waiting indefinitely. Before dispatch the row stays `approved`, with message text `Waiting for …`; execution changes it to `running`, "Sending…". Past the ten minutes it settles `failed`, clears executable arguments, and says ` couldn't be reached, so nothing was sent.` The work gets that outcome once through the ordered update list and may decide to ask again. This timeout is neither a declined nor an expired card: it does not count toward the three-card rule or the identical-call refusal. Once dispatched, a running call settles normally or becomes uncertain after restart. Forgetting a card blocks further calls of that tool in that piece of work until the owner writes or notes the work, including calls with changed arguments. Another tool is unaffected. This uses a content-free owner-removal marker and owner-input numbers in the tombstoned card metadata; no digest or call content is kept for it. From 36ebe0a4a1b9599ee46170c4e941912495f6791a Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:04:44 +0530 Subject: [PATCH 78/84] test(bots): forgetting settled cards preserves outcome and tool access --- tests/bots/botActions.test.ts | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index c01db1a2f1..9750e5bee4 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1802,3 +1802,39 @@ it.each(['open', 'approved'] as const)('R3-3 legacy #1340 %s cards withdraw on u expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) expect(t.calls).toEqual([]) }) + +it('R4-1 forgetting a sent card permits a different call of the same tool', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }); await flush() + const next = await start(f, t.workId, 2) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'sent card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + const result = await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'A different email' }, toolCallId: 'different-email', signal: new AbortController().signal }) + expect(result).not.toMatchObject({ isError: true }) + expect(f.store.all("SELECT id FROM bot_actions WHERE status = 'open'")).toHaveLength(1) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'done', args_digest: '[forgotten]', exec_args: null }) +}) + +it.each(['done', 'declined', 'tool_error', 'uncertain'] as const)('R4-1 forgetting untold %s content preserves the outcome', async outcome => { + const t = await setup(true) + if (outcome === 'tool_error') vi.spyOn(t.manager, 'callTool').mockResolvedValueOnce({ isError: true, content: [{ type: 'text', text: 'private tool answer' }] } as never) + if (outcome === 'uncertain') vi.spyOn(t.manager, 'callTool').mockRejectedValueOnce(new Error('connection lost')) + await t.call() + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: outcome === 'declined' ? 'not_now' : 'send' }) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'settled card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + await finish(f, t.work.payload); await flush() + const prompt = f.store.lastMainDispatch(t.workId)!.prompt.text + const line = outcome === 'done' ? 'Your owner sent it' : outcome === 'declined' ? 'Your owner chose not to send' : outcome === 'tool_error' ? 'The tool reported an error' : 'It could not be confirmed whether this went through' + expect(prompt).toContain(line) + expect(prompt).not.toContain('[forgotten]') + expect(prompt).not.toContain('private tool answer') + expect(prompt).not.toContain('Exact text') + expect(prompt).not.toContain('Your owner removed this request') +}) From 9c719ec41692c9498af462b5b64a20df9ea053ec Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:05:33 +0530 Subject: [PATCH 79/84] fix(bots): forgetting settled cards preserves their outcome and tool access --- src/mms/bots/actions/BotActions.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 224e921b67..7d4dc83ca5 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -160,15 +160,17 @@ export interface ActionRow { export function actionContinuation(action: Pick & Partial>): string { const result = action.result_json ? JSON.parse(action.result_json) as BotMcpCallOutcome : undefined if (JSON.parse(action.card_json ?? '{}').ownerRemoved) return 'Your owner removed this request. Do not ask for it again unless they write.' - if (result?.text === '[forgotten]') return 'The saved details of this outcome were removed.' + const forgotten = result?.text === '[forgotten]' + const card = JSON.parse(action.card_json ?? '{}') if (result?.notSentInTime) return `${result.text} Nothing left Mousse. Decide whether a new request is needed.` - const line = action.status === 'done' ? 'Your owner sent it. The tool answered:' + const line = action.status === 'done' ? forgotten ? 'Your owner sent it.' : 'Your owner sent it. The tool answered:' : action.status === 'declined' ? 'Your owner chose not to send this: carry on without it and say what you skipped.' : action.status === 'expired' ? 'This call expired. Nothing was sent; do not try the same call again without a new reason.' : action.status === 'withdrawn' ? 'No longer needed, so nothing was sent.' : action.status === 'uncertain' ? 'It could not be confirmed whether this went through: check before trying again.' - : result?.toolReportedError ? 'The tool reported an error. It may have done part of it: check before trying again. The tool answered:' + : result?.toolReportedError || card.toolReportedError ? 'The tool reported an error. It may have done part of it: check before trying again. The tool answered:' : 'Nothing was sent. The call failed:' + if (forgotten) return `${line} The saved details of this outcome were removed.` return `${line}${['done', 'failed', 'withdrawn', 'expired'].includes(action.status) ? `\n${result?.text ?? 'Carry on without it.'}` : ''}` } interface Host { @@ -204,7 +206,7 @@ export class BotActions { const pending = ['open', 'approved'].includes(String(action.status)) if (pending) this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'The request was forgotten. Nothing was sent.' }) this.forgetText(botId, String(action.id)) - if (action.message_id === messageId) this.host.store.run(`UPDATE bot_actions SET card_json = json_set(card_json, + if (pending && action.message_id === messageId) this.host.store.run(`UPDATE bot_actions SET card_json = json_set(card_json, '$.ownerRemoved', json('true'), '$.removedOwnerSeq', ?, '$.removedNoteSeq', ?) WHERE id = ?`, host.store.ownerLastWroteSeq(botId), Number(host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', botId, `cursor:action-note:${action.activation_id}`)?.value ?? 0), String(action.id)) if (!pending) continue @@ -219,6 +221,7 @@ export class BotActions { forgetText(botId: string, actionId?: string): void { this.host.store.run(`UPDATE bot_actions SET args_json = ?, args_digest = '[forgotten]', card_json = json_object('text', '[forgotten]', 'ownerSeq', COALESCE(json_extract(card_json, '$.ownerSeq'), 0), 'noteSeq', COALESCE(json_extract(card_json, '$.noteSeq'), 0), + 'toolReportedError', COALESCE(json_extract(result_json, '$.toolReportedError'), json_extract(card_json, '$.toolReportedError')), 'ownerRemoved', json_extract(card_json, '$.ownerRemoved'), 'removedOwnerSeq', json_extract(card_json, '$.removedOwnerSeq'), 'removedNoteSeq', json_extract(card_json, '$.removedNoteSeq')), bot_note = ?, result_json = ? WHERE bot_id = ? AND (? IS NULL OR id = ?)`, '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId, actionId ?? null, actionId ?? null) @@ -340,7 +343,7 @@ export class BotActions { if (moved && !pending.has(to)) { const action = this.get(id)! const row = this.host.store.activation(action.activation_id) - if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', result?.notSentInTime ? result.text : to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) + if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', result?.notSentInTime ? result.text : to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError || card.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) if (row?.endReason === 'approval') this.host.store.moveActivation(row.id, ['blocked'], 'blocked', { endReason: 'approval_answered' }) this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) } From a410bfdc99c7498e6653b5b63867a4dc9dc0d71d Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:06:36 +0530 Subject: [PATCH 80/84] fix(bots): keep message settlement independent of continuation metadata --- src/mms/bots/actions/BotActions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index 7d4dc83ca5..513af2b93f 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -343,7 +343,7 @@ export class BotActions { if (moved && !pending.has(to)) { const action = this.get(id)! const row = this.host.store.activation(action.activation_id) - if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', result?.notSentInTime ? result.text : to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError || card.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) + if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', result?.notSentInTime ? result.text : to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) if (row?.endReason === 'approval') this.host.store.moveActivation(row.id, ['blocked'], 'blocked', { endReason: 'approval_answered' }) this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) } From 11c97bd2fd6346ce27bcc1117a488327daf20a88 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:06:36 +0530 Subject: [PATCH 81/84] docs(bots): distinguish removing a pending request from forgetting a settled card --- docs/bots.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/bots.md b/docs/bots.md index e78f2e84fa..d790893012 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -781,13 +781,13 @@ Mousse makes the stored call once, without asking the model to recreate it. It c Settled actions join the same ordered, timed updates as waits, notes and answers. An action that caused the resume leads with its outcome. Its id is kept on the dispatch. Work's stored updates (waits, action outcomes, notes and answers, including work without wait history) count as told only when a dispatch carrying them produces model output or completes. Nonempty model text or thinking, or a model tool-call start, confirms delivery; merely preparing or starting a request does not. A failed, interrupted or replaced dispatch without that evidence leaves its updates pending, including after a time-limit card. A repeated update is acceptable; losing one is not. Carried/read (`read_at` and `applied_at`, plus the dispatch's `workDelivery`) keeps its existing meaning for late taps, Forget and compaction. Confirmation is a separate fact used only to decide what the next prompt carries: `unreadWorkAnswers`, `unreadWorkQuestion` and `unreadWorkNotes` include carried-but-unconfirmed updates without clearing those read markers. New carrying dispatches start with `prompt.workTold = pending`; `BotStore.confirmWorkDelivery` changes only that marker to `output` or `completed`. Reads happen before any confirmation write transaction, so a dispatch with no updates never opens one. A failed confirmation is caught and logged once per dispatch; it never fails the runtime's turn, and the next continuation can carry the update again. Completion of a new dispatch is confirmed explicitly; older rows with no marker also accept a completed stored outcome. Startup recovers a completion written before settlement. A usage retry carries the previous prompt's update ids, so it confirms only what that prompt contained. A database written by master as of #1339 has `workDelivery` for work that waited but no confirmation marker. If its carrying dispatch ended at a wall, a deadline or a turn cap, its notes and answers can be told once more after upgrading (twice is acceptable; losing them is not). Their carried/read behavior is preserved. Earlier databases with no such delivery ids gain no retrospective replay. Approval parks before a time or event wait and has no idle or week exemption. -A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An approved call recovered while its listing is unavailable waits for that listing to return. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting only its card withdraws and forgets the call, then continues the work told: "Your owner removed this request. Do not ask for it again unless they write." No tombstone text is read back to the work. Forgetting its request ends the work through the normal engine ending, with its journal entry and release of scratch, browser, progress and live status. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. +A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An accepted call waits for its service for at most ten minutes after the tap. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting only its card withdraws and forgets the call, then continues the work told: "Your owner removed this request. Do not ask for it again unless they write." No tombstone text is read back to the work. Forgetting its request ends the work through the normal engine ending, with its journal entry and release of scratch, browser, progress and live status. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. `/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, argument digest, card metadata, bot note and stored result with fixed forgotten markers. The owner-message and work-note counters in its card metadata stay, as do its call key, target, status and timestamps. A forgotten row no longer matches an argument digest; the call key still prevents a second execution. A late result cannot restore forgotten content. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. An owner pause keeps a held card: a pause is not a refusal. Send says `Resume to send this.` while paused. Pausing also withdraws an approved call still waiting for its service; recovery while owner-paused settles it as not sent, and its outcome joins unread updates for Resume. An open card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline before accepting the approval. An accepted Send must reach the service within ten minutes of the owner's tap (`APPROVED_SEND_WINDOW_MS`, from `answered_at`), independent of the card's original deadline. The due timer includes that deadline, so restart, sleep or a missing listing cannot leave it waiting indefinitely. Before dispatch the row stays `approved`, with message text `Waiting for …`; execution changes it to `running`, "Sending…". Past the ten minutes it settles `failed`, clears executable arguments, and says ` couldn't be reached, so nothing was sent.` The work gets that outcome once through the ordered update list and may decide to ask again. This timeout is neither a declined nor an expired card: it does not count toward the three-card rule or the identical-call refusal. Once dispatched, a running call settles normally or becomes uncertain after restart. -Forgetting a card blocks further calls of that tool in that piece of work until the owner writes or notes the work, including calls with changed arguments. Another tool is unaffected. This uses a content-free owner-removal marker and owner-input numbers in the tombstoned card metadata; no digest or call content is kept for it. +Forgetting a still-open or accepted waiting card blocks further calls of that tool in that piece of work until the owner writes or notes the work, including calls with changed arguments. Another tool is unaffected. Forgetting an already settled card only removes its content: it keeps its sent, not-sent, tool-error or uncertain outcome and does not block later calls. This uses a content-free owner-removal marker and owner-input numbers in the tombstoned card metadata; no digest or call content is kept for it. After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a Mousse update in the same ordered list preserves it for the next continuation. It is not an owner note: it neither steers the work as owner words nor starts another turn or report. Its delivery is confirmed on model output or completion, as for settled calls. Changed arguments may get a new review, but after three declined or expired cards for the same tool in the same work since its owner last wrote, further calls are refused until the owner writes or notes the work; the work is told to say what it needs in its report and wait. This uses the wake loop rule’s count and owner-input fact; the sentence says three cards were not sent, without treating expiry as an owner refusal. Any owner row, including a tapped answer to a question, lifts these refusals, as it does for wake loops. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. From 0166c4e9711d851e2131a59d8c06c70c76a0547c Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:08:37 +0530 Subject: [PATCH 82/84] test(bots): preserve master subagent rights and gate new tools after holds --- tests/bots/botActions.test.ts | 52 ++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 9750e5bee4..78e3242a75 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1,3 +1,4 @@ +import { BOT_SCHEDULE_ACT_TOOLS } from '../../src/shared/bots/personal/manifest' import { createBotMemoryAdmin } from '../../src/mms/bots/memory/admin' import { existsSync, mkdirSync, readFileSync } from 'node:fs' import { afterEach, expect, it, vi } from 'vitest' @@ -23,7 +24,7 @@ import { botFixture, createBot, finish, flush, start, type BotFixture } from './ let f: BotFixture const connections: McpManager[] = [] afterEach(async () => { f?.close(); await Promise.all(connections.splice(0).map(m => m.shutdown())) }) -async function setup(on: boolean, realServer = false, secondTool = false, threads = false) { +async function setup(on: boolean, realServer = false, secondTool = false, threads = false, ownerTools = false) { f = botFixture() const settings = getDefaultSettings() settings.experimental.botAsksFirst = on @@ -72,6 +73,13 @@ async function setup(on: boolean, realServer = false, secondTool = false, thread await f.bots.service.answer(botId, f.store.openAsks(botId)[0]!.id, 'allow') await finish(f, askingThreads.payload) } + if (ownerTools) for (const tool of ['secrets', 'schedules', 'quick_actions', 'shell']) { + const request = await f.bots.activate({ botId, input: `Allow ${tool}`, clientRequestId: `permission-${tool}` }) + const asking = await start(f, request.id) + asking.prepared.authority.escalate!({ permission: { tool }, reason: 'To help with this work' }) + await f.bots.service.answer(botId, f.store.openAsks(botId)[0]!.id, 'allow') + await finish(f, asking.payload) + } const grant = f.store.activeGrant(botId)! const manifest = { ...grant.manifest, mcp: server.tools.map(d => ({ serverId: 'mail', tool: d.toolName, ...(on ? { level: 'asks_first' as const } : {}) })) } f.store.approve(botId, botManifestDigest(manifest), manifest) @@ -962,14 +970,13 @@ it.each([true, false].flatMap(on => ['work', 'subagent'].map(caller => ({ on, ca const child = await start(f, t.workId, d.n) const authorities = [t.work.prepared.authority, child.prepared.authority] for (const bot of authorities) for (const name of ['thread_create', 'thread_send', 'thread_archive']) { - if (bot === t.work.prepared.authority) expect(botAppToolRefusal(bot, name, {})).toBeUndefined() - else expect(botAppToolRefusal(bot, name, {})).toBeTruthy() + expect(botAppToolRefusal(bot, name, {})).toBeUndefined() } if (caller === 'work') await t.call() else await callForBot({ bot: child.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'child-mail', signal: new AbortController().signal }) for (const bot of authorities) for (const name of ['thread_create', 'thread_send', 'thread_archive']) { const refused = botAppToolRefusal(bot, name, {}) - if (on || bot === child.prepared.authority) expect(refused).toBeTruthy() + if (on) expect(refused).toBeTruthy() else expect(refused).toBeUndefined() } expect(t.calls).toEqual(on ? [] : [t.args]) @@ -1838,3 +1845,40 @@ it.each(['done', 'declined', 'tool_error', 'uncertain'] as const)('R4-1 forgetti expect(prompt).not.toContain('Exact text') expect(prompt).not.toContain('Your owner removed this request') }) + + +it.each(['secrets', 'schedules', 'quick_actions'] as const)('R4-3 allowing %s from chat leaves the open card sendable once', async tool => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.service.chatSend({ botId: t.botId, text: 'Allow this permission for my work', clientRequestId: `allow-${tool}-with-card` }) + const chat = f.store.laneActivations(t.botId, 'chat', ['running'])[0]! + const asking = await start(f, chat.id) + asking.prepared.authority.escalate!({ permission: { tool }, reason: 'To help with this work' }) + await finish(f, asking.payload, 'completed', { text: 'May I use this permission?' }) + await f.bots.service.answer(t.botId, f.store.openAsks(t.botId)[0].id, 'allow') + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code: 'bot_action_settled' }) + expect(t.calls).toEqual([t.args]) +}) + +it.each([true, false].flatMap(on => ['work', 'subagent'].map(caller => ({ on, caller }))))('R4-3 new app-tool gates after $caller holds, switch=$on', async ({ on, caller }) => { + const t = await setup(on, false, false, true, true) + await t.work.prepared.authority.subagents!.start({ title: 'Helper', brief: 'Help with mail', toolCallId: 'helper' }) + const d = f.store.dispatches(t.workId).find(d => d.kind === 'subagent')! + const child = await start(f, t.workId, d.n) + const tools = ['secret_request', 'secret_run', 'schedule_list', ...BOT_SCHEDULE_ACT_TOOLS, 'create_quick_action', 'approval_respond'] + const authorities = [t.work.prepared.authority, child.prepared.authority] + const before = authorities.map(bot => tools.map(name => botAppToolRefusal(bot, name, {}))) + expect(before[0]).toEqual(tools.map(() => undefined)) + expect(before[1][tools.indexOf('approval_respond')]).toBeUndefined() + if (caller === 'work') await t.call() + else await callForBot({ bot: child.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'child-mail', signal: new AbortController().signal }) + for (const [i, bot] of authorities.entries()) for (const [j, name] of tools.entries()) { + const refused = botAppToolRefusal(bot, name, {}) + if (on) expect(refused, name).toMatch(i === 0 ? /held for your owner/ : /ended/) + else expect(refused, name).toBe(before[i][j]) + } + expect(t.calls).toEqual(on ? [] : [t.args]) +}) From e4258417873a97d743cf753c034f75695404228f Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:10:26 +0530 Subject: [PATCH 83/84] test(bots): seed held owner-tool grants for the dispatch gate cases --- tests/bots/botActions.test.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 78e3242a75..e7e4d550cd 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -73,12 +73,13 @@ async function setup(on: boolean, realServer = false, secondTool = false, thread await f.bots.service.answer(botId, f.store.openAsks(botId)[0]!.id, 'allow') await finish(f, askingThreads.payload) } - if (ownerTools) for (const tool of ['secrets', 'schedules', 'quick_actions', 'shell']) { - const request = await f.bots.activate({ botId, input: `Allow ${tool}`, clientRequestId: `permission-${tool}` }) - const asking = await start(f, request.id) - asking.prepared.authority.escalate!({ permission: { tool }, reason: 'To help with this work' }) - await f.bots.service.answer(botId, f.store.openAsks(botId)[0]!.id, 'allow') - await finish(f, asking.payload) + if (ownerTools) { + const current = f.bots.definitionOf(botId) + const held = f.store.activeGrant(botId)!.manifest + const manifest = { ...held, appTools: [...held.appTools, 'secrets', 'schedules', 'quick_actions'], tools: [...held.tools, 'shell' as const] } + const revision = f.host.definitions.publishRevision({ ...current, permissions: manifest }) + f.store.setPublished(botId, revision.revision!) + f.store.approve(botId, botManifestDigest(manifest), manifest) } const grant = f.store.activeGrant(botId)! const manifest = { ...grant.manifest, mcp: server.tools.map(d => ({ serverId: 'mail', tool: d.toolName, ...(on ? { level: 'asks_first' as const } : {}) })) } From 2339cdf21a50d7d9cbb4cf2e080f1874aa2a68f9 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:13:59 +0530 Subject: [PATCH 84/84] test(bots): forgetting an expired card keeps the existing unsent-card rule --- tests/bots/botActions.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index e7e4d550cd..4d8bc9d891 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1463,7 +1463,7 @@ it('R2-4 three expired cards refuse further calls without claiming the owner dec const memory = new BotMemoryStore({ db: f.store.db }) const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'declined call' })! memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) - expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('Your owner removed this request') }) + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(3) })