import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, readFileSync } from 'node:fs' import fs from 'node:fs' import { join } from 'node:path' import { assertReleasedPayloadSemantics } from '@deepseek-ai/dsh-session-format-v0-to-v1' import { resolveConfig } from '../src/host/config.ts' import type { HostAgent, HostPreStepDecision, HostUserMessage, } from '../src/host/dsh.ts' import { MnemonLifecycle, taskRoute } from '../src/host/lifecycle.ts' import { MemoryCompositionUnavailableError } from '../src/core/generation.ts' import { IdleReviewError, type IsolatedReviewRunner } from '../src/host/subagent.ts' import { LAYERED, cleanupLifecycleDirectories, completeDurableTurns, composedBy, directories, durableCandidate, fixture, registryWorkspace, requireDsh, userMessage, watermarkFile, workspaceTwo, writeWatermark, } from './fixtures/lifecycle.ts' afterAll(cleanupLifecycleDirectories) afterEach(() => vi.useRealTimers()) describe('Mnemon DSH lifecycle integration', () => { it('pauses idle review while confirmation is required and resumes after disabling it (#140)', async () => { vi.useFakeTimers() const config = resolveConfig({ confirmWrites: true, idleReviewMs: 5_000 }) const value = fixture(config) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(600_000) expect(value.coordinator.checkReviewAccess).not.toHaveBeenCalled() expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewBlocked: 'write-confirmation', idleReviewAttempts: 0, idleReviewPending: false }) config.confirmWrites = false await completeDurableTurns(value, 3, 4) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledTimes(1) expect(value.lifecycle.snapshot('session-1').current?.idleReviewBlocked).toBeUndefined() } finally { value.stop() } }) it('emits producer-owned guided context accepted by the published legacy Session migration', async () => { const value = fixture(resolveConfig({ recallMode: 'guided', writebackMode: 'guided' })) const decision = await value.preStep([userMessage()], 1) if (decision.kind !== 'enter') throw new Error('unexpected rejection') const messages = decision.messages.filter(message => message.source.kind === 'dsh-brain-mnemon') expect(messages.map(message => message.source.form)).toEqual(['instructions', 'memory-snapshot']) for (const message of messages) { expect(message.source).not.toHaveProperty('plugin') expect(() => assertReleasedPayloadSemantics({ type: 'user/message', seq: 0, time: 0, surfaceOp: 'append', data: JSON.parse(JSON.stringify(message)), }, 0)).not.toThrow() } value.stop() }) it('persists guided context through the published V4 codec that rejects plugin wrappers', async () => { const sessionApi = await import(requireDsh.resolve('@deepseek-ai/dsh-session')) const format = await import(requireDsh.resolve('@deepseek-ai/dsh-session-format-v3-to-v4')) const sessionId = sessionApi.SessionId('mnemon-source-contract-fixture') const session = sessionApi.Session.create(sessionId, undefined, { version: 4, id: sessionId, createdAt: 0, isSeeded: false, delegationDepth: 0, }) const value = fixture() const decision = await value.preStep([userMessage()], 1) if (decision.kind !== 'enter') throw new Error('unexpected rejection') const messages = decision.messages.slice(1) expect(messages.map(message => message.source.form)).toEqual(['instructions', 'memory-snapshot']) for (const message of messages) { const event = session.append('user/message', message, { surfaceOp: 'append' }) expect(format.releasedV4SessionFormatCodec.encodeEvent(event).data.source).toEqual(message.source) } const artifact = { header: session.header, inheritedEventCount: 0, events: session.snapshotEvents() } expect(() => format.restoreReleasedV4Artifact(artifact, sessionApi.KNOWN_SESSION_EVENT_TYPES)).not.toThrow() const oldWrapper = { ...artifact.events[0], data: { ...messages[0], source: { kind: 'plugin', plugin: 'dsh-brain-mnemon', form: 'instructions' } } } expect(() => format.restoreReleasedV4Artifact({ ...artifact, events: [oldWrapper] }, sessionApi.KNOWN_SESSION_EVENT_TYPES)) .toThrow('format v4 message requires a producer-owned source kind') value.stop() }) const ownSources = [ { kind: 'dsh-brain-mnemon', form: 'instructions' }, { kind: 'plugin:dsh-brain-mnemon', form: 'instructions' }, { kind: 'plugin', plugin: 'dsh-brain-mnemon', form: 'instructions' }, ] it.each(ownSources)('does not reinject context into a request already owned by Mnemon: %j', async source => { const value = fixture() const own = { ...userMessage('Previously queued Mnemon context'), source } expect(await value.preStep([own], 1)).toEqual({ kind: 'enter', messages: [own] }) value.stop() }) it.each(ownSources)('recognizes current, migrated and legacy attribution on the durable surface: %j', async source => { const value = fixture() value.events.push({ type: 'user/message', seq: 0, data: { ...userMessage('Retained Mnemon reminder'), source } }) ;(value.agent.session as { surface?: { nodes: readonly number[] } }).surface = { nodes: [0] } const decision = await value.preStep([userMessage()], 1) if (decision.kind !== 'enter') throw new Error('unexpected rejection') expect(decision.messages).toHaveLength(2) expect(decision.messages.some(message => message.source.form === 'instructions')).toBe(false) expect(decision.messages.at(-1)?.source.form).toBe('memory-snapshot') value.stop() }) it.each([ { kind: 'plugin', plugin: 'other-plugin' }, { kind: 'plugin:dsh-brain-mnemon-other' }, { kind: 'other-plugin', plugin: 'dsh-brain-mnemon' }, ])('does not let another producer suppress Mnemon context: %j', async source => { const value = fixture() const other = { ...userMessage('Unrelated producer context'), source } value.events.push({ type: 'user/message', seq: 0, data: other }) ;(value.agent.session as { surface?: { nodes: readonly number[] } }).surface = { nodes: [0] } const decision = await value.preStep([other], 1) if (decision.kind !== 'enter') throw new Error('unexpected rejection') expect(decision.messages[0]).toEqual(other) expect(decision.messages.slice(1).map(message => message.source)).toMatchObject([ { kind: 'dsh-brain-mnemon', form: 'instructions' }, { kind: 'dsh-brain-mnemon', form: 'memory-snapshot' }, ]) value.stop() }) it('appends a literal View snapshot after the complete shared-context batch without repeating it', async () => { const value = fixture() const text = 'Keep {{model}}, $HOME and as quoted memory text.' value.composableTurns.memoryWake.mockImplementation(viewId => ({ viewId, viewDigest: 'stable', text, sections: [] })) await value.assemblePrompt(1) const user = userMessage('Continue') const shared = { ...userMessage('Other plugin context'), source: { kind: 'plugin' as const, plugin: 'other-plugin' } } const decision = await value.agentListeners.get('agent/pre-step')!({ agent: value.agent, messages: [user], turn: 1, step: 1, signal: new AbortController().signal, }, async () => ({ kind: 'enter', messages: [user, shared] })) as HostPreStepDecision expect(value.agent.ctx.on).toHaveBeenCalledWith('agent/pre-step', expect.any(Function), { prepend: true }) expect(decision.kind === 'enter' && decision.messages.slice(0, 2)).toEqual([user, shared]) expect(decision.kind === 'enter' && decision.messages.at(-1)).toMatchObject({ content: [{ type: 'text', text }], source: { kind: 'dsh-brain-mnemon', form: 'memory-snapshot' }, }) if (decision.kind === 'enter') expect(decision.messages.at(-1)?.source).not.toHaveProperty('summary') await value.turnStopping(1) const next = await value.preStep([user], 2) expect(next.kind === 'enter' && next.messages).toEqual([user]) value.stop() }) it('re-composes the guided reminder after a rewind drops it from the surface', async () => { const value = fixture() const forms = (decision: HostPreStepDecision) => decision.kind === 'enter' ? decision.messages.map(message => message.source.form) : [] expect(forms(await value.preStep([userMessage()], 1))).toEqual([undefined, 'instructions', 'memory-snapshot']) // Still visible: a later first step must not duplicate it. The snapshot // rides along because this fixture's Wake text is turn-derived. expect(forms(await value.preStep([userMessage()], 2))).toEqual([undefined, 'memory-snapshot']) // Rewind replaces the surface and drops the reminder. The append-only event // log still contains it, which is why presence cannot be read from there. value.agent.session.surface = { nodes: [] } expect(forms(await value.preStep([userMessage()], 3))).toEqual([undefined, 'instructions', 'memory-snapshot']) }) it('pins one immutable Wake across every model step and releases it at the turn boundary', async () => { const value = fixture() // The snapshot is no longer a shared runtime-context contribution. expect(value.agentContexts).toHaveLength(0) const first = await value.preStep([userMessage('First step')], 7, 1) expect(value.promptAssemblies[0]?.contexts).toEqual([]) expect(first.kind === 'enter' && first.messages.at(-1)?.content).toEqual([{ type: 'text', text: 'Pinned Wake view-7' }]) expect(value.composableTurns.beginTurn).toHaveBeenCalledOnce() expect(value.runtimeSource.bindAgentRuntime).toHaveBeenCalledOnce() expect(value.composableTurns.beginTurn).toHaveBeenCalledWith('session-1:7', { storage: 'global', sessionId: 'session-1', agentId: 'session-1', }, 'agent.root-turn', expect.any(AbortSignal)) const continuation = await value.preStep([userMessage('Tool continuation')], 7, 2) expect(continuation.kind === 'enter' && continuation.messages).toHaveLength(1) expect(value.composableTurns.beginTurn).toHaveBeenCalledOnce() await value.turnStopping(7) expect(value.composableTurns.endTurn).toHaveBeenCalledWith('session-1:7') expect(value.composableTurns.turn('session-1:7')).toBeUndefined() const next = await value.preStep([userMessage('Next turn')], 8, 1) expect(next.kind === 'enter' && next.messages.at(-1)?.content).toEqual([{ type: 'text', text: 'Pinned Wake view-8' }]) expect(value.composableTurns.beginTurn).toHaveBeenCalledTimes(2) }) it('offers an active root Agent to standalone WebUI maintenance when no session is selected', () => { const value = fixture() expect(value.lifecycle.snapshot()).toMatchObject({ activeAgents: 1, sessionAvailable: true, taskAgentAvailable: true, current: { sessionId: 'session-1' }, }) expect(value.lifecycle.snapshot('missing-session')).toMatchObject({ sessionAvailable: true, current: { sessionId: 'session-1' }, }) }) it('pages old memory counters once and preserves them on repeated status refreshes (issue 632)', () => { const value = fixture() for (let seq = 0; seq < 2_000; seq++) value.events.push({ seq, type: seq === 5 ? 'tool/call' : 'fixture/padding', data: seq === 5 ? { turn: 1, name: 'mnemon_recall', callId: 'old' } : {} }) const snapshot = value.agent.session.snapshotEvents.bind(value.agent.session) const read = vi.spyOn(value.agent.session, 'snapshotEvents').mockImplementation((from, to) => { expect(from).toBeTypeOf('number'); expect(to).toBeTypeOf('number') expect(to! - from!).toBeLessThanOrEqual(256) return snapshot(from, to) }) expect(value.lifecycle.snapshot('session-1').current?.memoryToolCalls).toBe(1) read.mockClear() expect(value.lifecycle.snapshot('session-1').current?.memoryToolCalls).toBe(1) expect(read).not.toHaveBeenCalled() value.events.push({ seq: 2_000, type: 'tool/call', data: { turn: 2, name: 'mnemon_remember', callId: 'new' } }) expect(value.lifecycle.snapshot('session-1').current?.memoryToolCalls).toBe(2) expect(read.mock.calls).toEqual([[2_000, 2_001]]) value.stop() }) it('does not advertise task Agent actions when creation has no usable model route', async () => { const value = fixture(resolveConfig({ cliPath: '/fake/mnemon' }), { taskModelRoute: false }) expect(value.lifecycle.snapshot()).toMatchObject({ sessionAvailable: true, taskAgentAvailable: false }) await expect(value.lifecycle.maintainMetadata('', ['project'], workspaceTwo)).rejects.toThrow('no default provider/model') expect(value.createTaskAgent).not.toHaveBeenCalled() }) it('runs standalone maintenance under a disposable clean root Agent scoped to the selected workspace', async () => { const value = fixture() await value.lifecycle.maintainMetadata('', ['project'], workspaceTwo) await value.lifecycle.archiveDocument('', 'doc-1', workspaceTwo) expect(value.createTaskAgent).toHaveBeenCalledTimes(2) expect(value.createTaskAgent).toHaveBeenNthCalledWith(1, expect.objectContaining({ sessionId: expect.any(String), meta: { cwd: workspaceTwo, origin: 'subagent', agentPreset: 'default' }, agentOptions: { provider: 'deepseek', model: 'deepseek-chat' }, setup: expect.any(Function), signal: expect.any(AbortSignal), })) const metadataAgent = vi.mocked(value.coordinator.maintainMetadata).mock.calls[0]?.[0] as HostAgent expect(metadataAgent).not.toBe(value.agent) expect(metadataAgent.session.header?.cwd).toBe(workspaceTwo) expect(value.coordinator.archiveDocument).toHaveBeenCalledWith(expect.objectContaining({ session: expect.objectContaining({ header: { cwd: workspaceTwo, origin: 'subagent', agentPreset: 'default' } }) }), 'doc-1', expect.any(AbortSignal)) expect(value.defaultModel.currentSelection).toHaveBeenCalledTimes(2) expect(value.agentPresets.resolve).toHaveBeenCalledTimes(2) expect(value.agentPresets.mount).toHaveBeenCalledTimes(2) expect(value.disposedTaskAgents).toHaveLength(2) expect(value.lifecycle.snapshot()).toMatchObject({ activeAgents: 1, taskAgentAvailable: true }) }) // Every way the Host starts a task Agent. The maintenance runner also serves memory reconciliation and the // runtime memory capacity maintenance that condenses a full user profile before Save to memory adds to it. const taskAgentPaths: ReadonlyArray Promise]> = [ ['runtime memory capacity maintenance and memory reconciliation', lifecycle => lifecycle.runRuntimeMaintenanceTask({ storage: 'workspace', workspaceId: workspaceTwo, sessionId: 'session-1' }, new AbortController().signal, async () => 'maintained')], ['Save to memory', lifecycle => lifecycle.superviseTask('session-1', 'Keep the release checklist durable.', 'message-1', workspaceTwo)], ['Ask Agent', lifecycle => lifecycle.answerTask('', 'Which database?', [], workspaceTwo)], ['a Document write that makes room', lifecycle => lifecycle.mutateDocumentTask('session-1', { action: 'create', title: 'Release', content: 'Checklist.' }, workspaceTwo)], ['Document archive', lifecycle => lifecycle.archiveDocument('', 'doc-1', workspaceTwo)], ['a new Memory Space Provider', lifecycle => lifecycle.placeProviderTask('', { name: 'Release', description: 'Release decisions.' }, { prompt: 'Choose one.', candidates: [], appliedRules: [], selectorBrief: '' }, workspaceTwo)], ['Tidy names and descriptions', lifecycle => lifecycle.maintainMetadata('', ['project'], workspaceTwo)], ] it.each(taskAgentPaths)('creates the task Agent for %s with the subagent origin and no conversation lineage (#435)', async (_path, run) => { const value = fixture() await run(value.lifecycle) // DSH's sidebar and ACP session list leave out a session with this origin, the one DSH gives its own subagents. expect(value.createTaskAgent).toHaveBeenCalledOnce() expect(value.createTaskAgent.mock.calls[0]![0].meta).toEqual({ cwd: workspaceTwo, origin: 'subagent', agentPreset: 'default' }) expect(value.disposedTaskAgents).toHaveLength(1) }) it.each([false, true])('runs Runtime maintenance with clean workspace ownership and disposes it on failure=%s', async failed => { const value = fixture() const operation = vi.fn(async (agent: HostAgent) => { expect(agent).not.toBe(value.agent) expect(agent.session.header?.cwd).toBe(workspaceTwo) expect(agent.session.snapshotEvents()).toEqual([]) if (failed) throw new Error('model unavailable') return 'maintained' }) const result = value.lifecycle.runRuntimeMaintenanceTask({ storage: 'workspace', workspaceId: workspaceTwo, sessionId: 'session-1' }, new AbortController().signal, operation) if (failed) await expect(result).rejects.toThrow('model unavailable') else await expect(result).resolves.toBe('maintained') expect(value.createTaskAgent).toHaveBeenCalledOnce() expect(value.disposedTaskAgents).toHaveLength(1) }) it('falls back to the workspace registry when a task Agent has no workspace', async () => { const value = fixture(undefined, { workspaces: [{ path: registryWorkspace }] }) await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global' }, new AbortController().signal, async agent => agent.session.header?.cwd) expect(value.createTaskAgent).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: registryWorkspace, origin: 'subagent', agentPreset: 'default' } })) }) it('keeps a workspace whose folder is gone as the task cwd, and works from an existing one where DSH checks', async () => { const gone = join(directories, 'deleted-project') const workingDirectory = { set: vi.fn(async (_agent: HostAgent, path: string) => path) } const value = fixture(undefined, { workspaces: [{ path: join(directories, 'also-deleted') }, { path: registryWorkspace }], workingDirectory }) // Mnemon reads the workspace's memory from the cwd, so it stays the requested one. const cwd = await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'workspace', workspaceId: gone }, new AbortController().signal, async agent => agent.session.header?.cwd) expect(cwd).toBe(gone) expect(value.createTaskAgent).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: gone, origin: 'subagent', agentPreset: 'default' } })) expect(workingDirectory.set).toHaveBeenCalledWith(expect.objectContaining({ session: expect.objectContaining({ header: { cwd: gone, origin: 'subagent', agentPreset: 'default' } }) }), registryWorkspace, expect.any(AbortSignal)) await value.lifecycle.archiveDocument('', 'doc-1', gone) expect(workingDirectory.set).toHaveBeenLastCalledWith(expect.anything(), registryWorkspace, expect.any(AbortSignal)) expect(value.coordinator.archiveDocument).toHaveBeenCalledWith(expect.objectContaining({ session: expect.objectContaining({ header: { cwd: gone, origin: 'subagent', agentPreset: 'default' } }) }), 'doc-1', expect.any(AbortSignal)) }) it('works from the Host directory when no workspace folder exists, and leaves an existing workspace alone', async () => { const gone = join(directories, 'deleted-project') const workingDirectory = { set: vi.fn(async (_agent: HostAgent, path: string) => path) } const value = fixture(undefined, { workspaces: [{ path: join(directories, 'deleted-registry') }], workingDirectory }) expect(await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'workspace', workspaceId: gone }, new AbortController().signal, async agent => agent.session.header?.cwd)).toBe(gone) expect(workingDirectory.set).toHaveBeenCalledWith(expect.anything(), process.cwd(), expect.any(AbortSignal)) workingDirectory.set.mockClear() expect(await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'workspace', workspaceId: workspaceTwo }, new AbortController().signal, async agent => agent.session.header?.cwd)).toBe(workspaceTwo) expect(workingDirectory.set).not.toHaveBeenCalled() }) it('keeps a missing workspace as the task cwd on a DSH without the working-directory service', async () => { const gone = join(directories, 'deleted-project') const value = fixture(undefined, { workspaces: [{ path: registryWorkspace }] }) expect(await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'workspace', workspaceId: gone }, new AbortController().signal, async agent => agent.session.header?.cwd)).toBe(gone) }) it('keeps the first registered workspace for a task without one, and works from an existing folder when it is gone', async () => { const firstRegistered = join(directories, 'deleted-registry') const workingDirectory = { set: vi.fn(async (_agent: HostAgent, path: string) => path) } const value = fixture(undefined, { workspaces: [{ path: firstRegistered }, { path: registryWorkspace }], workingDirectory }) const cwd = await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global' }, new AbortController().signal, async agent => agent.session.header?.cwd) expect(cwd).toBe(firstRegistered) expect(workingDirectory.set).toHaveBeenCalledWith(expect.anything(), registryWorkspace, expect.any(AbortSignal)) }) it('falls back to the Host working directory when no workspace is known at all', async () => { const value = fixture() const cwd = await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global' }, new AbortController().signal, async agent => agent.session.header?.cwd) expect(cwd).toBe(process.cwd()) expect(value.createTaskAgent).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: process.cwd(), origin: 'subagent', agentPreset: 'default' } })) }) it('uses a fixed Provider and model for independent task Agents when configured', async () => { const value = fixture(resolveConfig({ cliPath: '/fake/mnemon', taskAgentModel: { mode: 'fixed', provider: 'openai', model: 'gpt-5' }, })) await value.lifecycle.maintainMetadata('', ['project'], workspaceTwo) expect(value.createTaskAgent).toHaveBeenCalledWith(expect.objectContaining({ agentOptions: { provider: 'openai', model: 'gpt-5', maxTokens: undefined }, })) expect(value.defaultModel.currentSelection).not.toHaveBeenCalled() }) it('lists model Providers concurrently and reports the effective independent task route', async () => { const value = fixture() await expect(value.lifecycle.taskAgentModels()).resolves.toEqual({ effective: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, defaultSelection: { provider: 'deepseek', model: 'deepseek-chat' }, inherited: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, groups: [ { id: 'deepseek', name: 'DeepSeek', models: [{ id: 'deepseek-chat', name: 'DeepSeek Chat' }] }, { id: 'openai', name: 'OpenAI', models: [{ id: 'gpt-5', name: 'GPT-5', description: 'General reasoning' }] }, ], failures: [], }) expect(value.llm.listModels).toHaveBeenCalledTimes(2) }) it('preserves first-party model modality metadata in the task Agent catalog', async () => { const value = fixture() value.llm.listProviders.mockReturnValue([{ id: 'deepseek-official', name: 'DeepSeek' }]) value.llm.listModels.mockResolvedValue([{ id: 'deepseek-v4-flash-vision-exp', name: 'DeepSeek-V4-Flash-Vision-Exp', inputModalities: ['text', 'image'], }]) await expect(value.lifecycle.taskAgentModels()).resolves.toMatchObject({ groups: [{ id: 'deepseek-official', models: [{ id: 'deepseek-v4-flash-vision-exp', inputModalities: ['text', 'image'], }], }], }) }) it('resolves the inherited task route without loading the full model directory', async () => { const value = fixture() await expect(value.lifecycle.taskAgentModels(false)).resolves.toEqual({ effective: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, defaultSelection: { provider: 'deepseek', model: 'deepseek-chat' }, inherited: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, groups: [], failures: [], }) expect(value.llm.listProviders).not.toHaveBeenCalled() expect(value.llm.listModels).not.toHaveBeenCalled() }) it('keeps the DSH new-session default for an inherited route that does not follow its conversation', async () => { const value = fixture(undefined, { sessionModel: { provider: 'ai', model: 'space-bunny' } }) // The catalog still names the conversation's route, so a page can say what the switch would change. await expect(value.lifecycle.taskAgentModels(false, 'session-1')).resolves.toEqual({ effective: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, defaultSelection: { provider: 'deepseek', model: 'deepseek-chat' }, session: { provider: 'ai', model: 'space-bunny' }, inherited: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, groups: [], failures: [], }) await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global', sessionId: 'session-1' }, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenCalledWith(expect.objectContaining({ agentOptions: { provider: 'deepseek', model: 'deepseek-chat', maxTokens: undefined }, })) }) it('preserves the default model reasoning effort for clean skill and maintenance tasks', async () => { const value = fixture(undefined, { conversationOptions: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' } }) value.defaultModel.currentSelection.mockReturnValue({ provider: 'openai', model: 'gpt-5', reasoningEffort: 'low' }) await value.lifecycle.runSkillTask(workspaceTwo, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'openai', model: 'gpt-5', reasoningEffort: 'low', maxTokens: undefined }, })) await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global', sessionId: 'session-1' }, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'openai', model: 'gpt-5', reasoningEffort: 'low', maxTokens: undefined }, })) }) it('runs a skill on its explicit model without the inherited reasoning effort', async () => { const value = fixture(undefined, { conversationOptions: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' } }) value.defaultModel.currentSelection.mockReturnValue({ provider: 'openai', model: 'gpt-5', reasoningEffort: 'max' }) const route = { provider: 'chosen-provider', model: 'chosen-model' } await value.lifecycle.runSkillTask(workspaceTwo, new AbortController().signal, async task => { expect(taskRoute(task)).toEqual(route) }, route) expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { ...route, maxTokens: undefined }, })) }) it('preserves the fallback Agent creation effort when the default model service is unavailable', async () => { const value = fixture(undefined, { conversationOptions: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'adapter-defined' } }) value.defaultModel.currentSelection.mockImplementation(() => { throw new Error('default model unavailable') }) await value.lifecycle.runSkillTask(workspaceTwo, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'adapter-defined', maxTokens: undefined }, })) }) it.each([undefined, '', ' '])('does not borrow a conversation effort when the default selection has %j', async reasoningEffort => { const value = fixture(undefined, { conversationOptions: { provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' } }) value.defaultModel.currentSelection.mockReturnValue({ provider: 'openai', model: 'gpt-5', ...(reasoningEffort === undefined ? {} : { reasoningEffort }) }) await value.lifecycle.runSkillTask(workspaceTwo, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'openai', model: 'gpt-5', maxTokens: undefined }, })) }) it('does not copy default reasoning effort onto a fixed task model', async () => { const value = fixture(resolveConfig({ cliPath: '/fake/mnemon', taskAgentModel: { mode: 'fixed', provider: 'openai', model: 'gpt-5' } })) value.defaultModel.currentSelection.mockReturnValue({ provider: 'deepseek', model: 'deepseek-chat', reasoningEffort: 'high' }) await value.lifecycle.runSkillTask(workspaceTwo, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'openai', model: 'gpt-5', maxTokens: undefined }, })) expect(value.defaultModel.currentSelection).not.toHaveBeenCalled() }) it('omits coding presets and confines skill task Agents to read-only sandbox and never approval (#727)', async () => { const value = fixture() const appended: Array<{ type: string; data: unknown }> = [] value.createTaskAgent.mockImplementationOnce(async taskOptions => { const taskCtx = { get: (name: string) => name === 'sandboxPolicy' ? { overrideOf: () => 'danger-full-access' } : name === 'approval' ? { overrideOf: () => 'ask' } : undefined, on: vi.fn(() => () => {}), effect: vi.fn((callback: () => (() => unknown) | void) => { const cleanup = callback() return () => cleanup?.() }), } const taskAgent = { id: taskOptions.sessionId, status: 'idle' as const, ...(taskOptions.agentOptions === undefined ? {} : { options: taskOptions.agentOptions }), session: { header: taskOptions.meta ?? {}, snapshotEvents: () => [], eventAt: () => undefined, surface: { nodes: [] }, append: (type: string, data: unknown) => { appended.push({ type, data }) }, }, ctx: taskCtx as unknown as HostAgent['ctx'], followup: vi.fn(), steer: vi.fn(), inject: vi.fn(), cancel: vi.fn(), } await taskOptions.setup?.(taskCtx as never, taskAgent) return { agent: taskAgent, dispose: vi.fn(async () => {}) } }) await value.lifecycle.runSkillTask(workspaceTwo, new AbortController().signal, async () => 'done') expect(value.agentPresets.resolve).not.toHaveBeenCalled() expect(value.agentPresets.mount).not.toHaveBeenCalled() expect(value.createTaskAgent.mock.calls[0]![0].meta).toEqual({ cwd: workspaceTwo, origin: 'subagent' }) expect(appended).toEqual([ { type: 'sandbox/mode', data: { mode: 'read-only', source: 'delegation' } }, { type: 'approval/policy', data: { policy: 'never', source: 'delegation' } }, ]) }) it('follows the conversation that asked for the work once its inherited route is switched to follow it', async () => { const value = fixture(resolveConfig({ cliPath: '/fake/mnemon', taskAgentModel: { mode: 'inherit', followConversation: true } }), { sessionModel: { provider: 'ai', model: 'space-bunny', reasoningEffort: 'high' } }) await expect(value.lifecycle.taskAgentModels(false, 'session-1')).resolves.toEqual({ effective: { provider: 'ai', model: 'space-bunny', source: 'session' }, defaultSelection: { provider: 'deepseek', model: 'deepseek-chat' }, session: { provider: 'ai', model: 'space-bunny' }, inherited: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, groups: [], failures: [], }) // The maintenance a write of that conversation needs, and a task its page asks for, both take its // route as DSH gives it to the conversation's own delegated work, reasoning effort included. await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global', sessionId: 'session-1' }, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'ai', model: 'space-bunny', reasoningEffort: 'high', maxTokens: undefined }, })) await value.lifecycle.maintainMetadata('session-1', ['project'], workspaceTwo) expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'ai', model: 'space-bunny', reasoningEffort: 'high', maxTokens: undefined }, })) }) it('never borrows another open conversation\'s model, and takes a conversation\'s creation route before its first request', async () => { const follow = resolveConfig({ cliPath: '/fake/mnemon', taskAgentModel: { mode: 'inherit', followConversation: true } }) const value = fixture(follow, { sessionModel: { provider: 'ai', model: 'space-bunny' } }) const dshDefault = { effective: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, defaultSelection: { provider: 'deepseek', model: 'deepseek-chat' }, inherited: { provider: 'deepseek', model: 'deepseek-chat', source: 'dsh-default' }, groups: [], failures: [], } // session-1 is open with a route of its own; a conversation that is not, and a caller without one, keep the default. await expect(value.lifecycle.taskAgentModels(false, 'session-2')).resolves.toEqual(dshDefault) await expect(value.lifecycle.taskAgentModels(false)).resolves.toEqual(dshDefault) await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global', sessionId: 'session-2' }, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'deepseek', model: 'deepseek-chat', maxTokens: undefined }, })) await value.lifecycle.runRuntimeMaintenanceTask({ storage: 'global' }, new AbortController().signal, async () => 'done') expect(value.createTaskAgent).toHaveBeenLastCalledWith(expect.objectContaining({ agentOptions: { provider: 'deepseek', model: 'deepseek-chat', maxTokens: undefined }, })) // Before its first request, DSH gives a conversation's delegated work the route it was created with; so does the switch. const fresh = fixture(follow, { conversationOptions: { provider: 'ai', model: 'starter' } }) await expect(fresh.lifecycle.taskAgentModels(false, 'session-1')).resolves.toMatchObject({ effective: { provider: 'ai', model: 'starter', source: 'session' }, session: { provider: 'ai', model: 'starter' }, }) // Half a request header is no route at all. await expect(fixture(follow, { sessionModel: { provider: ' ', model: 'space-bunny' } }).lifecycle.taskAgentModels(false, 'session-1')).resolves.toEqual(dshDefault) }) it.each([3_600, 5_000])('waits for a first-party network model directory returning after %i ms', async delay => { vi.useFakeTimers() const value = fixture() value.llm.listProviders.mockReturnValue([{ id: 'deepseek-official', name: 'DeepSeek' }, { id: 'openai', name: 'OpenAI' }]) value.llm.listModels.mockImplementation(async provider => { if (provider === 'deepseek-official') await new Promise(resolve => setTimeout(resolve, delay)) return [{ id: provider === 'deepseek-official' ? 'deepseek-flash' : 'gpt-5', name: provider }] }) const pending = value.lifecycle.taskAgentModels() await vi.advanceTimersByTimeAsync(delay) await expect(pending).resolves.toMatchObject({ groups: [{ id: 'deepseek-official', models: [{ id: 'deepseek-flash' }] }, { id: 'openai', models: [{ id: 'gpt-5' }] }], failures: [], }) expect(value.llm.listModels).toHaveBeenCalledTimes(2) expect(vi.getTimerCount()).toBe(0) }) it('preserves a first-party directory failure within the upstream request budget', async () => { vi.useFakeTimers() const value = fixture() value.llm.listProviders.mockReturnValue([{ id: 'deepseek-official', name: 'DeepSeek' }]) value.llm.listModels.mockImplementation(async () => { await new Promise(resolve => setTimeout(resolve, 5_000)) throw new Error('provider model directory request timed out') }) const pending = value.lifecycle.taskAgentModels() await vi.advanceTimersByTimeAsync(5_000) await expect(pending).resolves.toMatchObject({ groups: [], failures: [{ id: 'deepseek-official', message: 'provider model directory request timed out' }] }) expect(vi.getTimerCount()).toBe(0) }) it('still bounds a first-party directory that never settles', async () => { vi.useFakeTimers() const value = fixture() value.llm.listProviders.mockReturnValue([{ id: 'deepseek-official', name: 'DeepSeek' }, { id: 'openai', name: 'OpenAI' }]) value.llm.listModels.mockImplementation(async provider => provider === 'deepseek-official' ? await new Promise(() => {}) : [{ id: 'gpt-5', name: 'GPT-5' }]) const pending = value.lifecycle.taskAgentModels() await vi.advanceTimersByTimeAsync(6_000) await expect(pending).resolves.toMatchObject({ groups: [{ id: 'openai', models: [{ id: 'gpt-5' }] }], failures: [{ id: 'deepseek-official', message: 'model directory timed out after 6 seconds' }], }) expect(vi.getTimerCount()).toBe(0) }) it('isolates a stalled Provider while keeping the rest of the model catalog usable', async () => { vi.useFakeTimers() const value = fixture() value.llm.listModels.mockImplementation(async provider => provider === 'openai' ? await new Promise(() => {}) : [{ id: 'deepseek-chat', name: 'DeepSeek Chat' }]) const pending = value.lifecycle.taskAgentModels() await vi.advanceTimersByTimeAsync(3_000) await expect(pending).resolves.toMatchObject({ groups: [{ id: 'deepseek', models: [{ id: 'deepseek-chat' }] }], failures: [{ id: 'openai', message: 'model directory timed out after 3 seconds' }], }) }) it('runs Agent Query synthesis under a disposable clean root Agent', async () => { const value = fixture() await value.lifecycle.answerTask('', 'Which database?', [], workspaceTwo) expect(value.createTaskAgent).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: workspaceTwo, origin: 'subagent', agentPreset: 'default' }, agentOptions: { provider: 'deepseek', model: 'deepseek-chat' }, })) expect(value.coordinator.answer).toHaveBeenCalledWith(expect.objectContaining({ options: { provider: 'deepseek', model: 'deepseek-chat' }, session: expect.objectContaining({ header: expect.objectContaining({ cwd: workspaceTwo }) }), }), 'Which database?', [], expect.any(AbortSignal)) expect(value.disposedTaskAgents).toHaveLength(1) }) it('adds one durable optional reminder without repeating it into later turn history', async () => { const value = fixture() const prompt = userMessage('Aster 发布前需要检查哪些事项?') const decision = await value.preStep([prompt], 1) expect(decision).toMatchObject({ kind: 'enter' }) if (decision.kind !== 'enter') throw new Error('unexpected rejection') expect(decision.messages).toHaveLength(3) expect(decision.messages[1]?.source).toMatchObject({ kind: 'dsh-brain-mnemon', form: 'instructions' }) expect(decision.messages[1]?.content[0]?.text).toBe('[MNEMON] Use mnemon_view_route only when relevant evidence is missing. Use mnemon_view_action only for an intended memory change; require a write receipt. Use only ids offered by the current View and follow each Source\'s semantics. Otherwise use none.') expect(value.coordinator.recall).not.toHaveBeenCalled() const second = await value.preStep([userMessage('Second turn')], 2) if (second.kind !== 'enter') throw new Error('unexpected rejection') // The reminder is not repeated. The snapshot is present because this // fixture derives Wake text from the turn, so turn 2 is a new revision. expect(second.messages).toHaveLength(2) expect(second.messages.some(message => (message.source as { form?: string }).form === 'instructions')).toBe(false) expect(second.messages.at(-1)?.source).toMatchObject({ kind: 'dsh-brain-mnemon', form: 'memory-snapshot' }) expect(value.coordinator.recall).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').counters).toMatchObject({ primes: 1, recallCues: 1, writebackCues: 1 }) }) it('keeps durable image references intact while scoring only text from a multimodal prompt', async () => { const value = fixture() const prompt: HostUserMessage = { id: crypto.randomUUID(), role: 'user', content: [ { type: 'image', attachment: { attachmentId: 'image:sha256:fixture', mediaType: 'image/png', bytes: 128, width: 16, height: 8, name: 'architecture.png', }, }, { type: 'text', text: 'Inspect this diagram.' }, ], source: { kind: 'user' }, } const decision = await value.preStep([prompt], 1) await value.turnStopping(1) if (decision.kind !== 'enter') throw new Error('unexpected rejection') expect(decision.messages[0]).toBe(prompt) expect(decision.messages[0]?.content[0]).toEqual(prompt.content[0]) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity).toMatchObject({ totalUserTextLength: 'Inspect this diagram.'.length, turnCount: 1, }) }) it('restores a persisted session budget before scheduling another idle review', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'watermark-')) writeWatermark(directory, { version: 1, sessionId: 'session-1', attempts: 2, lastReviewAttemptAt: Date.now() - 60_000 }) const value = fixture(resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, maxPerSession: 2 } } as never), { directory }) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(600_000) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 2, idleReviewPending: false }) expect(value.coordinator.review).not.toHaveBeenCalled() } finally { value.stop() } }) it('does not spin timers when a backwards clock leaves a far-future cooling watermark', async () => { vi.useFakeTimers() vi.setSystemTime(1_000) const directory = mkdtempSync(join(directories, 'future-watermark-')) writeWatermark(directory, { version: 1, sessionId: 'session-1', attempts: 1, lastReviewAttemptAt: 3_000_000_000_000 }) const timer = vi.spyOn(globalThis, 'setTimeout') const value = fixture(resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true } }), { directory }) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(1_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) expect(timer).toHaveBeenCalledTimes(1) } finally { value.stop(); timer.mockRestore() } }) it('retains cooling time and attempts across Agent recreation without running catch-up work', async () => { vi.useFakeTimers() vi.setSystemTime(1_000_000) const directory = mkdtempSync(join(directories, 'restart-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, minIntervalMs: 30_000, maxPerSession: 2 } }) const first = fixture(config, { directory }) await completeDurableTurns(first) await vi.advanceTimersByTimeAsync(5_000) expect(first.coordinator.review).toHaveBeenCalledOnce() first.stop() const resumed = fixture(config, { directory }) try { expect(resumed.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 1, idleReviewPending: false, idleReviewWatermark: { state: 'ready', restoredAttempts: 1 } }) await vi.advanceTimersByTimeAsync(10_000) expect(resumed.coordinator.review).not.toHaveBeenCalled() await completeDurableTurns(resumed) await vi.advanceTimersByTimeAsync(19_999) expect(resumed.coordinator.review).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(1) expect(resumed.coordinator.review).toHaveBeenCalledOnce() expect(resumed.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(2) } finally { resumed.stop() } }) it('isolates persistent budgets by parent id and actual runtime root', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'identity-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, maxPerSession: 1 } }) const first = fixture(config, { directory }) await completeDurableTurns(first) await vi.advanceTimersByTimeAsync(5_000); first.stop() for (const options of [{ directory, sessionId: 'new-parent' }, { directory: join(directory, 'other-root') }]) { const value = fixture(config, options) try { expect(value.lifecycle.snapshot(options.sessionId ?? 'session-1').current?.idleReviewAttempts).toBe(0) await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() } finally { value.stop() } } }) it('drops the previous root snapshot when the replacement root watermark is corrupt', () => { const directory = mkdtempSync(join(directories, 'root-snapshot-')) const other = join(directory, 'other-root') writeWatermark(directory, { version: 1, sessionId: 'session-1', attempts: 1, lastReviewAttemptAt: 1_000 }) writeWatermark(other, '{') const value = fixture(resolveConfig({ idleReview: { persistWatermark: true } }), { directory }) try { expect(value.lifecycle.snapshot('session-1').current?.idleReviewWatermark?.restoredAttempts).toBe(1) const graph = value.runtimeSource.forAgent(value.agent) value.runtimeSource.forAgent.mockReturnValue({ ...graph, directory: other }) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 0, idleReviewWatermark: { state: 'error', restoredAttempts: 0 } }) } finally { value.stop() } }) it('keeps normal turns available while corrupt watermarks or a missing graph root pause automatic review', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'corrupt-')) writeWatermark(directory, '{private-session-content') for (const options of [{ directory }, {}]) { const value = fixture(resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true } }), options) try { for (let turn = 1; turn <= 2; turn++) { expect((await value.preStep([durableCandidate(300)], turn)).kind).toBe('enter') await value.turnStopping(turn) } await vi.advanceTimersByTimeAsync(600_000) expect(value.coordinator.review).not.toHaveBeenCalled() const state = value.lifecycle.snapshot('session-1').current expect(state).toMatchObject({ idleReviewWatermark: { state: 'error' }, idleReviewPending: false }) expect(state?.idleReviewWatermark?.error).not.toContain(directory) expect(state?.idleReviewWatermark?.error).not.toContain('private-session-content') } finally { value.stop() } } }) it('recovers a persisted review budget on a later turn after lock contention (#635)', async () => { vi.useFakeTimers() vi.setSystemTime(1_000_000) const directory = mkdtempSync(join(directories, 'busy-watermark-')) const saved = { version: 1, sessionId: 'session-1', attempts: 1, lastReviewAttemptAt: Date.now() - 60_000 } const filename = writeWatermark(directory, saved) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, minIntervalMs: 5_000, maxPerSession: 2 } }) const value = fixture(config, { directory }) const lock = filename + '.lock' try { fs.mkdirSync(lock) await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(JSON.parse(readFileSync(filename, 'utf8'))).toEqual(saved) expect(fs.existsSync(lock)).toBe(true) expect(value.lifecycle.snapshot('session-1').current?.idleReviewWatermark).toMatchObject({ state: 'error', error: expect.stringContaining('(busy)'), }) fs.rmdirSync(lock) await vi.advanceTimersByTimeAsync(600_000) expect(value.coordinator.review).not.toHaveBeenCalled() await completeDurableTurns(value, 3, 4) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() expect(JSON.parse(readFileSync(filename, 'utf8')).attempts).toBe(2) expect(value.lifecycle.snapshot('session-1').current?.idleReviewWatermark).toMatchObject({ state: 'ready', restoredAttempts: 1, maxPerSession: 2, }) await completeDurableTurns(value, 5, 6) await vi.advanceTimersByTimeAsync(600_000) expect(value.coordinator.review).toHaveBeenCalledOnce() } finally { value.stop() } }) it('loads repaired state on the next turn without discarding its quota (#635)', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'repaired-watermark-')) const filename = writeWatermark(directory, 'invalid state') const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, maxPerSession: 1 } }) const value = fixture(config, { directory }) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(600_000) expect(value.coordinator.checkReviewAccess).not.toHaveBeenCalled() expect(readFileSync(filename, 'utf8')).toBe('invalid state') const repaired = { version: 1, sessionId: 'session-1', attempts: 1, lastReviewAttemptAt: Date.now() - 60_000 } writeWatermark(directory, repaired) await completeDurableTurns(value, 3, 4) await vi.advanceTimersByTimeAsync(600_000) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 1, idleReviewPending: false, idleReviewWatermark: { state: 'ready', restoredAttempts: 1 }, }) expect(value.coordinator.review).not.toHaveBeenCalled() expect(JSON.parse(readFileSync(filename, 'utf8'))).toEqual(repaired) } finally { value.stop() } }) it('starts no child when atomic persistence fails and leaves the old budget intact', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'write-failure-')) const previous = JSON.stringify({ version: 1, sessionId: 'session-1', attempts: 0, lastReviewAttemptAt: null }) const filename = writeWatermark(directory, previous) const value = fixture(resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true } }), { directory }) const rename = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { throw Object.assign(new Error('sensitive-path'), { code: 'EACCES' }) }) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(readFileSync(filename, 'utf8')).toBe(previous) expect(value.lifecycle.snapshot('session-1').current?.idleReviewWatermark).toMatchObject({ state: 'error', error: expect.stringContaining('EACCES') }) } finally { rename.mockRestore(); value.stop() } }) it('writes the reservation before starting a reviewer and retains it when the next turn cancels review', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'cancel-watermark-')) const filename = watermarkFile(directory) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, maxPerSession: 1 } }) const value = fixture(config, { directory }) let signal: AbortSignal | undefined vi.mocked(value.coordinator.review).mockImplementation(async (_agent, controller) => { expect(JSON.parse(readFileSync(filename, 'utf8')).attempts).toBe(1) signal = controller return await new Promise((_resolve, reject) => controller.addEventListener('abort', () => reject(new Error('cancelled')), { once: true })) }) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) expect(value.lifecycle.snapshot('session-1').current?.reviewRunning).toBe(true) await value.preStep([userMessage('continue')], 3) expect(signal?.aborted).toBe(true) } finally { value.stop() } const resumed = fixture(config, { directory }) expect(resumed.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(1) resumed.stop() }) it.each([1, 2])('does no watermark I/O by default and persists earlier in-process attempts on opt-in (max: %s)', async maxPerSession => { vi.useFakeTimers(); vi.setSystemTime(1_000_000) const directory = mkdtempSync(join(directories, 'baseline-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { maxPerSession, minIntervalMs: 30_000 } }) const first = fixture(config, { directory }) await completeDurableTurns(first) await vi.advanceTimersByTimeAsync(5_000) expect(first.coordinator.review).toHaveBeenCalledOnce() expect(() => readFileSync(watermarkFile(directory))).toThrow() config.idleReview.persistWatermark = true expect(first.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(1) expect(JSON.parse(readFileSync(watermarkFile(directory), 'utf8')).attempts).toBe(1) first.stop() const resumed = fixture(config, { directory }) try { expect(resumed.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 1, nextReviewAt: '1970-01-01T00:17:15.000Z' }) await completeDurableTurns(resumed) await vi.advanceTimersByTimeAsync(5_000) expect(resumed.coordinator.review).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(25_000) expect(resumed.coordinator.review).toHaveBeenCalledTimes(maxPerSession === 2 ? 1 : 0) expect(JSON.parse(readFileSync(watermarkFile(directory), 'utf8')).attempts).toBe(maxPerSession) } finally { resumed.stop() } }) it('keeps the in-memory quota exhausted if persisting the opt-in baseline fails', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'baseline-failure-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { minIntervalMs: 5_000, maxPerSession: 1 } }) const value = fixture(config, { directory }) let rename: ReturnType | undefined try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) rename = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { throw Object.assign(new Error('baseline refused'), { code: 'EACCES' }) }) config.idleReview.persistWatermark = true expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 1, idleReviewWatermark: { state: 'error' } }) config.idleReview.persistWatermark = false await completeDurableTurns(value, 3, 4) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() } finally { rename?.mockRestore(); value.stop() } }) it('merges additional disabled-mode usage on re-enable in the same Agent', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 're-enable-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, minIntervalMs: 5_000, maxPerSession: 2 } }) const value = fixture(config, { directory }) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) config.idleReview.persistWatermark = false await completeDurableTurns(value, 3, 4) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledTimes(2) config.idleReview.persistWatermark = true expect(value.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(2) } finally { value.stop() } const resumed = fixture(config, { directory }) expect(resumed.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(2) resumed.stop() }) it('never merges disabled-mode usage from another runtime root into a newly enabled root', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'baseline-root-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { maxPerSession: 1 } }) const value = fixture(config, { directory }) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) const graph = value.runtimeSource.forAgent(value.agent) value.runtimeSource.forAgent.mockReturnValue({ ...graph, directory: join(directory, 'new-root') }) config.idleReview.persistWatermark = true expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 0, idleReviewWatermark: { restoredAttempts: 0 } }) } finally { value.stop() } }) it.each(['root', 'disable', 'dispose'] as const)('invalidates queued persistent review when %s changes before dispatch', async change => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'queued-watermark-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true } }) const value = fixture(config, { directory }) try { await completeDurableTurns(value) if (change === 'disable') config.idleReview.persistWatermark = false if (change === 'dispose') value.stop() if (change === 'root') { const graph = value.runtimeSource.forAgent(value.agent) value.runtimeSource.forAgent.mockReturnValue({ ...graph, directory: join(directory, 'changed-root') }) } await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() } finally { value.stop() } }) it.each(['turn', 'policy', 'dispose'] as const)('cancels admission before reserving an attempt when %s changes', async change => { vi.useFakeTimers() const config = resolveConfig({ idleReviewMs: 5_000 }) const value = fixture(config) let finish: ((available: boolean) => void) | undefined try { await completeDurableTurns(value, 1, 1) vi.mocked(value.coordinator.checkReviewAccess).mockImplementationOnce(() => new Promise(resolve => { finish = resolve })) await value.preStep([durableCandidate(300)], 2) const stopping = value.turnStopping(2) await vi.waitFor(() => expect(finish).toBeDefined()) expect(value.lifecycle.snapshot('session-1').current?.reviewRunning).toBe(true) expect(value.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(0) if (change === 'turn') await value.preStep([userMessage('New foreground turn')], 3) if (change === 'policy') config.idleReview.enabled = false if (change === 'dispose') value.stop() finish?.(true) await stopping await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() if (change !== 'dispose') expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ reviewRunning: false, idleReviewAttempts: 0 }) } finally { value.stop() } }) it.each([false, true])('rechecks unavailable admission once in a later step (recovers=%s, issue 635)', async recovers => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) try { await completeDurableTurns(value, 1, 1) await value.preStep([durableCandidate(300)], 2) const check = vi.mocked(value.coordinator.checkReviewAccess).mockReset().mockResolvedValue(false) check.mockResolvedValueOnce(false).mockResolvedValueOnce(recovers) const request = async (step: number) => value.agentListeners.get('agent/request')?.({ agent: value.agent, turn: 2, step, signal: new AbortController().signal }, async () => ({})) await request(1) await request(1) // A model transport retry is still the same step. expect(check).toHaveBeenCalledTimes(1) await request(2) await request(3) expect(check).toHaveBeenCalledTimes(2) await value.turnStopping(2) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledTimes(recovers ? 1 : 0) expect(value.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(recovers ? 1 : 0) } finally { value.stop() } }) it('preserves the watermark and quota when admission recovers after reopening (issue 635)', async () => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'recovered-admission-')) const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark: true, minIntervalMs: 5_000, maxPerSession: 2 } }) const before = fixture(config, { directory }) await completeDurableTurns(before) await vi.advanceTimersByTimeAsync(5_000) expect(before.lifecycle.snapshot('session-1').current?.idleReviewAttempts).toBe(1) before.stop() const resumed = fixture(config, { directory }) try { expect(resumed.lifecycle.snapshot('session-1').current?.idleReviewWatermark?.restoredAttempts).toBe(1) await completeDurableTurns(resumed, 3, 3) await resumed.preStep([durableCandidate(300)], 4) vi.mocked(resumed.coordinator.checkReviewAccess).mockResolvedValueOnce(false).mockResolvedValueOnce(true) const request = resumed.agentListeners.get('agent/request')! for (const step of [1, 2]) await request({ agent: resumed.agent, turn: 4, step, signal: new AbortController().signal }, async () => ({})) await resumed.turnStopping(4) await vi.advanceTimersByTimeAsync(5_000) expect(resumed.coordinator.review).toHaveBeenCalledOnce() expect(JSON.parse(readFileSync(watermarkFile(directory), 'utf8')).attempts).toBe(2) await completeDurableTurns(resumed, 5, 6) await vi.advanceTimersByTimeAsync(5_000) expect(resumed.coordinator.review).toHaveBeenCalledOnce() } finally { resumed.stop() } }) it('waits for the review score threshold, then debounces a full-checkpoint review', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) await value.preStep([durableCandidate()], 1) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: false, reviewActivity: { score: 4, threshold: 5, eligible: false, totalUserTextLength: 150, turnCount: 1 }, }) await value.preStep([userMessage('one more turn')], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: true, reviewRunning: false, reviewActivity: { score: 5, threshold: 5, eligible: true, turnCount: 2 }, }) await vi.advanceTimersByTimeAsync(4_999) expect(value.coordinator.review).not.toHaveBeenCalled() await vi.advanceTimersByTimeAsync(1) expect(value.coordinator.review).toHaveBeenCalledWith(value.agent, expect.any(AbortSignal), expect.any(Function)) expect(value.coordinator.write).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: false, lastReviewAction: 'skipped', lastReviewScore: 5, reviewActivity: { score: 0, eligible: false, turnCount: 0 }, }) }) it('keeps review attempts available while no registered write target can accept the task', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) vi.mocked(value.coordinator.canReview).mockReturnValue(false) await value.preStep([durableCandidate(300)], 1) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: false, idleReviewAttempts: 0 }) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() vi.mocked(value.coordinator.canReview).mockReturnValue(true) await value.preStep([durableCandidate(300)], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) // The last target can disappear after scheduling but before child startup. vi.mocked(value.coordinator.canReview).mockReturnValue(false) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: false, idleReviewAttempts: 0 }) value.stop() }) it.each([ ['failed', 300_000, true], ['successful', 5_000, false], ] as const)('caps %s idle review attempts across a long session (issues 100/255)', async (_kind, minIntervalMs, failed) => { vi.useFakeTimers() const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const value = fixture(resolveConfig({ idleReviewMs: 5_000, idleReview: { provider: 'spawn', minIntervalMs, maxPerSession: 2 } })) if (failed) vi.mocked(value.coordinator.review).mockRejectedValue(new Error('TeamError: reviewer failed')) try { for (let turn = 1; turn <= 30; turn += 1) { await completeDurableTurns(value, turn, turn) await vi.advanceTimersByTimeAsync(5_000) } if (failed) { expect(value.coordinator.review).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(300_000) } expect(value.coordinator.review).toHaveBeenCalledTimes(2) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewAttempts: 2, idleReviewPending: false }) await completeDurableTurns(value, 31, 31) await vi.advanceTimersByTimeAsync(600_000) expect(value.coordinator.review).toHaveBeenCalledTimes(2) } finally { value.stop(); warn.mockRestore() } }) it('pauses review before creating a child while Team tools are installed and resumes after removal', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) let teamTools = true const get = value.agent.ctx.get! value.agent.ctx.get = name => name === 'agentTeams' ? {} : get(name) value.agent.ctx.tools = { get: name => teamTools && name === 'spawn_teammate' ? {} : undefined } try { await completeDurableTurns(value, 1, 3) await vi.advanceTimersByTimeAsync(600_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewBlocked: 'agent-team', idleReviewAttempts: 0, idleReviewPending: false }) teamTools = false await completeDurableTurns(value, 4, 4) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() } finally { value.stop() } }) it('allows explicitly scoped Team review and honors switching back to pause (issue 275)', async () => { vi.useFakeTimers() const config = resolveConfig({ idleReviewMs: 5_000, idleReview: { agentTeams: 'scoped', minIntervalMs: 5_000 } } as never) const value = fixture(config) const get = value.agent.ctx.get! value.agent.ctx.get = name => name === 'agentTeams' ? {} : get(name) value.agent.ctx.tools = { get: name => name === 'spawn_teammate' ? {} : undefined } try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() expect(value.lifecycle.snapshot('session-1').current?.idleReviewBlocked).toBeUndefined() await completeDurableTurns(value, 3, 4) Object.assign(config.idleReview, { agentTeams: 'pause' }) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewBlocked: 'agent-team', idleReviewAttempts: 1 }) } finally { value.stop() } }) it('catches UNAUTHORIZED from agentTeams.isEnabled inside the idle review timer and snapshot (issue 702)', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) let throwUnauthorized = false const unauthorized = Object.assign(new Error('subagent tree access requires the exact live caller'), { code: 'UNAUTHORIZED' }) const get = value.agent.ctx.get! value.agent.ctx.get = name => name === 'agentTeams' ? { isEnabled: () => { if (throwUnauthorized) throw unauthorized; return false } } : get(name) value.agent.ctx.tools = { get: () => undefined } try { await completeDurableTurns(value) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) throwUnauthorized = true await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewBlocked: 'agent-team', idleReviewPending: false, idleReviewAttempts: 0, }) } finally { value.stop() } }) it('absorbs unexpected synchronous errors in the idle review timer without crashing the host (issue 702)', async () => { vi.useFakeTimers() const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) try { await completeDurableTurns(value) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) vi.spyOn(value.coordinator, 'canReview').mockImplementation(() => { throw new Error('synthetic timer check failure') }) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ lastPhase: 'error', lastError: 'synthetic timer check failure', idleReviewPending: false, }) expect(warn).toHaveBeenCalledWith(expect.stringContaining('synthetic timer check failure')) } finally { warn.mockRestore(); value.stop() } }) it('disables only idle review and cancels an already scheduled review when toggled off', async () => { vi.useFakeTimers() const config = resolveConfig({ idleReviewMs: 5_000 }) const value = fixture(config) try { await completeDurableTurns(value) config.idleReview.enabled = false await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').counters).toMatchObject({ recallCues: 1, writebackCues: 1 }) await value.lifecycle.supervise('session-1', 'Explicit durable fact') expect(value.coordinator.write).toHaveBeenCalledOnce() } finally { value.stop() } }) it('does not adopt an already disposed Agent context (issue 623)', () => { const value = fixture(resolveConfig({}), { inactive: true }) try { expect(value.agent.ctx.effect).not.toHaveBeenCalled() expect(value.lifecycle.snapshot().activeAgents).toBe(0) } finally { value.stop() } }) it.each([false, true])('skips a stale idle timer without spending review quota (persist=%s)', async persistWatermark => { vi.useFakeTimers() const directory = mkdtempSync(join(directories, 'disposed-idle-')) const value = fixture(resolveConfig({ idleReviewMs: 5_000, idleReview: { persistWatermark } }), { directory }) try { await completeDurableTurns(value) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) value.deactivateContext() await vi.advanceTimersByTimeAsync(5_000) const state = value.lifecycle.snapshot('session-1') expect(value.coordinator.review).not.toHaveBeenCalled() expect(state.current).toMatchObject({ idleReviewPending: false, reviewRunning: false, idleReviewAttempts: 0 }) expect(state.current?.lastReviewFailure).toBeUndefined() expect(state.current?.lastError).toBeUndefined() expect(state.current?.nextReviewAt).toBeUndefined() expect(state.counters.failures).toBe(0) } finally { value.stop() } }) it.each([false, true])('treats inactive-context rejection as cancellation, retaining partial receipts=%s', async committed => { vi.useFakeTimers() const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) const cause = Object.assign(new Error('cannot create effect on inactive context'), { code: 'INACTIVE_EFFECT' }) vi.mocked(value.coordinator.review).mockRejectedValueOnce(new IdleReviewError('Review interrupted', { status: committed ? 'partial' : 'failed', provider: 'fork', receipts: committed ? [{ tool: 'mnemon_document_create', action: 'created', documentId: 'committed-document' }] : [], }, { cause })) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) const state = value.lifecycle.snapshot('session-1') expect(state.current?.reviewRunning).toBe(false) // Reservation happened before asynchronous preparation; never rewind durable usage. expect(state.current?.idleReviewAttempts).toBe(1) expect(state.counters.failures).toBe(committed ? 1 : 0) if (committed) expect(state.current?.lastReviewFailure).toMatchObject({ status: 'partial', receipts: [{ documentId: 'committed-document' }] }) else { expect(state.current?.lastReviewFailure).toBeUndefined() expect(state.current?.lastError).toBeUndefined() expect(warn).not.toHaveBeenCalled() } } finally { value.stop(); warn.mockRestore() } }) it('surfaces committed receipts without counting an incomplete review as success', async () => { vi.useFakeTimers() const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) vi.mocked(value.coordinator.review).mockRejectedValueOnce(new IdleReviewError('TeamError: after commit', { status: 'partial', runId: 'review-run', provider: 'fork', receipts: [{ tool: 'mnemon_document_create', action: 'created', documentId: 'committed-document' }], })) try { await completeDurableTurns(value) await vi.advanceTimersByTimeAsync(5_000) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ lastPhase: 'error', idleReviewAttempts: 1, lastReviewFailure: { status: 'partial', runId: 'review-run', receipts: [{ documentId: 'committed-document' }] } }) expect(value.lifecycle.snapshot('session-1').counters.failures).toBe(1) expect(value.lifecycle.snapshot('session-1').current?.lastReviewAction).toBeUndefined() } finally { value.stop(); warn.mockRestore() } }) it('reports idle-review failures and retains the warning until a successful review', async () => { vi.useFakeTimers() const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) vi.mocked(value.coordinator.review).mockRejectedValueOnce(new Error('CONTEXT_WINDOW_EXCEEDED: request (145508 tokens) exceeds the available context size (98304 tokens), sk-secret123456')) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('threshold turn')], 2) await value.turnStopping(2) await vi.advanceTimersByTimeAsync(5_000) expect(warn).toHaveBeenCalledOnce() expect(warn).toHaveBeenCalledWith(expect.stringContaining('idle review failed')) expect(warn).toHaveBeenCalledWith(expect.stringContaining('[redacted]')) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ lastPhase: 'error', reviewRunning: false, lastError: expect.stringContaining('CONTEXT_WINDOW_EXCEEDED') }) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity.turnCount).toBe(2) expect(value.followup).not.toHaveBeenCalled() expect(value.steer).not.toHaveBeenCalled() await value.preStep([userMessage('Continue the task')], 3) expect(value.lifecycle.snapshot('session-1').current?.lastError).toContain('CONTEXT_WINDOW_EXCEEDED') await value.turnStopping(3) await vi.advanceTimersByTimeAsync(300_000) expect(value.lifecycle.snapshot('session-1').current?.lastError).toBeUndefined() expect(warn).toHaveBeenCalledOnce() } finally { value.stop() warn.mockRestore() } }) it('keeps an aborted review quiet when a new parent turn cancels it', async () => { vi.useFakeTimers() const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) vi.mocked(value.coordinator.review).mockImplementationOnce(async (_parent, signal) => new Promise((_resolve, reject) => { signal.addEventListener('abort', () => reject(new Error('cancelled review')), { once: true }) })) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('threshold turn')], 2) await value.turnStopping(2) await vi.advanceTimersByTimeAsync(5_000) await value.preStep([userMessage('Resume the parent task')], 3) expect(warn).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').counters.failures).toBe(0) expect(value.lifecycle.snapshot('session-1').current?.lastError).toBeUndefined() } finally { value.stop() warn.mockRestore() } }) it('does not start background work when activity has no deterministic dirty candidate', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) await value.preStep([userMessage('x'.repeat(150))], 1) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) await value.preStep([userMessage('one more ordinary turn')], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: false, reviewActivity: { score: 5, eligible: true }, }) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() }) it('admits a substantial completed assistant artifact without another classifier call', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) await value.preStep([userMessage('x'.repeat(150))], 1) value.events.push({ type: 'assistant/message', data: { turn: 1, message: { content: [{ type: 'text', text: 'Reusable architecture artifact. '.repeat(24) }] }, }, }) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) await value.preStep([userMessage('one more ordinary turn')], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: true, reviewActivity: { score: 5, eligible: true }, }) }) it('honors explicit no-memory maintenance intent before starting a review child', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) await value.preStep([userMessage(`${'x'.repeat(150)},不要主动写记忆。`)], 1) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) await value.preStep([userMessage('请简短确认,但仍不要主动写记忆。')], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: false, reviewActivity: { score: 0, eligible: false, turnCount: 0 }, }) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() }) it('cancels a pending idle review when a new turn begins', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) await value.preStep([durableCandidate()], 1) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) await value.preStep([userMessage('threshold turn')], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) await vi.advanceTimersByTimeAsync(4_000) await value.preStep([userMessage('A new turn arrived')], 3) await vi.advanceTimersByTimeAsync(2_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(false) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity).toMatchObject({ score: 6, turnCount: 3 }) }) it('cancels delayed review work when a one-shot Host disposes the plugin', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) await value.preStep([durableCandidate()], 1) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) await value.preStep([userMessage('threshold turn')], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) value.stop() await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.lifecycle.snapshot('session-1').activeAgents).toBe(0) }) it('counts completed tool results and unique tool names with the review score weights', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) await value.preStep([userMessage('x'.repeat(100))], 1) const names = ['read', 'read', 'write', 'search', 'read'] names.forEach((name, index) => { value.events.push({ type: 'tool/call', data: { turn: 1, step: 1, callId: `call-${index}`, name } }) value.events.push({ type: 'tool/result', data: { turn: 1, step: 1, message: { source: { callId: `call-${index}` } } } }) }) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ idleReviewPending: true, reviewActivity: { totalUserTextLength: 100, turnCount: 1, toolCallCount: 5, uniqueToolCount: 3, textLengthScore: 2, turnScore: 1, toolCallScore: 1, toolDiversityScore: 1, score: 5, }, }) }) it('does not double-score repeated stopping notifications for the same turn', async () => { const value = fixture() await value.preStep([userMessage('short')], 1) await value.turnStopping(1) await value.turnStopping(1) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity).toMatchObject({ totalUserTextLength: 5, turnCount: 1, score: 1, }) }) it('deduplicates the same entered user message across multiple steps', async () => { const value = fixture() const prompt = userMessage('x'.repeat(50)) await value.preStep([prompt], 1, 1) await value.preStep([prompt], 1, 2) await value.turnStopping(1) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity).toMatchObject({ totalUserTextLength: 50, turnCount: 1, textLengthScore: 1, turnScore: 1, score: 2, }) }) it('keeps the activity watermark when a new turn aborts an in-flight review', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) vi.mocked(value.coordinator.review).mockImplementationOnce(async (_parent, signal) => await new Promise(resolve => { const finish = () => resolve({ delegated: true, runId: 'review-child', provider: 'fork', summary: 'Stale completion', action: 'skipped', memoryBodyIds: [], }) if (signal.aborted) finish() else signal.addEventListener('abort', finish, { once: true }) })) await value.preStep([durableCandidate()], 1) value.events.push({ type: 'turn/end', data: { turn: 1 } }) await value.turnStopping(1) await value.preStep([userMessage('threshold turn')], 2) value.events.push({ type: 'turn/end', data: { turn: 2 } }) await value.turnStopping(2) await vi.advanceTimersByTimeAsync(5_000) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ reviewRunning: true }) await value.preStep([userMessage('new evidence')], 3) await vi.advanceTimersByTimeAsync(0) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ reviewRunning: false, idleReviewPending: false, reviewActivity: { score: 6, turnCount: 3, eligible: true }, }) expect(value.lifecycle.snapshot('session-1').current?.lastReviewAt).toBeUndefined() }) it('settles an aborted idle review before a new turn pins the same Agent runtime', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 })) vi.mocked(value.coordinator.review).mockImplementationOnce(async (parent, signal) => { const execution = await value.runtimeSource.executions.workflow(parent, 'review', signal) try { await new Promise(resolve => { if (signal.aborted) resolve() else signal.addEventListener('abort', () => resolve(), { once: true }) }) return { delegated: true, runId: 'review-child', provider: 'fork', summary: 'Aborted stale review', action: 'skipped', memoryBodyIds: [], documentIds: [], } } finally { execution.release() } }) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('threshold turn')], 2) await value.turnStopping(2) await vi.advanceTimersByTimeAsync(5_000) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ reviewRunning: true }) await expect(value.preStep([userMessage('new evidence')], 3)).resolves.toMatchObject({ kind: 'enter' }) expect(value.lifecycle.snapshot('session-1').current).toMatchObject({ reviewRunning: false, idleReviewPending: false, }) expect(value.composableTurns.activeTurn()).toMatchObject({ turnId: 'session-1:3' }) } finally { value.stop() await vi.advanceTimersByTimeAsync(0) } }) it('can cue recall and remember independently', async () => { const recallOnly = fixture(resolveConfig({ recallMode: 'guided', writebackMode: 'off' })) const recallDecision = await recallOnly.preStep([userMessage()], 1) if (recallDecision.kind !== 'enter') throw new Error('unexpected rejection') expect(recallDecision.messages[1]?.content[0]?.text).toContain('mnemon_view_route') expect(recallDecision.messages[1]?.content[0]?.text).not.toContain('mnemon_view_action') const rememberOnly = fixture(resolveConfig({ recallMode: 'off', writebackMode: 'guided' })) const rememberDecision = await rememberOnly.preStep([userMessage()], 1) if (rememberDecision.kind !== 'enter') throw new Error('unexpected rejection') expect(rememberDecision.messages[1]?.content[0]?.text).toContain('mnemon_view_action') expect(rememberDecision.messages[1]?.content[0]?.text).not.toContain('mnemon_view_route') }) it.each(LAYERED)('does not send default Source guidance or run three-tier review under a custom Strategy (%s Layered)', async (_label, strategyWorkflows) => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000, memoryTopology: { strategyId: 'personal-notes' } }), { strategyWorkflows }) try { const decision = await value.preStep([durableCandidate()], 1) if (decision.kind !== 'enter') throw new Error('unexpected rejection') const reminder = decision.messages[1]?.content[0]?.text expect(reminder).toContain('current View') expect(reminder).not.toMatch(/Documents|Memory Spaces|mnemon_recall|mnemon_runtime_memory/) await value.turnStopping(1) await value.preStep([userMessage('one more substantive turn')], 2) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity.eligible).toBe(true) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(false) await vi.advanceTimersByTimeAsync(10_000) expect(value.coordinator.review).not.toHaveBeenCalled() expect(value.coordinator.write).not.toHaveBeenCalled() } finally { value.stop() } }) it('does not suggest View actions when the existing writeEnabled preference is false', async () => { const value = fixture(resolveConfig({ writeEnabled: false })) try { const decision = await value.preStep([userMessage()], 1) if (decision.kind !== 'enter') throw new Error('unexpected rejection') expect(decision.messages[1]?.content[0]?.text).toContain('mnemon_view_route') expect(decision.messages[1]?.content[0]?.text).not.toContain('mnemon_view_action') } finally { value.stop() } }) it.each(LAYERED)('reviews the turns the configured Layered strategy composed (%s)', async (_label, strategyWorkflows) => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 }), { strategyWorkflows }) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('one more substantive turn')], 2) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() } finally { value.stop() } }) it('decides a scheduled review without reaching into the runtime again', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 }), { strategyWorkflows: LAYERED[1][1] }) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('one more substantive turn')], 2) await value.turnStopping(2) // DSH exits on an exception thrown from a timer, so the scheduled check uses what the turn recorded. value.runtimeSource.forAgent.mockImplementation(() => { throw new Error('workspace graph unavailable') }) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() } finally { value.stop() } }) it.each(LAYERED)('rechecks the selected Strategy before running an already-scheduled default review (%s Layered)', async (_label, strategyWorkflows) => { vi.useFakeTimers() const config = resolveConfig({ idleReviewMs: 5_000 }) const value = fixture(config, { strategyWorkflows }) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('one more turn')], 2) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) config.memoryTopology.strategyId = 'personal-notes' await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).not.toHaveBeenCalled() } finally { value.stop() } }) it('runs idle review for a third-party Strategy that declares it', async () => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000, memoryTopology: { strategyId: 'personal-notes' } }), { strategyWorkflows: { 'personal-notes': ['idle-review'] } }) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('one more substantive turn')], 2) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(true) await vi.advanceTimersByTimeAsync(5_000) expect(value.coordinator.review).toHaveBeenCalledOnce() } finally { value.stop() } }) it('leaves idle review to the Strategies that declare it, the Layered one included', async () => { vi.useFakeTimers() // A Layered strategy that declares only capacity maintenance opts out of idle review; // without a declaration at all, as copies before 0.5.10 have, its type id stands for both. const value = fixture(resolveConfig({ idleReviewMs: 5_000 }), { strategyWorkflows: { 'default-three-tier': ['runtime-capacity'] } }) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('one more substantive turn')], 2) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity.eligible).toBe(true) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(false) await vi.advanceTimersByTimeAsync(10_000) expect(value.coordinator.review).not.toHaveBeenCalled() } finally { value.stop() } }) it.each(LAYERED)('runs three-tier review only over turns that three-tier composed (%s Layered)', async (_label, strategyWorkflows) => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 }), { strategyWorkflows }) const pin = value.composableTurns.beginTurn.getMockImplementation()! // The selected Strategy is off, so the only installed one composes instead. value.composableTurns.beginTurn.mockImplementation(async (turnId: string, scope: object) => { const context = await pin(turnId, scope) Object.assign(context.view, composedBy('general')) return context }) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('one more substantive turn')], 2) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.reviewActivity.eligible).toBe(true) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(false) await vi.advanceTimersByTimeAsync(10_000) expect(value.coordinator.review).not.toHaveBeenCalled() } finally { value.stop() } }) it.each(LAYERED)('runs no idle review after turns that ran without memory (%s Layered)', async (_label, strategyWorkflows) => { vi.useFakeTimers() const value = fixture(resolveConfig({ idleReviewMs: 5_000 }), { strategyWorkflows }) // No composition is serving, so the turns run without a View. value.composableTurns.beginTurn.mockRejectedValue(new MemoryCompositionUnavailableError({ state: 'incomplete', contributionRevision: 0, sourceInstanceKeys: [], diagnostics: [{ code: 'missing-strategy', message: 'No Memory Strategy contribution is installed.' }] })) const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) try { await value.preStep([durableCandidate()], 1) await value.turnStopping(1) await value.preStep([userMessage('one more substantive turn')], 2) await value.turnStopping(2) expect(value.lifecycle.snapshot('session-1').current?.idleReviewPending).toBe(false) await vi.advanceTimersByTimeAsync(10_000) expect(value.coordinator.review).not.toHaveBeenCalled() } finally { warn.mockRestore(); value.stop() } }) it('delegates memory-tab candidates directly to an isolated memory subagent', async () => { const value = fixture() const result = await value.lifecycle.supervise('session-1', 'Use SQLite because deployment must remain single-file.') expect(result).toMatchObject({ delegated: true, sessionId: 'session-1', runId: 'write-child' }) expect(value.followup).not.toHaveBeenCalled() expect(value.coordinator.write).toHaveBeenCalledWith(value.agent, 'supervised-writeback', { content: 'Use SQLite because deployment must remain single-file.', source: 'explicit Mnemon tab submission', }, expect.any(AbortSignal)) expect(value.lifecycle.snapshot('session-1').counters.supervisedRequests).toBe(1) }) it('runs workspace-only memory-tab candidates in a disposable top-level task Agent', async () => { const value = fixture() const result = await value.lifecycle.superviseTask('', 'Keep workspace release decisions durable.', undefined, workspaceTwo) expect(result).toMatchObject({ delegated: true, runId: 'write-child' }) expect(value.createTaskAgent).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: workspaceTwo, origin: 'subagent', agentPreset: 'default' } })) expect(value.coordinator.write).toHaveBeenCalledWith(expect.objectContaining({ session: expect.objectContaining({ header: expect.objectContaining({ cwd: workspaceTwo }) }) }), 'supervised-writeback', { content: 'Keep workspace release decisions durable.', source: 'explicit Mnemon tab submission', }, expect.anything()) expect(value.disposedTaskAgents).toContain(result.sessionId) }) it('deduplicates replayed assistant-message supervision by session and message id', async () => { const value = fixture() const [first, replay] = await Promise.all([ value.lifecycle.supervise('session-1', 'Keep the release checklist durable.', 'message-1'), value.lifecycle.supervise('session-1', 'Keep the release checklist durable.', 'message-1'), ]) expect(replay).toEqual(first) expect(value.coordinator.write).toHaveBeenCalledTimes(1) expect(value.coordinator.write).toHaveBeenCalledWith(value.agent, 'supervised-writeback', { content: 'Keep the release checklist durable.', source: 'explicit assistant memory action', }, expect.any(AbortSignal)) expect(value.lifecycle.snapshot('session-1').counters.supervisedRequests).toBe(1) }) it('treats an edited candidate for the same message as a request of its own', async () => { const value = fixture() const first = await value.lifecycle.supervise('session-1', 'Keep the release checklist durable.', 'message-1') // Issue #342: the Save to memory dialog lets the user edit a candidate after it was answered. const edited = await value.lifecycle.supervise('session-1', 'Keep the release checklist and its owner durable.', 'message-1') expect(edited).toMatchObject({ delegated: true, sessionId: 'session-1' }) expect(value.coordinator.write).toHaveBeenCalledTimes(2) expect(value.coordinator.write).toHaveBeenLastCalledWith(value.agent, 'supervised-writeback', { content: 'Keep the release checklist and its owner durable.', source: 'explicit assistant memory action', }, expect.any(AbortSignal)) // Sending the latest text again replays its result instead of writing it twice. await expect(value.lifecycle.supervise('session-1', 'Keep the release checklist and its owner durable.', 'message-1')).resolves.toEqual(edited) expect(value.coordinator.write).toHaveBeenCalledTimes(2) // Editing back to the first text is a request of its own as well: the edited // write may have replaced it, so its first receipt no longer answers it. await expect(value.lifecycle.supervise('session-1', 'Keep the release checklist durable.', 'message-1')).resolves.not.toBe(first) expect(value.coordinator.write).toHaveBeenCalledTimes(3) expect(value.lifecycle.snapshot('session-1').counters.supervisedRequests).toBe(3) }) it('replays and takes edits per message for the dialog in a disposable task Agent', async () => { const value = fixture() // The Save to memory dialog sends its message id through superviseTask, scoped to the workspace. const first = await value.lifecycle.superviseTask('session-1', 'Keep the release checklist durable.', 'message-1', workspaceTwo) await expect(value.lifecycle.superviseTask('session-1', 'Keep the release checklist durable.', 'message-1', workspaceTwo)).resolves.toEqual(first) expect(value.coordinator.write).toHaveBeenCalledTimes(1) await value.lifecycle.superviseTask('session-1', 'Keep the release checklist and its owner durable.', 'message-1', workspaceTwo) expect(value.coordinator.write).toHaveBeenCalledTimes(2) expect(value.createTaskAgent).toHaveBeenCalledTimes(2) }) it('extracts assistant text from the durable DSH message content', () => { const value = fixture() value.events.push({ type: 'assistant/message', data: { turn: 1, step: 1, message: { id: 'message-1', role: 'assistant', content: [ { type: 'text', text: 'First paragraph.' }, { type: 'tool-call', id: 'call-1', name: 'read', arguments: '{}' }, { type: 'text', text: 'Second paragraph.' }, ], source: { kind: 'model', provider: 'mock', model: 'mock' }, }, }, }) expect(value.lifecycle.assistantMessage('session-1', 'message-1')).toEqual({ messageId: 'message-1', text: 'First paragraph.\n\nSecond paragraph.', }) expect(value.lifecycle.assistantMessage('session-1', 'missing')).toBeNull() }) it('keeps disabled lifecycle hooks out of model input while retaining manual supervision', async () => { const value = fixture(resolveConfig({ lifecycleEnabled: false, recallMode: 'off', writebackMode: 'off' })) const prompt = userMessage() const decision = await value.preStep([prompt], 1) expect(decision).toEqual({ kind: 'enter', messages: [prompt] }) expect(value.composableTurns.beginTurn).toHaveBeenCalledOnce() expect(value.steer).not.toHaveBeenCalled() await expect(value.lifecycle.supervise('session-1', 'Durable preference')).resolves.toMatchObject({ delegated: true }) }) it('maps blocked isolated reviews to refusal (#733)', async () => { const config = resolveConfig() const value = fixture(config) ;(value.composableTurns as unknown as { retainView?: () => () => void }).retainView = () => () => undefined let runner: IsolatedReviewRunner | undefined const coordinator = { ...value.coordinator, setIsolatedReviewRunner: vi.fn((callback: IsolatedReviewRunner | undefined) => { runner = callback }), } const agentEvents: Array<{ type: string; data: Record }> = [] const taskCtx = { on: vi.fn(() => () => undefined), effect: vi.fn((callback: () => (() => unknown) | void) => { const cleanup = callback() return () => cleanup?.() }), } const isolatedChild = { id: 'mnemon-review-v1-blocked', status: 'idle' as const, session: { header: {}, snapshotEvents: () => agentEvents, eventAt: (seq: number) => agentEvents[seq], surface: { nodes: [] }, }, ctx: taskCtx, followup: vi.fn(() => { agentEvents.push({ type: 'turn/end', data: { turn: 1, reason: { kind: 'blocked' } } }) }), steer: vi.fn(), inject: vi.fn(), cancel: vi.fn(), whenIdle: vi.fn(async () => undefined), } const ctx = { agents: { get: (id: string) => id === value.agent.id ? value.agent : id === isolatedChild.id ? isolatedChild : undefined, roots: () => [value.agent], create: vi.fn(async (taskOptions: { setup?: (agentCtx: unknown, child: unknown) => Promise | void }) => { await taskOptions.setup?.(taskCtx, isolatedChild) return { agent: isolatedChild, dispose: vi.fn(async () => undefined) } }), }, subagents: { getProvider: () => ({ capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true } }), }, get: vi.fn((name: string) => name === 'agentDefaultModel' ? value.defaultModel : name === 'agentPresets' ? value.agentPresets : undefined), on: vi.fn(() => () => undefined), } const lifecycle = new MnemonLifecycle(ctx as never, coordinator as never, config, { ...value.runtimeSource, config } as never) const stop = lifecycle.start() try { await value.preStep([userMessage()], 1) expect(runner).toBeDefined() const blocked = await runner!({ parent: value.agent, provider: 'spawn', sessionId: isolatedChild.id, prompt: 'Review checkpoint.', persona: 'Reviewer.', allowedTools: ['mnemon_subagent_result'], maxTokens: 1_024, signal: new AbortController().signal, guardTools: () => undefined, }) expect(blocked).toEqual({ stopReason: 'refusal' }) } finally { stop() value.stop() } }) it('extracts redacted turn-end error details from managed isolated reviews when diagnostic is omitted (#733)', async () => { const config = resolveConfig() const value = fixture(config) ;(value.composableTurns as unknown as { retainView?: () => () => void }).retainView = () => () => undefined let runner: IsolatedReviewRunner | undefined const coordinator = { ...value.coordinator, setIsolatedReviewRunner: vi.fn((callback: IsolatedReviewRunner | undefined) => { runner = callback }), } const rootListeners = new Map unknown>() const createdAgents = new Map() createdAgents.set(value.agent.id, value.agent) const makeCtx = () => ({ on: vi.fn(() => () => undefined), effect: vi.fn((callback: () => (() => unknown) | void) => { const cleanup = callback() return () => cleanup?.() }), systemPrompt: { section: vi.fn(() => () => undefined), getSectionOrder: () => 0 }, tools: { restrict: vi.fn(() => () => undefined), guard: vi.fn(() => () => undefined) }, }) const managedEvents = [ { type: 'turn/end', data: { turn: 1, reason: { kind: 'error', error: { code: 'MODEL_ROUTE', message: 'rejected sk-secret123456' } } } }, ] const managedChildId = 'mnemon-review-v1-managed-err' const managedChild = { id: managedChildId, status: 'idle' as const, session: { header: { origin: 'subagent' as const }, snapshotEvents: () => managedEvents, eventAt: (seq: number) => managedEvents[seq], surface: { nodes: [] }, }, ctx: makeCtx(), followup: vi.fn(), steer: vi.fn(), inject: vi.fn(), cancel: vi.fn(), } as unknown as HostAgent const ctx = { agents: { get: (id: string) => createdAgents.get(id), isOwnedBy: () => true, roots: () => [value.agent], create: vi.fn(async (taskOptions: { sessionId: string; setup?: (agentCtx: unknown, child: unknown) => Promise | void }) => { const ownerCtx = makeCtx() const owner = { id: taskOptions.sessionId, status: 'idle' as const, session: { header: {}, snapshotEvents: () => [], eventAt: () => undefined, surface: { nodes: [] } }, ctx: ownerCtx, followup: vi.fn(), steer: vi.fn(), inject: vi.fn(), cancel: vi.fn(), } as unknown as HostAgent await taskOptions.setup?.(ownerCtx, owner) createdAgents.set(owner.id, owner) return { agent: owner, dispose: vi.fn(async () => { createdAgents.delete(owner.id) }) } }), }, subagents: { rootOf: (agent: HostAgent) => agent, getProvider: () => ({ capabilities: { outputSchema: true, depthLimit: true }, prepareContinuable: () => undefined }), startActivation: vi.fn(async (spec: { childId: string }) => { createdAgents.set(spec.childId, managedChild) const listener = rootListeners.get('agent/created') as ((payload: { agent: HostAgent }) => void) | undefined listener?.({ agent: managedChild }) return { childId: spec.childId, result: Promise.resolve({ output: [], stopReason: 'error' }), dispose: vi.fn(async () => { createdAgents.delete(spec.childId) }), } }), }, get: vi.fn((name: string) => name === 'agentDefaultModel' ? value.defaultModel : name === 'agentPresets' ? value.agentPresets : undefined), on: vi.fn((name: string, listener: (...args: never[]) => unknown) => { rootListeners.set(name, listener) return () => rootListeners.delete(name) }), } const lifecycle = new MnemonLifecycle(ctx as never, coordinator as never, config, { ...value.runtimeSource, config } as never) const stop = lifecycle.start() try { await value.preStep([userMessage()], 1) expect(runner).toBeDefined() const outcome = await runner!({ parent: value.agent, provider: 'spawn', sessionId: managedChildId, prompt: 'Review checkpoint.', persona: 'Reviewer.', allowedTools: ['mnemon_subagent_result'], maxTokens: 1_024, signal: new AbortController().signal, guardTools: () => undefined, }) expect(outcome).toEqual({ stopReason: 'error', detail: 'MODEL_ROUTE: rejected [redacted]' }) } finally { stop() value.stop() } }) })