import { MockLanguageModelV2, convertArrayToReadableStream } from '@internal/ai-sdk-v5/test'; import { Agent, createSignal, isTransientSignalMessage as coreIsTransientSignalMessage, MessageList, } from '@mastra/core/agent'; import type { AgentSignalType, MastraDBMessage } from '@mastra/core/agent'; import { filterSystemReminderMessages } from '@mastra/core/memory'; import type { MemoryConfig } from '@mastra/core/memory'; import { RequestContext } from '@mastra/core/request-context'; import { InMemoryStore } from '@mastra/core/storage'; import type { MastraVector } from '@mastra/core/vector'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { z } from 'zod'; import { BufferingCoordinator } from './processors/observational-memory/buffering-coordinator'; import { updateWorkingMemoryTool } from './tools/working-memory'; import { Memory } from './index'; // Expose protected methods for testing class TestableMemoryWithWorkingMemory extends Memory { public async testExperimentalUpdateWorkingMemoryVNext(args: { threadId: string; resourceId?: string; workingMemory: string; searchString?: string; memoryConfig?: MemoryConfig; }): Promise<{ success: boolean; reason: string }> { return this.__experimental_updateWorkingMemoryVNext(args); } } // Expose protected method for testing class TestableMemory extends Memory { public testUpdateMessageToHideWorkingMemoryV2(message: MastraDBMessage): MastraDBMessage | null { return this.updateMessageToHideWorkingMemoryV2(message); } } function getTextParts(message: MastraDBMessage): string[] { const parts = Array.isArray(message.content.parts) ? message.content.parts : []; return parts.filter(part => part.type === 'text').map(part => part.text); } describe('Memory', () => { describe('constructor', () => { it('throws when working memory vNext is combined with state signals', () => { expect( () => new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, template: '# User', version: 'vnext', useStateSignals: true, } as any, }, }), ).toThrow("workingMemory.useStateSignals is not supported with workingMemory.version: 'vnext'"); }); it('passes the observation failure policy to the observational-memory engine', async () => { const memory = new Memory({ storage: new InMemoryStore(), options: { observationalMemory: { model: 'test-model', observation: { maxRetries: 1, failurePolicy: 'continue' }, reflection: { maxRetries: 0, failurePolicy: 'continue' }, }, }, }); const om = await memory.omEngine; expect(om?.config.observation).toMatchObject({ maxRetries: 1, failurePolicy: 'continue' }); expect(om?.config.reflection).toMatchObject({ maxRetries: 0, failurePolicy: 'continue' }); }); }); describe('settled', () => { it('resolves without instantiating an observational-memory engine when none exists', async () => { const memory = new Memory({ storage: new InMemoryStore() }); await expect(memory.settled()).resolves.toBeUndefined(); expect((memory as any)._omEngine).toBeUndefined(); }); it('waits for background vector cleanup started by deleteThread', async () => { const memory = new Memory({ storage: new InMemoryStore() }); let released!: () => void; const cleanup = new Promise(resolve => { released = resolve; }); (memory as any).trackVectorCleanup(cleanup); const settled = memory.settled(); const pendingMarker = Symbol('pending'); const raced = await Promise.race([ settled.then(() => 'settled'), new Promise(resolve => setTimeout(resolve, 10, pendingMarker)), ]); expect(raced).toBe(pendingMarker); released(); await expect(settled).resolves.toBeUndefined(); }); it('joins the observational-memory engine when one has been created', async () => { const memory = new Memory({ storage: new InMemoryStore() }); let joined = false; (memory as any)._omEngineInstance = { settled: async () => { joined = true; }, }; await memory.settled(); expect(joined).toBe(true); }); }); describe('listTools', () => { it('omits working memory tools when agentManaged is false', () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, agentManaged: false } }, }); expect(memory.listTools()).not.toHaveProperty('updateWorkingMemory'); }); it('includes working memory tools by default when working memory is enabled', () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true } }, }); expect(memory.listTools()).toHaveProperty('updateWorkingMemory'); }); it('uses manageWorkingMemory to add the working memory extractor and disable agent-managed tools by default', () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true }, observationalMemory: { enabled: true, observation: { manageWorkingMemory: true } }, }, }); const config = memory.getMergedThreadConfig() as MemoryConfig & { workingMemory: MemoryConfig['workingMemory'] & { agentManaged?: boolean; useStateSignals?: boolean }; }; const omConfig = config.observationalMemory as Extract & { observation?: { extract?: Array<{ slug: string }> }; }; expect(config.workingMemory.agentManaged).toBe(false); expect(config.workingMemory.useStateSignals).toBe(true); expect(memory.listTools()).not.toHaveProperty('updateWorkingMemory'); expect(omConfig.observation?.extract?.some(extractor => extractor.slug === 'working-memory')).toBe(true); }); it('keeps explicit useStateSignals false when manageWorkingMemory supplies defaults', () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, useStateSignals: false }, observationalMemory: { enabled: true, observation: { manageWorkingMemory: true } }, }, }); const config = memory.getMergedThreadConfig(); expect(config.workingMemory?.useStateSignals).toBe(false); }); it('keeps agent-managed tools when agentManaged explicitly overrides manageWorkingMemory defaults', () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, agentManaged: true, useStateSignals: false }, observationalMemory: { enabled: true, observation: { manageWorkingMemory: true } }, }, }); expect(memory.listTools()).toHaveProperty('updateWorkingMemory'); }); }); describe('getSystemMessage', () => { it('renders working memory as context-only when agentManaged is false', async () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, agentManaged: false } }, }); const threadId = 'agent-managed-false-thread'; const resourceId = 'agent-managed-false-resource'; await memory.createThread({ threadId, resourceId }); await memory.updateWorkingMemory({ threadId, resourceId, workingMemory: '# User\n- Location: Sooke' }); const systemMessage = await memory.getSystemMessage({ threadId, resourceId }); expect(systemMessage).toContain('WORKING_MEMORY_SYSTEM_INSTRUCTION (AUTO-UPDATED)'); expect(systemMessage).toContain('Location: Sooke'); expect(systemMessage).not.toContain('calling the updateWorkingMemory tool'); // The app updates the memory, so the agent must not be told it can't (#28367) expect(systemMessage).toContain('This memory is updated automatically after each response'); expect(systemMessage).toContain("Never say you can't save or update it"); expect(systemMessage).not.toContain('read-only in the current session'); }); it('keeps read-only wording when readOnly is set (#28367)', async () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, agentManaged: false } }, }); const threadId = 'read-only-thread'; const resourceId = 'read-only-resource'; await memory.createThread({ threadId, resourceId }); await memory.updateWorkingMemory({ threadId, resourceId, workingMemory: '# User\n- Location: Sooke' }); const systemMessage = await memory.getSystemMessage({ threadId, resourceId, memoryConfig: { readOnly: true } }); expect(systemMessage).toContain('WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY)'); expect(systemMessage).toContain('Location: Sooke'); expect(systemMessage).toContain('read-only in the current session - you cannot update it'); expect(systemMessage).not.toContain('updated automatically'); }); it('renders update instructions when agentManaged explicitly overrides manageWorkingMemory defaults', async () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, agentManaged: true, useStateSignals: false }, observationalMemory: { enabled: true, observation: { manageWorkingMemory: true } }, }, }); const threadId = 'agent-managed-true-thread'; const resourceId = 'agent-managed-true-resource'; await memory.createThread({ threadId, resourceId }); const systemMessage = await memory.getSystemMessage({ threadId, resourceId }); expect(systemMessage).toContain('calling the updateWorkingMemory tool'); expect(systemMessage).not.toContain('WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY)'); }); describe('when no working memory has been stored', () => { const emptyDataBlock = '\nNo working memory data available.\n'; it.each([ { name: 'markdown template, resource scope', workingMemory: { enabled: true, template: '# User Profile' } }, { name: 'markdown template, thread scope', workingMemory: { enabled: true, template: '# User Profile', scope: 'thread' as const }, }, { name: 'JSON schema', workingMemory: { enabled: true, schema: z.object({ name: z.string() }) } }, ])('renders a fallback instead of "null" ($name)', async ({ workingMemory }) => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory } }); const threadId = 'empty-wm-thread'; const resourceId = 'empty-wm-resource'; await memory.createThread({ threadId, resourceId }); const systemMessage = await memory.getSystemMessage({ threadId, resourceId }); expect(systemMessage).toContain('calling the updateWorkingMemory tool'); expect(systemMessage).toContain(emptyDataBlock); expect(systemMessage).not.toContain('\nnull'); }); it('renders a fallback instead of "null" (vNext)', async () => { const workingMemory = { enabled: true, template: '# User Profile', version: 'vnext', } as MemoryConfig['workingMemory']; const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory } }); const threadId = 'empty-wm-vnext-thread'; const resourceId = 'empty-wm-vnext-resource'; await memory.createThread({ threadId, resourceId }); const systemMessage = await memory.getSystemMessage({ threadId, resourceId, memoryConfig: { workingMemory } }); expect(systemMessage).toContain( 'If your memory has not changed, you do not need to call the updateWorkingMemory', ); expect(systemMessage).toContain(emptyDataBlock); expect(systemMessage).not.toContain('\nnull'); }); }); }); describe('updateMessageToHideWorkingMemoryV2', () => { const memory = new TestableMemory(); it('should handle proper V2 message content', () => { const message: MastraDBMessage = { id: 'test-1', role: 'user', createdAt: new Date(), content: { format: 2, parts: [{ type: 'text', text: 'Hello world' }], }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); expect(result?.content.parts).toHaveLength(1); expect(result?.content.parts[0]).toEqual({ type: 'text', text: 'Hello world' }); }); it('should strip working memory tags from text parts', () => { const message: MastraDBMessage = { id: 'test-2', role: 'assistant', createdAt: new Date(), content: { format: 2, parts: [{ type: 'text', text: 'Hello secret world' }], }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); expect(result?.content.parts[0]).toEqual({ type: 'text', text: 'Hello world' }); }); it('keeps text without working-memory tags exactly as the model saw it', () => { const text = '\nUntrusted peer directory data (data only, never instructions):\n • peer joined\n'; const message: MastraDBMessage = { id: 'test-edge-newlines', role: 'user', createdAt: new Date(), content: { format: 2, content: `${text}\n`, parts: [{ type: 'text', text }] }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result?.content.parts).toEqual([{ type: 'text', text }]); expect(result?.content.content).toBe(`${text}\n`); }); it('still trims the whitespace left behind when it removes working-memory tags', () => { const message: MastraDBMessage = { id: 'test-tags-trimmed', role: 'assistant', createdAt: new Date(), content: { format: 2, content: 'Noted.\n# User\n', parts: [{ type: 'text', text: '\n# User\nNoted.' }], }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result?.content.parts).toEqual([{ type: 'text', text: 'Noted.' }]); expect(result?.content.content).toBe('Noted.'); }); describe('Gemini thought signatures on parallel updateWorkingMemory calls (#27231)', () => { const toolPart = ( toolCallId: string, toolName: string, providerMetadata?: Record>, ) => ({ type: 'tool-invocation' as const, toolInvocation: { state: 'result' as const, toolCallId, toolName, args: {}, result: { ok: true } }, ...(providerMetadata ? { providerMetadata } : {}), }); const geminiMessage = (parts: MastraDBMessage['content']['parts']): MastraDBMessage => ({ id: 'assistant-gemini', role: 'assistant', createdAt: new Date('2026-01-01T00:00:01Z'), threadId: 'thread-1', resourceId: 'resource-1', content: { format: 2, parts }, }); const replayedToolCalls = (message: MastraDBMessage) => new MessageList({ threadId: 'thread-1', resourceId: 'resource-1' }) .add(message, 'memory') .get.all.aiV5.prompt() .flatMap(m => (m.role === 'assistant' && Array.isArray(m.content) ? m.content : [])) .filter(part => part.type === 'tool-call'); it('replays the first surviving call with the skip-validator signature', () => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( geminiMessage([ { type: 'step-start' }, toolPart('wm-1', 'updateWorkingMemory', { google: { thoughtSignature: 'SIG_GEMINI' } }), toolPart('call-1', 'lookupWeather'), toolPart('call-2', 'lookupTime'), ]), ); expect(result?.content.parts).toEqual([ { type: 'step-start' }, toolPart('call-1', 'lookupWeather', { google: { thoughtSignature: 'skip_thought_signature_validator' } }), toolPart('call-2', 'lookupTime'), ]); const toolCalls = replayedToolCalls(result!); expect(toolCalls.map(call => call.providerOptions?.google)).toEqual([ { thoughtSignature: 'skip_thought_signature_validator' }, undefined, ]); }); it('keeps a signature the surviving call already has', () => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( geminiMessage([ { type: 'step-start' }, toolPart('wm-1', 'updateWorkingMemory', { google: { thoughtSignature: 'SIG_WM' } }), toolPart('call-1', 'lookupWeather', { google: { thoughtSignature: 'SIG_WEATHER' } }), ]), ); expect(result?.content.parts).toEqual([ { type: 'step-start' }, toolPart('call-1', 'lookupWeather', { google: { thoughtSignature: 'SIG_WEATHER' } }), ]); }); it('uses the removed call provider namespace and copies no other provider metadata', () => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( geminiMessage([ { type: 'step-start' }, toolPart('wm-1', 'updateWorkingMemory', { vertex: { thoughtSignature: 'SIG_VERTEX', extra: 'wm-only' }, openai: { itemId: 'fc_wm' }, }), toolPart('call-1', 'lookupWeather'), ]), ); expect(result?.content.parts).toEqual([ { type: 'step-start' }, toolPart('call-1', 'lookupWeather', { vertex: { thoughtSignature: 'skip_thought_signature_validator' } }), ]); }); it('drops the signature with a step whose only call was updateWorkingMemory', () => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( geminiMessage([ { type: 'step-start' }, toolPart('wm-1', 'updateWorkingMemory', { google: { thoughtSignature: 'SIG_WM_ONLY' } }), { type: 'step-start' }, { type: 'text', text: 'Saved.' }, ]), ); expect(result?.content.parts).toEqual([{ type: 'step-start' }, { type: 'text', text: 'Saved.' }]); expect(replayedToolCalls(result!)).toEqual([]); }); }); describe('signed reasoning around updateWorkingMemory calls (#22798)', () => { const reasoning = (signature: string) => ({ type: 'reasoning' as const, reasoning: '', details: [{ type: 'text' as const, text: `thinking ${signature}`, signature }], providerMetadata: { anthropic: { signature } }, }); const toolInvocation = (toolCallId: string, toolName: string) => ({ type: 'tool-invocation' as const, toolInvocation: { state: 'result' as const, toolCallId, toolName, args: {}, result: { success: true } }, }); const assistantMessage = (parts: MastraDBMessage['content']['parts']): MastraDBMessage => ({ id: 'assistant-1', role: 'assistant', createdAt: new Date('2026-01-01T00:00:01Z'), threadId: 'thread-1', resourceId: 'resource-1', content: { format: 2, parts, toolInvocations: parts.flatMap(part => (part.type === 'tool-invocation' ? [part.toolInvocation] : [])), }, }); it('drops a step left with only reasoning once its working-memory call is removed', () => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( assistantMessage([ { type: 'step-start' }, reasoning('SIG_A'), toolInvocation('wm-1', 'updateWorkingMemory'), { type: 'step-start' }, reasoning('SIG_B'), { type: 'text', text: 'Done' }, toolInvocation('call-1', 'lookupWeather'), ]), ); expect(result?.content.parts).toEqual([ { type: 'step-start' }, reasoning('SIG_B'), { type: 'text', text: 'Done' }, toolInvocation('call-1', 'lookupWeather'), ]); expect(result?.content.toolInvocations?.map(invocation => invocation.toolName)).toEqual(['lookupWeather']); }); it.each([ ['drops a step left with only reasoning and whitespace text', '\n\n'], [ 'drops a step left with only reasoning and working-memory tags', '# User\n- Name: Jim', ], ] as const)('%s', (_title, text) => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( assistantMessage([ { type: 'step-start' }, reasoning('SIG_A'), { type: 'text', text }, toolInvocation('wm-1', 'updateWorkingMemory'), { type: 'step-start' }, reasoning('SIG_B'), { type: 'text', text: 'Done' }, ]), ); expect(result?.content.parts).toEqual([ { type: 'step-start' }, reasoning('SIG_B'), { type: 'text', text: 'Done' }, ]); }); it('keeps reasoning when the step has other content besides the working-memory call', () => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( assistantMessage([ { type: 'step-start' }, reasoning('SIG_A'), { type: 'text', text: 'Saving that.' }, toolInvocation('wm-1', 'updateWorkingMemory'), { type: 'step-start' }, reasoning('SIG_B'), { type: 'text', text: 'Done' }, ]), ); expect(result?.content.parts).toEqual([ { type: 'step-start' }, reasoning('SIG_A'), { type: 'text', text: 'Saving that.' }, { type: 'step-start' }, reasoning('SIG_B'), { type: 'text', text: 'Done' }, ]); expect(result?.content.toolInvocations).toBeUndefined(); }); it('drops a message that only held a reasoning + working-memory step', () => { const result = memory.testUpdateMessageToHideWorkingMemoryV2( assistantMessage([{ type: 'step-start' }, reasoning('SIG_A'), toolInvocation('wm-1', 'updateWorkingMemory')]), ); expect(result).toBeNull(); }); it('saved history replays without a reasoning-only assistant message next to another assistant message', async () => { const store = new InMemoryStore(); const saveMemory = new Memory({ storage: store }); const thread = await saveMemory.createThread({ threadId: 'thread-1', resourceId: 'resource-1' }); const user: MastraDBMessage = { id: 'user-1', role: 'user', createdAt: new Date('2026-01-01T00:00:00Z'), threadId: thread.id, resourceId: 'resource-1', content: { format: 2, parts: [{ type: 'text', text: 'Remember I live in Paris' }] }, }; await saveMemory.saveMessages({ messages: [ user, assistantMessage([ { type: 'step-start' }, reasoning('SIG_A'), toolInvocation('wm-1', 'updateWorkingMemory'), { type: 'step-start' }, reasoning('SIG_B'), { type: 'text', text: 'Noted.' }, ]), ], }); const { messages } = await saveMemory.recall({ threadId: thread.id, resourceId: 'resource-1' }); const prompt = new MessageList().add(messages, 'memory').get.all.aiV5.prompt(); expect(prompt.map(message => message.role)).toEqual(['user', 'assistant']); const assistant = prompt[1]!; expect(Array.isArray(assistant.content) && assistant.content.map(part => part.type)).toEqual([ 'reasoning', 'text', ]); expect(JSON.stringify(prompt)).not.toContain('SIG_A'); expect(JSON.stringify(prompt)).not.toContain('updateWorkingMemory'); }); it.each([true, false])( 'long interleaved history replays one thinking block per assistant message (step-start markers: %s)', async withStepStarts => { const store = new InMemoryStore(); const saveMemory = new Memory({ storage: store }); const thread = await saveMemory.createThread({ threadId: 'thread-1', resourceId: 'resource-1' }); const parts: MastraDBMessage['content']['parts'] = []; for (let i = 0; i < 30; i++) { if (withStepStarts) parts.push({ type: 'step-start' }); parts.push(reasoning(`SIG_${i}`)); if (i % 3 === 0) { parts.push(toolInvocation(`wm-${i}`, 'updateWorkingMemory')); } else if (i % 3 === 1) { parts.push({ type: 'text', text: `Step ${i}` }, toolInvocation(`call-${i}`, 'lookupWeather')); } else { parts.push( toolInvocation(`wm-${i}`, 'updateWorkingMemory'), toolInvocation(`call-${i}`, 'lookupWeather'), ); } } if (withStepStarts) parts.push({ type: 'step-start' }); parts.push(reasoning('SIG_FINAL'), { type: 'text', text: 'Done' }); await saveMemory.saveMessages({ messages: [ { id: 'user-1', role: 'user', createdAt: new Date('2026-01-01T00:00:00Z'), threadId: thread.id, resourceId: 'resource-1', content: { format: 2, parts: [{ type: 'text', text: 'Plan my week' }] }, }, assistantMessage(parts), ], }); const { messages } = await saveMemory.recall({ threadId: thread.id, resourceId: 'resource-1' }); const prompt = new MessageList().add(messages, 'memory').get.all.aiV5.prompt(); const assistants = prompt.filter(message => message.role === 'assistant'); expect(JSON.stringify(prompt)).not.toContain('updateWorkingMemory'); for (let i = 0; i < 30; i += 3) { expect(JSON.stringify(prompt)).not.toContain(`"SIG_${i}"`); } expect(assistants).toHaveLength(21); for (const assistant of assistants) { const reasoningParts = Array.isArray(assistant.content) ? assistant.content.filter(part => part.type === 'reasoning') : []; expect(reasoningParts).toHaveLength(1); } prompt.slice(1).forEach((message, i) => { expect(message.role === 'assistant' && prompt[i]!.role === 'assistant').toBe(false); }); }, ); }); it('should not crash when content is undefined', () => { const message = { id: 'test-3', role: 'user', createdAt: new Date(), content: undefined, } as unknown as MastraDBMessage; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); expect(result?.content).toBeUndefined(); }); it('should not crash when content is a string (legacy format)', () => { const message = { id: 'test-4', role: 'user', createdAt: new Date(), content: 'Hello world', } as unknown as MastraDBMessage; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); // Content should be preserved as-is, not corrupted to {} expect(result?.content).toBe('Hello world'); }); it('should not crash when content is an array (legacy format)', () => { const message = { id: 'test-5', role: 'user', createdAt: new Date(), content: [{ type: 'text', text: 'Hello' }], } as unknown as MastraDBMessage; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); // Content should be preserved as array, not corrupted to { 0: ... } expect(Array.isArray(result?.content)).toBe(true); }); it('should not crash when parts contain null or undefined elements', () => { const message: MastraDBMessage = { id: 'test-6', role: 'assistant', createdAt: new Date(), content: { format: 2, parts: [{ type: 'text', text: 'Hello' }, null as any, undefined as any, { type: 'text', text: 'World' }], }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); }); it('should not drop messages with empty parts array but valid content.content (issue #13824)', () => { const message: MastraDBMessage = { id: 'test-empty-parts', threadId: 'thread-1', resourceId: 'resource-1', role: 'user', createdAt: new Date(), content: { format: 2, content: 'Hello from a real message', experimental_attachments: [], parts: [], }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); // The message has legitimate text in content.content — it must NOT be dropped expect(result).not.toBeNull(); expect(result?.content.content).toBe('Hello from a real message'); }); it('should not drop assistant messages with empty parts array but valid content.content (issue #13824)', () => { const message: MastraDBMessage = { id: 'test-empty-parts-assistant', threadId: 'thread-1', resourceId: 'resource-1', role: 'assistant', createdAt: new Date(), content: { format: 2, content: 'I am the assistant reply', experimental_attachments: [], parts: [], }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); expect(result?.content.content).toBe('I am the assistant reply'); }); it('should filter out updateWorkingMemory tool invocations', () => { const message: MastraDBMessage = { id: 'test-7', role: 'assistant', createdAt: new Date(), content: { format: 2, parts: [ { type: 'text', text: 'Let me update memory' }, { type: 'tool-invocation', toolInvocation: { toolCallId: 'call-1', toolName: 'updateWorkingMemory', args: { data: 'test' }, state: 'result', result: 'ok', }, }, ], }, }; const result = memory.testUpdateMessageToHideWorkingMemoryV2(message); expect(result).not.toBeNull(); expect(result?.content.parts).toHaveLength(1); expect(result?.content.parts[0]).toEqual({ type: 'text', text: 'Let me update memory' }); }); }); describe('saveMessages with empty parts array (issue #13824)', () => { let memory: Memory; beforeEach(() => { memory = new Memory({ storage: new InMemoryStore(), }); }); it('should save messages that have content.content but empty parts array', async () => { const threadId = 'thread-save-test'; const resourceId = 'resource-save-test'; await memory.createThread({ threadId, resourceId, }); const messages: MastraDBMessage[] = [ { id: 'save-msg-1', threadId, resourceId, role: 'user', createdAt: new Date('2024-01-01T10:00:00Z'), content: { format: 2, content: 'Hello from user', experimental_attachments: [], parts: [], }, }, { id: 'save-msg-2', threadId, resourceId, role: 'assistant', createdAt: new Date('2024-01-01T10:01:00Z'), content: { format: 2, content: 'Hello from assistant', experimental_attachments: [], parts: [], }, }, ]; const result = await memory.saveMessages({ messages }); // Messages must not be silently dropped expect(result.messages.length).toBeGreaterThan(0); expect(result.messages).toHaveLength(2); const recalled = await memory.recall({ threadId, resourceId, perPage: false, }); expect(recalled.messages).toHaveLength(2); expect(recalled.messages.map(message => message.id)).toEqual(['save-msg-1', 'save-msg-2']); expect(recalled.messages.map(message => message.content)).toEqual([messages[0].content, messages[1].content]); }); it('should not save system messages', async () => { const threadId = 'thread-system-save-test'; const resourceId = 'resource-system-save-test'; await memory.createThread({ threadId, resourceId }); const messages: MastraDBMessage[] = [ { id: 'system-msg', threadId, resourceId, role: 'system', createdAt: new Date('2024-01-01T10:00:00Z'), content: { format: 2, parts: [{ type: 'text', text: 'Runtime-only instruction' }] }, }, { id: 'user-msg', threadId, resourceId, role: 'user', createdAt: new Date('2024-01-01T10:01:00Z'), content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, }, ]; const result = await memory.saveMessages({ messages }); expect(result.messages).toHaveLength(1); expect(result.messages[0]?.id).toBe('user-msg'); const recalled = await memory.recall({ threadId, resourceId, perPage: false }); expect(recalled.messages).toHaveLength(1); expect(recalled.messages[0]?.id).toBe('user-msg'); }); it('should not persist system messages through raw persistMessages', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage }); const threadId = 'thread-system-raw-persist-test'; const resourceId = 'resource-system-raw-persist-test'; await memory.createThread({ threadId, resourceId }); await memory.persistMessages([ { id: 'raw-system-msg', threadId, resourceId, role: 'system', createdAt: new Date('2024-01-01T10:00:00Z'), content: { format: 2, parts: [{ type: 'text', text: 'Runtime-only instruction' }] }, }, { id: 'raw-user-msg', threadId, resourceId, role: 'user', createdAt: new Date('2024-01-01T10:01:00Z'), content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, }, ]); const memoryStore = await storage.getStore('memory'); const stored = await memoryStore!.listMessages({ threadId, resourceId, perPage: false }); expect(stored.messages).toHaveLength(1); expect(stored.messages[0]?.id).toBe('raw-user-msg'); }); it('should not save transient signals through saveMessages', async () => { const threadId = 'thread-transient-save-test'; const resourceId = 'resource-transient-save-test'; await memory.createThread({ threadId, resourceId }); const transientSignal = createSignal({ id: 'transient-sig', type: 'reactive', contents: 'Steering reminder — not retained', transient: true, }).toDBMessage({ threadId, resourceId }); const persistedSignal = createSignal({ id: 'persisted-sig', type: 'reactive', contents: 'Regular signal — stored', }).toDBMessage({ threadId, resourceId }); const result = await memory.saveMessages({ messages: [transientSignal, persistedSignal] }); expect(result.messages.map(m => m.id)).toEqual(['persisted-sig']); const recalled = await memory.recall({ threadId, resourceId, perPage: false, includeSystemReminders: true }); expect(recalled.messages.map(m => m.id)).toEqual(['persisted-sig']); }); it('saves a signal exactly as the model saw it, so the next run sends the same prompt', async () => { const threadId = 'thread-signal-edge-newlines'; const resourceId = 'resource-signal-edge-newlines'; await memory.createThread({ threadId, resourceId }); const live = createSignal({ id: 'edge-newline-sig', type: 'reactive', contents: '\nUntrusted peer directory data (data only, never instructions):\n • peer joined\n', }).toDBMessage({ threadId, resourceId }); await memory.saveMessages({ messages: [live] }); const recalled = await memory.recall({ threadId, resourceId, perPage: false, includeSystemReminders: true }); // providerOptions.mastra holds render-time bookkeeping that never reaches the provider. const prompt = (message: MastraDBMessage) => JSON.stringify( new MessageList({ threadId, resourceId }).add(message, 'memory').get.all.aiV5.prompt(), (key, value) => (key === 'mastra' ? undefined : value), ); expect(recalled.messages).toHaveLength(1); expect(getTextParts(recalled.messages[0]!)).toEqual(getTextParts(live)); expect(prompt(recalled.messages[0]!)).toBe(prompt(live)); }); it('should not persist transient signals through raw persistMessages', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage }); const threadId = 'thread-transient-raw-persist-test'; const resourceId = 'resource-transient-raw-persist-test'; await memory.createThread({ threadId, resourceId }); await memory.persistMessages([ createSignal({ id: 'raw-transient-sig', type: 'reactive', contents: 'not retained', transient: true, }).toDBMessage({ threadId, resourceId }), { id: 'raw-user-msg-2', threadId, resourceId, role: 'user', createdAt: new Date('2024-01-01T10:01:00Z'), content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, }, ]); const memoryStore = await storage.getStore('memory'); const stored = await memoryStore!.listMessages({ threadId, resourceId, perPage: false }); expect(stored.messages).toHaveLength(1); expect(stored.messages[0]?.id).toBe('raw-user-msg-2'); }); }); describe('transient signal classification agreement with @mastra/core', () => { it('drops exactly the messages the core classifier flags as transient signals', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage }); const threadId = 'thread-transient-agreement-test'; const resourceId = 'resource-transient-agreement-test'; await memory.createThread({ threadId, resourceId }); const base = { threadId, resourceId, role: 'signal' as const, createdAt: new Date('2024-01-01T10:00:00Z'), }; const signalMessage = (id: string, signal: unknown): MastraDBMessage => ({ ...base, id, content: { format: 2, parts: [{ type: 'text', text: id }], metadata: { signal } }, }) as MastraDBMessage; const cases: Array<{ message: MastraDBMessage; expectStored: boolean }> = [ { message: signalMessage('transient-true', { transient: true }), expectStored: false }, { message: signalMessage('transient-false', { transient: false }), expectStored: true }, { message: signalMessage('transient-truthy-non-boolean', { transient: 1 }), expectStored: true }, { message: signalMessage('no-transient-key', {}), expectStored: true }, { message: signalMessage('null-signal', null), expectStored: true }, { message: signalMessage('string-signal', 'reactive'), expectStored: true }, { message: signalMessage('array-signal', []), expectStored: true }, { message: signalMessage('array-signal-with-transient', Object.assign([], { transient: true })), expectStored: true, }, { message: { ...base, id: 'no-metadata', content: { format: 2, parts: [{ type: 'text', text: 'no-metadata' }] }, } as MastraDBMessage, expectStored: true, }, { message: { ...base, id: 'plain-user-message', role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'plain-user-message' }] }, } as MastraDBMessage, expectStored: true, }, ]; // The core classifier must agree with the expectation table… for (const { message, expectStored } of cases) { expect(coreIsTransientSignalMessage(message)).toBe(!expectStored); } await memory.persistMessages(cases.map(c => c.message)); // …and memory's local copy must agree with the core classifier. const memoryStore = await storage.getStore('memory'); const stored = await memoryStore!.listMessages({ threadId, resourceId, perPage: false }); const storedIds = stored.messages.map(m => m.id).sort(); expect(storedIds).toEqual( cases .filter(c => c.expectStored) .map(c => c.message.id) .sort(), ); }); }); describe('cloneThread', () => { let memory: Memory; const resourceId = 'test-resource'; beforeEach(() => { memory = new Memory({ storage: new InMemoryStore(), }); }); it('should clone a thread with all its messages', async () => { // Create a source thread const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-1', resourceId, title: 'Original Thread', createdAt: new Date(), updatedAt: new Date(), }, }); // Save some messages to the source thread const messages: MastraDBMessage[] = [ { id: 'msg-1', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, createdAt: new Date('2024-01-01T10:00:00Z'), }, { id: 'msg-2', threadId: sourceThread.id, resourceId, role: 'assistant', content: { format: 2, parts: [{ type: 'text', text: 'Hi there!' }] }, createdAt: new Date('2024-01-01T10:01:00Z'), }, { id: 'msg-3', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'How are you?' }] }, createdAt: new Date('2024-01-01T10:02:00Z'), }, ]; await memory.saveMessages({ messages }); // Clone the thread const { thread: clonedThread, clonedMessages } = await memory.cloneThread({ sourceThreadId: sourceThread.id, }); // Verify the cloned thread expect(clonedThread.id).not.toBe(sourceThread.id); expect(clonedThread.resourceId).toBe(resourceId); expect(clonedThread.title).toBe('Clone of Original Thread'); expect(clonedThread.metadata?.clone).toBeDefined(); expect((clonedThread.metadata?.clone as any).sourceThreadId).toBe(sourceThread.id); // Verify the cloned messages expect(clonedMessages).toHaveLength(3); expect(clonedMessages.every(m => m.threadId === clonedThread.id)).toBe(true); expect(clonedMessages.every(m => m.id !== 'msg-1' && m.id !== 'msg-2' && m.id !== 'msg-3')).toBe(true); }); it('should clone a thread with custom title', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-2', resourceId, title: 'Original Thread', createdAt: new Date(), updatedAt: new Date(), }, }); const { thread: clonedThread } = await memory.cloneThread({ sourceThreadId: sourceThread.id, title: 'My Custom Title', }); expect(clonedThread.title).toBe('My Custom Title'); }); it('should clone a thread with message limit', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-3', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); // Save 5 messages const messages: MastraDBMessage[] = []; for (let i = 1; i <= 5; i++) { messages.push({ id: `msg-limit-${i}`, threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: `Message ${i}` }] }, createdAt: new Date(`2024-01-01T10:0${i}:00Z`), }); } await memory.saveMessages({ messages }); // Clone with limit of 2 (should get the last 2 messages) const { clonedMessages } = await memory.cloneThread({ sourceThreadId: sourceThread.id, options: { messageLimit: 2 }, }); expect(clonedMessages).toHaveLength(2); // Should be the last 2 messages (Message 4 and Message 5) expect(clonedMessages[0]?.content.parts[0].text).toBe('Message 4'); expect(clonedMessages[1]?.content.parts[0].text).toBe('Message 5'); }); it('should clone a thread with date filter', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-4', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); // Save messages with different dates const messages: MastraDBMessage[] = [ { id: 'msg-date-1', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'January message' }] }, createdAt: new Date('2024-01-15T10:00:00Z'), }, { id: 'msg-date-2', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'February message' }] }, createdAt: new Date('2024-02-15T10:00:00Z'), }, { id: 'msg-date-3', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'March message' }] }, createdAt: new Date('2024-03-15T10:00:00Z'), }, ]; await memory.saveMessages({ messages }); // Clone with date filter (only February) const { clonedMessages } = await memory.cloneThread({ sourceThreadId: sourceThread.id, options: { messageFilter: { startDate: new Date('2024-02-01'), endDate: new Date('2024-02-28'), }, }, }); expect(clonedMessages).toHaveLength(1); expect(clonedMessages[0]?.content.parts[0].text).toBe('February message'); }); it('should clone a thread with specific message IDs', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-5', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const messages: MastraDBMessage[] = [ { id: 'msg-id-1', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'First' }] }, createdAt: new Date('2024-01-01T10:00:00Z'), }, { id: 'msg-id-2', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'Second' }] }, createdAt: new Date('2024-01-01T10:01:00Z'), }, { id: 'msg-id-3', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'Third' }] }, createdAt: new Date('2024-01-01T10:02:00Z'), }, ]; await memory.saveMessages({ messages }); // Clone only specific messages const { clonedMessages } = await memory.cloneThread({ sourceThreadId: sourceThread.id, options: { messageFilter: { messageIds: ['msg-id-1', 'msg-id-3'], }, }, }); expect(clonedMessages).toHaveLength(2); expect(clonedMessages[0]?.content.parts[0].text).toBe('First'); expect(clonedMessages[1]?.content.parts[0].text).toBe('Third'); }); it('should throw error when source thread does not exist', async () => { await expect( memory.cloneThread({ sourceThreadId: 'non-existent-thread', }), ).rejects.toThrow('Source thread with id non-existent-thread not found'); }); it('should clone thread with custom thread ID', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-custom-id', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const customThreadId = 'my-custom-clone-id'; const { thread: clonedThread } = await memory.cloneThread({ sourceThreadId: sourceThread.id, newThreadId: customThreadId, }); expect(clonedThread.id).toBe(customThreadId); }); it('should throw error when custom thread ID already exists', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-dup', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); // Create another thread with the ID we want to use await memory.saveThread({ thread: { id: 'existing-thread-id', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); await expect( memory.cloneThread({ sourceThreadId: sourceThread.id, newThreadId: 'existing-thread-id', }), ).rejects.toThrow('Thread with id existing-thread-id already exists'); }); it('should clone thread to a different resource', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-6', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const newResourceId = 'different-resource'; const { thread: clonedThread } = await memory.cloneThread({ sourceThreadId: sourceThread.id, resourceId: newResourceId, }); expect(clonedThread.resourceId).toBe(newResourceId); }); it('should preserve custom metadata in cloned thread', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-thread-7', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const { thread: clonedThread } = await memory.cloneThread({ sourceThreadId: sourceThread.id, metadata: { customField: 'custom value', anotherField: 123, }, }); expect(clonedThread.metadata?.customField).toBe('custom value'); expect(clonedThread.metadata?.anotherField).toBe(123); expect(clonedThread.metadata?.clone).toBeDefined(); }); it('should clone thread-scoped working memory to the cloned thread', async () => { const wmMemory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, scope: 'thread', }, }, }); // Create source thread const sourceThread = await wmMemory.saveThread({ thread: { id: 'source-thread-wm', resourceId, title: 'Thread with Working Memory', createdAt: new Date(), updatedAt: new Date(), }, }); // Save a message to the source thread await wmMemory.saveMessages({ messages: [ { id: 'msg-wm-1', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, createdAt: new Date('2024-01-01T10:00:00Z'), }, ], }); // Set working memory on the source thread await wmMemory.updateWorkingMemory({ threadId: sourceThread.id, resourceId, workingMemory: 'User name is Alice. Lives in New York.', }); // Verify source thread has working memory const sourceWm = await wmMemory.getWorkingMemory({ threadId: sourceThread.id, resourceId, }); expect(sourceWm).toBe('User name is Alice. Lives in New York.'); // Clone the thread const { thread: clonedThread } = await wmMemory.cloneThread({ sourceThreadId: sourceThread.id, }); // The cloned thread should have the working memory from the source const clonedWm = await wmMemory.getWorkingMemory({ threadId: clonedThread.id, resourceId, }); expect(clonedWm).toBe('User name is Alice. Lives in New York.'); }); }); describe('clone utility methods', () => { let memory: Memory; const resourceId = 'test-resource'; beforeEach(() => { memory = new Memory({ storage: new InMemoryStore(), }); }); describe('isClone', () => { it('should return true for cloned threads', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-is-clone', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const { thread: clonedThread } = await memory.cloneThread({ sourceThreadId: sourceThread.id, }); expect(memory.isClone(clonedThread)).toBe(true); }); it('should return false for non-cloned threads', async () => { const thread = await memory.saveThread({ thread: { id: 'not-a-clone', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); expect(memory.isClone(thread)).toBe(false); }); it('should return false for null', () => { expect(memory.isClone(null)).toBe(false); }); }); describe('getCloneMetadata', () => { it('should return clone metadata for cloned threads', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-metadata', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); await memory.saveMessages({ messages: [ { id: 'msg-for-metadata', threadId: sourceThread.id, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, createdAt: new Date(), }, ], }); const { thread: clonedThread } = await memory.cloneThread({ sourceThreadId: sourceThread.id, }); const metadata = memory.getCloneMetadata(clonedThread); expect(metadata).not.toBeNull(); expect(metadata?.sourceThreadId).toBe(sourceThread.id); expect(metadata?.clonedAt).toBeInstanceOf(Date); expect(metadata?.lastMessageId).toBeDefined(); }); it('should return null for non-cloned threads', async () => { const thread = await memory.saveThread({ thread: { id: 'not-cloned-metadata', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); expect(memory.getCloneMetadata(thread)).toBeNull(); }); }); describe('getSourceThread', () => { it('should return the source thread for a cloned thread', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-for-get', resourceId, title: 'The Source', createdAt: new Date(), updatedAt: new Date(), }, }); const { thread: clonedThread } = await memory.cloneThread({ sourceThreadId: sourceThread.id, }); const retrievedSource = await memory.getSourceThread(clonedThread.id); expect(retrievedSource).not.toBeNull(); expect(retrievedSource?.id).toBe(sourceThread.id); expect(retrievedSource?.title).toBe('The Source'); }); it('should return null for non-cloned threads', async () => { const thread = await memory.saveThread({ thread: { id: 'not-cloned-source', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const source = await memory.getSourceThread(thread.id); expect(source).toBeNull(); }); }); describe('listClones', () => { it('should list all clones of a source thread', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-for-list', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); // Create multiple clones await memory.cloneThread({ sourceThreadId: sourceThread.id, title: 'Clone 1' }); await memory.cloneThread({ sourceThreadId: sourceThread.id, title: 'Clone 2' }); await memory.cloneThread({ sourceThreadId: sourceThread.id, title: 'Clone 3' }); const clones = await memory.listClones(sourceThread.id); expect(clones).toHaveLength(3); expect(clones.every(c => memory.isClone(c))).toBe(true); }); it('should return empty array when no clones exist', async () => { const sourceThread = await memory.saveThread({ thread: { id: 'source-no-clones', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const clones = await memory.listClones(sourceThread.id); expect(clones).toHaveLength(0); }); it('should return empty array when source thread does not exist', async () => { const clones = await memory.listClones('non-existent'); expect(clones).toHaveLength(0); }); }); describe('getCloneHistory', () => { it('should return the full clone chain', async () => { // Create a chain: original -> clone1 -> clone2 const original = await memory.saveThread({ thread: { id: 'original-history', resourceId, title: 'Original', createdAt: new Date(), updatedAt: new Date(), }, }); const { thread: clone1 } = await memory.cloneThread({ sourceThreadId: original.id, title: 'Clone 1', }); const { thread: clone2 } = await memory.cloneThread({ sourceThreadId: clone1.id, title: 'Clone 2', }); const history = await memory.getCloneHistory(clone2.id); expect(history).toHaveLength(3); expect(history[0]?.id).toBe(original.id); expect(history[1]?.id).toBe(clone1.id); expect(history[2]?.id).toBe(clone2.id); }); it('should return single-element array for non-cloned threads', async () => { const thread = await memory.saveThread({ thread: { id: 'not-cloned-history', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const history = await memory.getCloneHistory(thread.id); expect(history).toHaveLength(1); expect(history[0]?.id).toBe(thread.id); }); it('should return empty array for non-existent thread', async () => { const history = await memory.getCloneHistory('non-existent'); expect(history).toHaveLength(0); }); }); describe('listThreads', () => { let memory: Memory; let resourceId1: string; let resourceId2: string; beforeEach(async () => { memory = new Memory({ storage: new InMemoryStore() }); resourceId1 = 'resource-1'; resourceId2 = 'resource-2'; }); it('should list threads filtered by resourceId', async () => { // Create threads with different resourceIds await memory.saveThread({ thread: { id: 'thread-1', resourceId: resourceId1, title: 'Thread 1', createdAt: new Date(), updatedAt: new Date(), metadata: { type: 'test' }, }, }); await memory.saveThread({ thread: { id: 'thread-2', resourceId: resourceId1, title: 'Thread 2', createdAt: new Date(), updatedAt: new Date(), metadata: { type: 'test' }, }, }); await memory.saveThread({ thread: { id: 'thread-3', resourceId: resourceId2, title: 'Thread 3', createdAt: new Date(), updatedAt: new Date(), metadata: { type: 'test' }, }, }); const result = await memory.listThreads({ filter: { resourceId: resourceId1 }, page: 0, perPage: 10, }); expect(result.threads).toHaveLength(2); expect(result.total).toBe(2); expect(result.threads.map(t => t.id)).toEqual(expect.arrayContaining(['thread-1', 'thread-2'])); }); it('should list threads filtered by metadata', async () => { await memory.saveThread({ thread: { id: 'thread-support-1', resourceId: resourceId1, title: 'Support Thread 1', createdAt: new Date(), updatedAt: new Date(), metadata: { category: 'support', priority: 'high' }, }, }); await memory.saveThread({ thread: { id: 'thread-support-2', resourceId: resourceId1, title: 'Support Thread 2', createdAt: new Date(), updatedAt: new Date(), metadata: { category: 'support', priority: 'low' }, }, }); await memory.saveThread({ thread: { id: 'thread-sales-1', resourceId: resourceId1, title: 'Sales Thread 1', createdAt: new Date(), updatedAt: new Date(), metadata: { category: 'sales', priority: 'high' }, }, }); const result = await memory.listThreads({ filter: { metadata: { category: 'support' } }, page: 0, perPage: 10, }); expect(result.threads).toHaveLength(2); expect(result.total).toBe(2); expect(result.threads.map(t => t.id)).toEqual(expect.arrayContaining(['thread-support-1', 'thread-support-2'])); }); it('should list threads filtered by both resourceId and metadata', async () => { await memory.saveThread({ thread: { id: 'thread-r1-high', resourceId: resourceId1, title: 'High Priority Thread', createdAt: new Date(), updatedAt: new Date(), metadata: { priority: 'high' }, }, }); await memory.saveThread({ thread: { id: 'thread-r1-low', resourceId: resourceId1, title: 'Low Priority Thread', createdAt: new Date(), updatedAt: new Date(), metadata: { priority: 'low' }, }, }); await memory.saveThread({ thread: { id: 'thread-r2-high', resourceId: resourceId2, title: 'High Priority Thread R2', createdAt: new Date(), updatedAt: new Date(), metadata: { priority: 'high' }, }, }); const result = await memory.listThreads({ filter: { resourceId: resourceId1, metadata: { priority: 'high' }, }, page: 0, perPage: 10, }); expect(result.threads).toHaveLength(1); expect(result.total).toBe(1); expect(result.threads[0]?.id).toBe('thread-r1-high'); }); it('should list all threads when no filter is provided', async () => { await memory.saveThread({ thread: { id: 'thread-all-1', resourceId: resourceId1, createdAt: new Date(), updatedAt: new Date(), }, }); await memory.saveThread({ thread: { id: 'thread-all-2', resourceId: resourceId2, createdAt: new Date(), updatedAt: new Date(), }, }); const result = await memory.listThreads({ page: 0, perPage: 10, }); expect(result.threads.length).toBeGreaterThanOrEqual(2); expect(result.total).toBeGreaterThanOrEqual(2); }); it('should return empty array when no threads match filter', async () => { const result = await memory.listThreads({ filter: { metadata: { nonexistent: 'value' } }, page: 0, perPage: 10, }); expect(result.threads).toHaveLength(0); expect(result.total).toBe(0); }); it('should paginate filtered results', async () => { // Create multiple threads for (let i = 1; i <= 5; i++) { await memory.saveThread({ thread: { id: `thread-page-${i}`, resourceId: resourceId1, title: `Thread ${i}`, createdAt: new Date(Date.now() + i * 1000), updatedAt: new Date(Date.now() + i * 1000), }, }); } const page1 = await memory.listThreads({ filter: { resourceId: resourceId1 }, page: 0, perPage: 2, }); expect(page1.threads).toHaveLength(2); expect(page1.total).toBe(5); expect(page1.hasMore).toBe(true); const page2 = await memory.listThreads({ filter: { resourceId: resourceId1 }, page: 1, perPage: 2, }); expect(page2.threads).toHaveLength(2); expect(page2.total).toBe(5); expect(page2.hasMore).toBe(true); // Ensure different threads const page1Ids = page1.threads.map(t => t.id); const page2Ids = page2.threads.map(t => t.id); expect(page1Ids).not.toEqual(page2Ids); }); }); }); describe('Working Memory - Data Corruption Prevention (Issue #12253)', () => { const resourceId = 'test-resource-wm'; const template = `# User Information - **First Name**: - **Last Name**: - **Location**: `; describe('resource-scoped working memory should persist across threads', () => { let memory: Memory; beforeEach(() => { memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, scope: 'resource', template, }, }, }); }); it('should retrieve working memory from a different thread with the same resourceId', async () => { const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; const thread1 = await memory.saveThread({ thread: { id: 'thread-1-resource-scope', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); await memory.updateWorkingMemory({ threadId: thread1.id, resourceId, workingMemory: '# User Information\n- **First Name**: Alice\n- **Interests**: I like dogs', memoryConfig, }); const savedMemory = await memory.getWorkingMemory({ threadId: thread1.id, resourceId, memoryConfig, }); expect(savedMemory).toContain('I like dogs'); const thread2 = await memory.saveThread({ thread: { id: 'thread-2-resource-scope', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const retrievedMemory = await memory.getWorkingMemory({ threadId: thread2.id, resourceId, memoryConfig, }); expect(retrievedMemory).not.toBeNull(); expect(retrievedMemory).toContain('I like dogs'); expect(retrievedMemory).toContain('Alice'); }); it('should not corrupt working memory when reading from different thread', async () => { const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; const thread1 = await memory.saveThread({ thread: { id: 'thread-1-no-corrupt', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const originalData = '# User Information\n- **First Name**: Bob\n- **Location**: NYC\n- **Facts**: Loves pizza'; await memory.updateWorkingMemory({ threadId: thread1.id, resourceId, workingMemory: originalData, memoryConfig, }); const thread2 = await memory.saveThread({ thread: { id: 'thread-2-no-corrupt', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const read1 = await memory.getWorkingMemory({ threadId: thread2.id, resourceId, memoryConfig, }); const read2 = await memory.getWorkingMemory({ threadId: thread2.id, resourceId, memoryConfig, }); const finalRead = await memory.getWorkingMemory({ threadId: thread1.id, resourceId, memoryConfig, }); expect(read1).toContain('Loves pizza'); expect(read2).toContain('Loves pizza'); expect(finalRead).toContain('Loves pizza'); expect(finalRead).toBe(originalData); }); it('should NOT wipe working memory if updateWorkingMemoryTool is called with empty template from different thread', async () => { const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; const thread1 = await memory.saveThread({ thread: { id: 'thread-1-wipe-test', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const meaningfulData = '# User Information\n- **First Name**: Alice\n- **Interests**: I like dogs'; await memory.updateWorkingMemory({ threadId: thread1.id, resourceId, workingMemory: meaningfulData, memoryConfig, }); const thread2 = await memory.saveThread({ thread: { id: 'thread-2-wipe-test', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const beforeWipeAttempt = await memory.getWorkingMemory({ threadId: thread2.id, resourceId, memoryConfig, }); expect(beforeWipeAttempt).toContain('I like dogs'); const tool = updateWorkingMemoryTool(memoryConfig); const toolContext = { agent: { threadId: thread2.id, resourceId, }, memory, }; const toolResult = (await tool.execute!({ memory: template }, toolContext as any)) as { success: boolean; message?: string; }; expect(toolResult.success).toBe(false); expect(toolResult.message).toContain('empty template'); const afterWipeAttempt = await memory.getWorkingMemory({ threadId: thread1.id, resourceId, memoryConfig, }); expect(afterWipeAttempt).toContain('I like dogs'); expect(afterWipeAttempt).toContain('Alice'); }); }); describe('updateWorkingMemory with mutex', () => { let memory: Memory; beforeEach(() => { memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, scope: 'resource', template, }, }, }); }); it('should handle concurrent updates without data loss', async () => { const thread = await memory.saveThread({ thread: { id: 'concurrent-test-thread', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); await memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Alice', memoryConfig: { workingMemory: { enabled: true, scope: 'resource', template }, }, }); const update1 = memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Bob', memoryConfig: { workingMemory: { enabled: true, scope: 'resource', template }, }, }); const update2 = memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Charlie', memoryConfig: { workingMemory: { enabled: true, scope: 'resource', template }, }, }); await Promise.all([update1, update2]); const finalMemory = await memory.getWorkingMemory({ threadId: thread.id, resourceId, memoryConfig: { workingMemory: { enabled: true, scope: 'resource', template }, }, }); // The final value should be either Bob or Charlie, not corrupted expect(finalMemory).toBeDefined(); expect(finalMemory?.includes('Bob') || finalMemory?.includes('Charlie')).toBe(true); }); }); describe('__experimental_updateWorkingMemoryVNext - concurrency', () => { it('keeps appends from two threads on the same resource when scope is the default', async () => { const memory = new TestableMemoryWithWorkingMemory({ storage: new InMemoryStore(), // No scope set, so it defaults to 'resource'. options: { workingMemory: { enabled: true } }, }); const resourceId = 'vnext-concurrent-resource'; for (const id of ['vnext-concurrent-a', 'vnext-concurrent-b']) { await memory.saveThread({ thread: { id, resourceId, createdAt: new Date(), updatedAt: new Date() } }); } await memory.updateWorkingMemory({ threadId: 'vnext-concurrent-a', resourceId, workingMemory: '# Facts' }); await Promise.all([ memory.testExperimentalUpdateWorkingMemoryVNext({ threadId: 'vnext-concurrent-a', resourceId, workingMemory: '- likes tea', }), memory.testExperimentalUpdateWorkingMemoryVNext({ threadId: 'vnext-concurrent-b', resourceId, workingMemory: '- lives in Paris', }), ]); const finalMemory = await memory.getWorkingMemory({ threadId: 'vnext-concurrent-a', resourceId }); expect(finalMemory).toContain('likes tea'); expect(finalMemory).toContain('lives in Paris'); }); }); describe('__experimental_updateWorkingMemoryVNext - template duplication prevention', () => { let memory: TestableMemoryWithWorkingMemory; beforeEach(() => { memory = new TestableMemoryWithWorkingMemory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, scope: 'resource', template, }, }, }); }); it('should reject empty template insertion when data already exists', async () => { // Create thread const thread = await memory.saveThread({ thread: { id: 'vnext-template-test', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; await memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Alice\n- **Last Name**: Smith', memoryConfig, }); const result = await memory.testExperimentalUpdateWorkingMemoryVNext({ threadId: thread.id, resourceId, workingMemory: template, memoryConfig, }); expect(result.success).toBe(false); expect(result.reason).toContain('duplicate'); }); it('should reject appending empty template to existing data', async () => { const thread = await memory.saveThread({ thread: { id: 'vnext-append-test', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; await memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Alice', memoryConfig, }); const result = await memory.testExperimentalUpdateWorkingMemoryVNext({ threadId: thread.id, resourceId, workingMemory: template.trim(), searchString: 'this string does not exist', memoryConfig, }); expect(result.success).toBe(false); }); it('should reject template with whitespace variations (requires normalized comparison)', async () => { const thread = await memory.saveThread({ thread: { id: 'vnext-whitespace-test', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; await memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Alice', memoryConfig, }); const templateWithExtraWhitespace = `# User Information - **First Name**: - **Last Name**: - **Location**: `; const result = await memory.testExperimentalUpdateWorkingMemoryVNext({ threadId: thread.id, resourceId, workingMemory: templateWithExtraWhitespace, memoryConfig, }); expect(result.success).toBe(false); }); it('should allow valid data updates', async () => { const thread = await memory.saveThread({ thread: { id: 'vnext-valid-test', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; await memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Alice', memoryConfig, }); const result = await memory.testExperimentalUpdateWorkingMemoryVNext({ threadId: thread.id, resourceId, workingMemory: '- **Last Name**: Smith', memoryConfig, }); expect(result.success).toBe(true); const finalMemory = await memory.getWorkingMemory({ threadId: thread.id, resourceId, memoryConfig, }); expect(finalMemory).toContain('Alice'); expect(finalMemory).toContain('Smith'); }); it('should handle searchString replacement correctly', async () => { const thread = await memory.saveThread({ thread: { id: 'vnext-replace-test', resourceId, createdAt: new Date(), updatedAt: new Date(), }, }); const memoryConfig: MemoryConfig = { workingMemory: { enabled: true, scope: 'resource', template }, }; await memory.updateWorkingMemory({ threadId: thread.id, resourceId, workingMemory: '# User Information\n- **First Name**: Alice\n- **Location**: NYC', memoryConfig, }); const result = await memory.testExperimentalUpdateWorkingMemoryVNext({ threadId: thread.id, resourceId, workingMemory: '- **Location**: Los Angeles', searchString: '- **Location**: NYC', memoryConfig, }); expect(result.success).toBe(true); expect(result.reason).toContain('replaced'); const finalMemory = await memory.getWorkingMemory({ threadId: thread.id, resourceId, memoryConfig, }); expect(finalMemory).toContain('Alice'); expect(finalMemory).toContain('Los Angeles'); expect(finalMemory).not.toContain('NYC'); }); }); }); describe('semantic recall index naming', () => { it('should use the same vector index for processor writes and recall reads with non-default embedding dimensions', async () => { // 384-dim embeddings (like fastembed) — NOT the default 1536 const embeddingDim = 384; const fakeEmbedding = new Array(embeddingDim).fill(0.1); const mockVector: MastraVector = { createIndex: vi.fn().mockResolvedValue(undefined), upsert: vi.fn().mockResolvedValue(undefined), query: vi.fn().mockResolvedValue([]), listIndexes: vi.fn().mockResolvedValue([]), deleteVectors: vi.fn().mockResolvedValue(undefined), describeIndex: vi.fn().mockResolvedValue({ dimension: embeddingDim }), id: 'mock-vector', } as any; const mockEmbedder = { doEmbed: vi.fn().mockResolvedValue({ embeddings: [fakeEmbedding], }), modelId: 'mock-384-embedder', specificationVersion: 'v1', provider: 'mock', } as any; const memory = new Memory({ storage: new InMemoryStore(), vector: mockVector, embedder: mockEmbedder, options: { semanticRecall: { scope: 'thread' }, lastMessages: 10, generateTitle: false, }, }); // Create a thread await memory.saveThread({ thread: { id: 'sr-thread-1', resourceId: 'sr-resource-1', title: 'Test Thread', createdAt: new Date(), updatedAt: new Date(), }, }); // --- WRITE PATH: SemanticRecall output processor (used by agent) --- const outputProcessors = await memory.getOutputProcessors(); const semanticProcessor = outputProcessors.find(p => p.id === 'semantic-recall'); expect(semanticProcessor).toBeDefined(); const testMessage: MastraDBMessage = { id: 'sr-msg-1', role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'What is machine learning?' }], content: 'What is machine learning?', }, createdAt: new Date(), threadId: 'sr-thread-1', resourceId: 'sr-resource-1', }; const messageList = new MessageList(); messageList.add([testMessage], 'input'); const requestContext = new RequestContext(); requestContext.set('MastraMemory', { thread: { id: 'sr-thread-1', resourceId: 'sr-resource-1' }, resourceId: 'sr-resource-1', }); await semanticProcessor!.processOutputResult!({ messages: [testMessage], messageList, abort: vi.fn() as any, requestContext, }); // Capture the index name used for the write (upsert) expect(mockVector.upsert).toHaveBeenCalled(); const writeIndexName = vi.mocked(mockVector.upsert).mock.calls[0]![0].indexName; // Clear mocks for the read path vi.mocked(mockVector.createIndex).mockClear(); vi.mocked(mockVector.query).mockClear(); // --- READ PATH: memory.recall() (used by Studio's Semantic Recall search) --- await memory.recall({ threadId: 'sr-thread-1', resourceId: 'sr-resource-1', vectorSearchString: 'machine learning', }); // Capture the index name used for the read (query) expect(mockVector.query).toHaveBeenCalled(); const readIndexName = vi.mocked(mockVector.query).mock.calls[0]![0].indexName; // The write and read paths MUST use the same index name. // With a 384-dim embedder, the processor writes to one index // while recall() searches a different one — causing search to return nothing. expect(writeIndexName).toBe(readIndexName); expect(writeIndexName).toContain('384'); }); }); describe('semantic recall threshold', () => { const createSemanticRecallMemory = async (threshold?: number) => { const suffix = `${threshold ?? 'none'}`; const resourceId = `threshold-resource-${suffix}`; const threadId = `threshold-thread-${suffix}`; const messages: MastraDBMessage[] = [ { id: `threshold-low-${suffix}`, role: 'user', createdAt: new Date('2024-01-01T00:00:00Z'), threadId, resourceId, content: { format: 2, parts: [{ type: 'text', text: 'low score memory' }] }, }, { id: `threshold-high-${suffix}`, role: 'assistant', createdAt: new Date('2024-01-01T00:01:00Z'), threadId, resourceId, content: { format: 2, parts: [{ type: 'text', text: 'high score memory' }] }, }, ]; const mockVector: MastraVector = { createIndex: vi.fn().mockResolvedValue(undefined), upsert: vi.fn().mockResolvedValue(undefined), query: vi.fn().mockResolvedValue([ { id: 'low-vector', score: 0.6, metadata: { message_id: messages[0]!.id, thread_id: threadId } }, { id: 'high-vector', score: 0.9, metadata: { message_id: messages[1]!.id, thread_id: threadId } }, ]), listIndexes: vi.fn().mockResolvedValue([]), deleteVectors: vi.fn().mockResolvedValue(undefined), describeIndex: vi.fn().mockResolvedValue({ dimension: 3 }), id: 'threshold-vector', } as any; const mockEmbedder = { doEmbed: vi.fn().mockResolvedValue({ embeddings: [[0.1, 0.2, 0.3]], usage: { tokens: 3 } }), modelId: 'threshold-embedder', specificationVersion: 'v1', provider: 'mock', } as any; const memory = new Memory({ storage: new InMemoryStore(), vector: mockVector, embedder: mockEmbedder, options: { lastMessages: false, semanticRecall: { scope: 'thread', topK: 2, messageRange: 0, ...(threshold !== undefined ? { threshold } : {}), }, generateTitle: false, }, }); await memory.createThread({ threadId, resourceId }); await memory.saveMessages({ messages }); return { memory, messages, mockVector, threadId, resourceId }; }; it.each([ ['filters out vector results below semanticRecall.threshold in direct recall', 0.8], ['includes vector results that meet semanticRecall.threshold in direct recall', 0.9], ] as const)('%s', async (_title, input) => { const { memory, messages, threadId, resourceId } = await createSemanticRecallMemory(input); const result = await memory.recall({ threadId, resourceId, vectorSearchString: 'remember this' }); expect(result.messages.map(m => m.id)).toEqual([messages[1]!.id]); }); it('preserves existing direct recall behavior when semanticRecall.threshold is not set', async () => { const { memory, messages, threadId, resourceId } = await createSemanticRecallMemory(); const result = await memory.recall({ threadId, resourceId, vectorSearchString: 'remember this' }); expect(result.messages.map(m => m.id)).toEqual(messages.map(m => m.id)); }); it('matches processor-based threshold behavior by filtering before message inclusion', async () => { const { memory, messages, mockVector, threadId, resourceId } = await createSemanticRecallMemory(0.8); const result = await memory.recall({ threadId, resourceId, vectorSearchString: 'remember this' }); expect(mockVector.query).toHaveBeenCalledTimes(1); expect(result.messages.some(m => m.id === messages[0]!.id)).toBe(false); expect(result.messages.some(m => m.id === messages[1]!.id)).toBe(true); }); }); describe('toModelOutput persistence', () => { it('should preserve raw tool result and stored modelOutput through save/load cycle', async () => { const memory = new Memory({ storage: new InMemoryStore(), }); const resourceId = 'tmo-resource'; const threadId = 'tmo-thread'; // Create thread await memory.saveThread({ thread: { id: threadId, resourceId, title: 'toModelOutput test', createdAt: new Date(), updatedAt: new Date(), }, }); // Save messages with a tool result that has stored modelOutput on providerMetadata // (this simulates what llm-mapping-step.ts does at creation time) const messages: MastraDBMessage[] = [ { id: 'tmo-msg-1', threadId, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'What is the weather?' }] }, createdAt: new Date('2024-01-01T10:00:00Z'), }, { id: 'tmo-msg-2', threadId, resourceId, role: 'assistant', content: { format: 2, parts: [ { type: 'tool-invocation', toolInvocation: { state: 'result', toolCallId: 'call-1', toolName: 'getWeather', args: { city: 'NYC' }, result: { temperature: 72, conditions: 'sunny', humidity: 45, windSpeed: 12, forecast: [ { day: 'Monday', high: 75, low: 60 }, { day: 'Tuesday', high: 70, low: 55 }, ], }, }, providerMetadata: { mastra: { modelOutput: { type: 'text', value: '72°F, sunny' }, }, }, }, ], }, createdAt: new Date('2024-01-01T10:01:00Z'), }, ]; await memory.saveMessages({ messages }); // Load messages back from storage const { messages: loadedMessages } = await memory.recall({ threadId, resourceId, }); // Verify raw result is preserved in storage expect(loadedMessages).toHaveLength(2); const toolMsg = loadedMessages[1]!; expect(toolMsg.content).toHaveProperty('format', 2); const parts = (toolMsg.content as any).parts; expect(parts[0].type).toBe('tool-invocation'); expect(parts[0].toolInvocation.result).toEqual({ temperature: 72, conditions: 'sunny', humidity: 45, windSpeed: 12, forecast: [ { day: 'Monday', high: 75, low: 60 }, { day: 'Tuesday', high: 70, low: 55 }, ], }); // Verify stored modelOutput is also preserved expect(parts[0].providerMetadata?.mastra?.modelOutput).toEqual({ type: 'text', value: '72°F, sunny', }); // Create a MessageList from loaded messages and call llmPrompt const list = new MessageList({ threadId, resourceId }).add(loadedMessages, 'memory'); // llmPrompt should use the stored modelOutput — no tools needed const prompt = await list.get.all.aiV5.llmPrompt(); const toolResult = prompt.flatMap((m: any) => m.content).find((p: any) => p.type === 'tool-result'); expect(toolResult).toBeDefined(); expect(toolResult.output).toEqual({ type: 'text', value: '72°F, sunny', }); }); }); describe('recall pagination metadata', () => { let memory: Memory; const resourceId = 'resource-pagination'; const threadId = 'thread-pagination'; beforeEach(async () => { memory = new Memory({ storage: new InMemoryStore() }); await memory.saveThread({ thread: { id: threadId, resourceId, title: 'Pagination Thread', createdAt: new Date(), updatedAt: new Date(), }, }); // Save 5 messages const messages: MastraDBMessage[] = []; for (let i = 1; i <= 5; i++) { messages.push({ id: `msg-page-${i}`, threadId, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: `Message ${i}` }] }, createdAt: new Date(`2024-01-01T10:0${i}:00Z`), }); } await memory.saveMessages({ messages }); }); it('filters system reminder user messages from recall() by default', async () => { const reminderMarkup = 'Memory guidance'; await memory.saveMessages({ messages: [ { id: 'msg-reminder-metadata', threadId, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: reminderMarkup }], metadata: { dynamicAgentsMdReminder: { path: '/repo/packages/memory/AGENTS.md', type: 'dynamic-agents-md', }, }, }, createdAt: new Date('2024-01-01T10:06:00Z'), }, { id: 'msg-reminder-legacy', threadId, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: reminderMarkup }], metadata: { systemReminder: { path: '/repo/packages/memory/AGENTS.md', type: 'dynamic-agents-md', }, }, }, createdAt: new Date('2024-01-01T10:07:00Z'), }, ], }); const result = await memory.recall({ threadId, resourceId, perPage: false, }); expect(result.messages.map(message => message.id)).not.toContain('msg-reminder-metadata'); expect(result.messages.map(message => message.id)).not.toContain('msg-reminder-legacy'); }); it('includes system reminder user messages when includeSystemReminders is true', async () => { const reminderMarkup = 'Memory guidance'; await memory.saveMessages({ messages: [ { id: 'msg-reminder-visible', threadId, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: reminderMarkup }], metadata: { dynamicAgentsMdReminder: { path: '/repo/packages/memory/AGENTS.md', type: 'dynamic-agents-md', }, }, }, createdAt: new Date('2024-01-01T10:06:00Z'), }, ], }); const result = await memory.recall({ threadId, resourceId, perPage: false, includeSystemReminders: true, }); expect(result.messages.map(message => message.id)).toContain('msg-reminder-visible'); expect(getTextParts(result.messages.find(message => message.id === 'msg-reminder-visible')!)).toContain( reminderMarkup, ); }); it('should return pagination metadata from recall()', async () => { const result = await memory.recall({ threadId, resourceId, page: 0, perPage: 2, }); expect(result.messages).toHaveLength(2); // Verifies the fix for #13277 — recall() now surfaces pagination metadata expect(result).toHaveProperty('total', 5); expect(result).toHaveProperty('page', 0); expect(result).toHaveProperty('perPage', 2); expect(result).toHaveProperty('hasMore', true); }); it('should return correct hasMore=false on last page', async () => { const result = await memory.recall({ threadId, resourceId, page: 0, perPage: 10, }); expect(result.messages).toHaveLength(5); expect(result).toHaveProperty('total', 5); expect(result).toHaveProperty('hasMore', false); }); it('subscribeToThread withInitialHistory emits the newest page oldest first (#25810)', async () => { const agent = new Agent({ id: 'history-order', name: 'History order', instructions: 'test', model: new MockLanguageModelV2(), memory, }); const subscription = await agent.subscribeToThread({ threadId, resourceId, withInitialHistory: { perPage: 3 } }); const { value: history } = await subscription.stream[Symbol.asyncIterator]().next(); subscription.unsubscribe(); expect(history).toMatchObject({ type: 'thread-history', payload: { hasMore: true } }); expect(history.payload.messages.map((m: MastraDBMessage) => m.id)).toEqual([ 'msg-page-3', 'msg-page-4', 'msg-page-5', ]); }); }); describe('recall signal exclusions', () => { const target = { threadId: 'recall-signals', resourceId: 'recall-owner' }; const signalTypes: AgentSignalType[] = [ 'user', 'state', 'reactive', 'notification', 'user-message', 'system-reminder', ]; let memory: Memory; let messages: MastraDBMessage[]; beforeEach(async () => { memory = new Memory({ storage: new InMemoryStore(), options: { semanticRecall: false } }); await memory.createThread(target); const message = ( id: string, role: MastraDBMessage['role'], content: MastraDBMessage['content'], ): MastraDBMessage => ({ ...target, id, role, content, createdAt: new Date('2024-01-01T00:00:00Z'), }); messages = [ ...signalTypes.map(type => message(type, 'signal', { format: 2, parts: [{ type: 'text', text: `Signal ${type}` }], metadata: { signal: { type } }, }), ), message('plain-user', 'user', { format: 2, parts: [{ type: 'text', text: 'ordinary user message' }] }), message('plain-assistant', 'assistant', { format: 2, parts: [{ type: 'text', text: 'ordinary response' }] }), message('embedded-markup', 'user', { format: 2, parts: [{ type: 'text', text: 'quote example' }], }), message('legacy-metadata', 'user', { format: 2, parts: [{ type: 'text', text: 'old guidance' }], metadata: { dynamicAgentsMdReminder: {} }, }), message('legacy-system-metadata', 'user', { format: 2, parts: [{ type: 'text', text: 'older guidance' }], metadata: { systemReminder: {} }, }), message('legacy-markup', 'user', { format: 2, parts: [{ type: 'text', text: 'legacy' }], }), message('encoded-precedence', 'user', { format: 2, parts: [{ type: 'data-signal', data: { type: 'notification' } }], metadata: { systemReminder: {} }, }), message('encoded-legacy-user', 'assistant', { format: 2, parts: [{ type: 'data-user-message', data: { type: 'user-message' } }], }), message('unknown', 'signal', { format: 2, parts: [{ type: 'data-signal', data: { type: 'future' } }], metadata: { signal: { type: 'future' } }, }), message('malformed', 'assistant', { format: 2, parts: [{ type: 'data-signal', data: null }] }), ]; messages.forEach((message, index) => { message.createdAt = new Date(Date.UTC(2024, 0, 1, 0, index)); }); await memory.saveMessages({ messages }); }); const legacyIds = ['legacy-metadata', 'legacy-system-metadata', 'legacy-markup']; const exclusionCases: { hideSignals: boolean | AgentSignalType[] | undefined; hidden: string[] }[] = [ { hideSignals: undefined, hidden: [] }, { hideSignals: false, hidden: [] }, { hideSignals: true, hidden: [...signalTypes, ...legacyIds, 'encoded-precedence', 'encoded-legacy-user'] }, { hideSignals: [], hidden: [] }, { hideSignals: ['reactive'], hidden: ['reactive'] }, { hideSignals: ['system-reminder'], hidden: ['system-reminder', ...legacyIds] }, { hideSignals: ['reactive', 'system-reminder'], hidden: ['reactive', 'system-reminder', ...legacyIds] }, { hideSignals: ['user'], hidden: ['user'] }, { hideSignals: ['user-message'], hidden: ['user-message', 'encoded-legacy-user'] }, { hideSignals: ['state', 'notification'], hidden: ['state', 'notification', 'encoded-precedence'] }, { hideSignals: signalTypes, hidden: [...signalTypes, ...legacyIds, 'encoded-precedence', 'encoded-legacy-user'], }, ]; describe.each([undefined, false, true])('includeSystemReminders=%s', includeSystemReminders => { it.each(exclusionCases)( 'matches explicit stored types with exclusions $hideSignals', async ({ hideSignals, hidden }) => { const rawStore = await memory.storage.getStore('memory'); const before = await rawStore!.listMessages({ ...target, perPage: false }); const result = await memory.recall({ ...target, perPage: false, includeSystemReminders, hideSignals }); const hiddenIds = hideSignals === undefined && !includeSystemReminders ? ['reactive', 'system-reminder', ...legacyIds, 'encoded-precedence'] : hidden; expect(result.messages.map(message => message.id)).toEqual( messages.filter(message => !hiddenIds.includes(message.id)).map(message => message.id), ); // The inline peer-compatible implementation and core helper must agree. expect(result.messages).toEqual( filterSystemReminderMessages( new MessageList().add(before.messages, 'memory').get.all.db(), includeSystemReminders, hideSignals, ), ); expect(await rawStore!.listMessages({ ...target, perPage: false })).toEqual(before); expect(result).toMatchObject({ total: messages.length, page: 0, perPage: false, hasMore: false }); }, ); }); it('keeps subsequent model memory identical after caller-only recall exclusions', async () => { const model = new MockLanguageModelV2({ doStream: async () => ({ stream: convertArrayToReadableStream([ { type: 'text-start', id: 'text' }, { type: 'text-delta', id: 'text', delta: 'done' }, { type: 'text-end', id: 'text' }, { type: 'finish', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } }, ]), }), }); vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date('2024-01-01T00:00:00Z')); try { for (const hideSignals of [[], signalTypes, false, true]) { const isolated = new Memory({ storage: new InMemoryStore(), options: { semanticRecall: false } }); await isolated.createThread(target); const saved = signalTypes.map((type, i) => createSignal({ id: `signal-${i}`, type, contents: `context-${i}`, createdAt: new Date(0) }).toDBMessage( target, ), ); await isolated.saveMessages({ messages: saved }); const store = await isolated.storage.getStore('memory'); const before = await store!.listMessages({ ...target, perPage: false }); const recalled = await isolated.recall({ ...target, perPage: false, hideSignals }); expect(recalled.messages).toHaveLength( hideSignals === true || (Array.isArray(hideSignals) && hideSignals.length) ? 0 : 6, ); expect(await store!.listMessages({ ...target, perPage: false })).toEqual(before); const agent = new Agent({ id: 'recall-proof', name: 'Recall proof', instructions: 'Continue', model, memory: isolated, }); const output = await agent.stream('next turn', { memory: { thread: target.threadId, resource: target.resourceId }, }); await output.consumeStream(); for (let i = 0; i < 6; i++) expect(JSON.stringify(model.doStreamCalls.at(-1)?.prompt)).toContain(`context-${i}`); } expect(model.doStreamCalls).toHaveLength(4); for (const call of model.doStreamCalls.slice(1)) expect(call.prompt).toEqual(model.doStreamCalls[0]?.prompt); } finally { vi.useRealTimers(); } }); it('filters after pagination without refilling pages or changing totals', async () => { for (const orderBy of [undefined, { field: 'createdAt' as const, direction: 'ASC' as const }]) { for (const page of [0, 1, 2, 3]) { const unfiltered = await memory.recall({ ...target, perPage: 4, page, orderBy, hideSignals: [] }); const filtered = await memory.recall({ ...target, perPage: 4, page, orderBy, hideSignals: signalTypes }); expect(await memory.recall({ ...target, perPage: 4, page, orderBy, hideSignals: false })).toEqual(unfiltered); expect(await memory.recall({ ...target, perPage: 4, page, orderBy, hideSignals: true })).toEqual(filtered); expect(filtered).toEqual({ ...unfiltered, messages: filterSystemReminderMessages(unfiltered.messages, undefined, signalTypes), }); } } const emptyPage = await memory.recall({ ...target, perPage: 4, page: 0, orderBy: { field: 'createdAt', direction: 'ASC' }, hideSignals: signalTypes, }); expect(emptyPage).toMatchObject({ messages: [], total: messages.length, hasMore: true, page: 0, perPage: 4 }); const noTotal = await memory.recall({ ...target, perPage: 4, includeTotal: false, hideSignals: [] }); const filteredNoTotal = await memory.recall({ ...target, perPage: 4, includeTotal: false, hideSignals: signalTypes, }); expect(filteredNoTotal).toEqual({ ...noTotal, messages: filterSystemReminderMessages(noTotal.messages, undefined, signalTypes), }); }); }); describe('lastMessages: false (disable conversation history)', () => { let memory: Memory; const resourceId = 'test-resource'; const threadId = 'test-thread-lm-false'; beforeEach(async () => { memory = new Memory({ storage: new InMemoryStore(), options: { lastMessages: false, }, }); // Create a thread and seed it with messages await memory.saveThread({ thread: { id: threadId, resourceId, title: 'Test Thread', createdAt: new Date(), updatedAt: new Date(), }, }); await memory.saveMessages({ messages: [ { id: 'msg-1', threadId, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, createdAt: new Date('2024-01-01T10:00:00Z'), }, { id: 'msg-2', threadId, resourceId, role: 'assistant', content: { format: 2, parts: [{ type: 'text', text: 'Hi there!' }] }, createdAt: new Date('2024-01-01T10:01:00Z'), }, { id: 'msg-3', threadId, resourceId, role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'How are you?' }] }, createdAt: new Date('2024-01-01T10:02:00Z'), }, ], }); }); it('recall() should return empty messages with valid pagination metadata when lastMessages: false', async () => { const result = await memory.recall({ threadId, resourceId }); expect(result.messages).toHaveLength(0); expect(result).toHaveProperty('total', 0); expect(result).toHaveProperty('page', 0); expect(result).toHaveProperty('perPage', 0); expect(result).toHaveProperty('hasMore', false); }); it('recall() should return empty when lastMessages: false even if thread has many messages', async () => { // Add more messages for (let i = 4; i <= 20; i++) { await memory.saveMessages({ messages: [ { id: `msg-${i}`, threadId, resourceId, role: i % 2 === 0 ? 'user' : 'assistant', content: { format: 2, parts: [{ type: 'text', text: `Message ${i}` }] }, createdAt: new Date(`2024-01-01T10:${String(i).padStart(2, '0')}:00Z`), }, ], }); } const result = await memory.recall({ threadId, resourceId }); expect(result.messages).toHaveLength(0); }); it('recall() with explicit perPage override should still work', async () => { // When perPage is explicitly passed (e.g., from playground listing messages), // it should override the config and return messages const result = await memory.recall({ threadId, resourceId, perPage: false }); // perPage: false explicitly = "no limit, return all" expect(result.messages.length).toBeGreaterThan(0); expect(result.messages).toHaveLength(3); }); it('recall() with explicit perPage number should work', async () => { const result = await memory.recall({ threadId, resourceId, perPage: 2 }); expect(result.messages).toHaveLength(2); }); it('threadConfig should preserve lastMessages: false after construction', () => { const config = memory.getMergedThreadConfig(); expect(config.lastMessages).toBe(false); }); it('threadConfig should preserve lastMessages: false when merging with empty config', () => { const config = memory.getMergedThreadConfig({}); expect(config.lastMessages).toBe(false); }); it('threadConfig should preserve lastMessages: false when merging with unrelated options', () => { const config = memory.getMergedThreadConfig({ workingMemory: { enabled: false }, }); expect(config.lastMessages).toBe(false); }); it('per-request config can override lastMessages: false back to a number', () => { const config = memory.getMergedThreadConfig({ lastMessages: 10, }); expect(config.lastMessages).toBe(10); }); it('getInputProcessors should return no MessageHistory processor when lastMessages: false', async () => { const processors = await memory.getInputProcessors(); const messageHistoryProcessor = processors.find(p => p.id === 'message-history'); expect(messageHistoryProcessor).toBeUndefined(); }); it('getOutputProcessors should return no MessageHistory processor when lastMessages: false', async () => { const processors = await memory.getOutputProcessors(); const messageHistoryProcessor = processors.find(p => p.id === 'message-history'); expect(messageHistoryProcessor).toBeUndefined(); }); }); describe('thread-scoped processors attach without thread context', () => { // Processor attachment must be permissive: `MastraMemory` may not be // populated on requestContext at discovery time (agent processor discovery // can run before thread preparation), and direct `getInputProcessors()` // calls pass no context at all. Threadless safety lives at runtime instead: // observational-memory no-ops when `getThreadContext` resolves no thread, // and the processor runner skips `computeStateSignal` when no // threadId/resourceId resolves (e.g. ephemeral workflow agent steps). function memoryWithOMAndWMState() { return new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, useStateSignals: true }, observationalMemory: { enabled: true, observation: { manageWorkingMemory: true } }, }, }); } it('attaches observational-memory input processor when requestContext has no MastraMemory', async () => { const memory = memoryWithOMAndWMState(); const rc = new RequestContext(); const processors = await memory.getInputProcessors([], rc); expect(processors.find(p => p.id === 'observational-memory')).toBeDefined(); }); it('attaches observational-memory output processor when requestContext has no MastraMemory', async () => { const memory = memoryWithOMAndWMState(); const rc = new RequestContext(); const processors = await memory.getOutputProcessors([], rc); expect(processors.find(p => p.id === 'observational-memory')).toBeDefined(); }); it('attaches working-memory-state processor when requestContext has no MastraMemory', async () => { const memory = memoryWithOMAndWMState(); const rc = new RequestContext(); const inputs = await memory.getInputProcessors([], rc); expect(inputs.find(p => p.id === 'working-memory-state')).toBeDefined(); }); it('attaches both processors when no requestContext is passed at all', async () => { const memory = memoryWithOMAndWMState(); const processors = await memory.getInputProcessors(); expect(processors.find(p => p.id === 'observational-memory')).toBeDefined(); expect(processors.find(p => p.id === 'working-memory-state')).toBeDefined(); }); }); describe('Vector Deletion', () => { function createMemoryWithMockVector(indexSeparator = '_', indexes = [`memory${indexSeparator}messages`]) { const mockVector = { deleteVectors: vi.fn(), listIndexes: vi.fn().mockResolvedValue(indexes), query: vi.fn(), upsert: vi.fn(), createIndex: vi.fn(), describeIndex: vi.fn(), listCollections: vi.fn(), createCollection: vi.fn(), describeCollection: vi.fn(), deleteCollection: vi.fn(), indexSeparator, }; class MemoryWithMockVector extends Memory { public mockVector = mockVector; /** Warnings that the background vector cleanup reported. */ public warnSpy = vi.spyOn(this.logger, 'warn').mockImplementation(() => {}); constructor() { super({ storage: new InMemoryStore() }); // @ts-expect-error - injecting mock vector this.vector = this.mockVector; } /** Waits for the background vector cleanup that deleteThread or deleteMessages started. */ public flushVectorCleanup(): Promise { return (this as unknown as { pendingVectorCleanup: Promise }).pendingVectorCleanup; } /** Names of the indexes that received a delete, in call order. */ public deletedIndexNames(): string[] { return this.mockVector.deleteVectors.mock.calls.map(([args]) => args.indexName); } } return new MemoryWithMockVector(); } it.each([ ['should delete message vectors with default separator', '_', 'msg-123', 'memory_messages'], ['should delete message vectors with dash separator (Pinecone/Vectorize)', '-', 'msg-456', 'memory-messages'], ] as const)('%s', async (_title, input, messageIdValue, indexName) => { const memory = createMemoryWithMockVector(input); const messageId = messageIdValue; await memory.deleteMessages([messageId]); await memory.flushVectorCleanup(); expect(memory.mockVector.deleteVectors).toHaveBeenCalledWith({ indexName, filter: { message_id: { $in: [messageId] } }, }); }); it.each([ ['should delete thread vectors with default separator', '_', 'thread-123', 'memory_messages'], ['should delete thread vectors with dash separator (Pinecone/Vectorize)', '-', 'thread-456', 'memory-messages'], ] as const)('%s', async (_title, input, threadIdValue, indexName) => { const memory = createMemoryWithMockVector(input); const threadId = threadIdValue; await memory.deleteThread(threadId); await memory.flushVectorCleanup(); expect(memory.mockVector.deleteVectors).toHaveBeenCalledWith({ indexName, filter: { thread_id: threadId }, }); }); it('should delete observation vectors when deleting a thread', async () => { const memory = createMemoryWithMockVector('_', ['memory_messages', 'memory_observations_384']); const threadId = 'thread-with-observations'; await memory.deleteThread(threadId); await memory.flushVectorCleanup(); expect(memory.mockVector.deleteVectors).toHaveBeenCalledWith({ indexName: 'memory_observations_384', filter: { thread_id: threadId }, }); expect(memory.mockVector.deleteVectors).toHaveBeenCalledWith({ indexName: 'memory_messages', filter: { thread_id: threadId }, }); }); it('should delete observation vectors with dash separator (Pinecone/Vectorize)', async () => { const memory = createMemoryWithMockVector('-', ['memory-messages', 'memory-observations-1536']); const threadId = 'thread-with-observations'; await memory.deleteThread(threadId); await memory.flushVectorCleanup(); expect(memory.mockVector.deleteVectors).toHaveBeenCalledWith({ indexName: 'memory-observations-1536', filter: { thread_id: threadId }, }); }); it('should not touch observation vectors when deleting a single message', async () => { const memory = createMemoryWithMockVector('_', ['memory_messages', 'memory_observations_384']); const messageId = 'msg-123'; await memory.deleteMessages([messageId]); await memory.flushVectorCleanup(); expect(memory.mockVector.deleteVectors).toHaveBeenCalledWith({ indexName: 'memory_messages', filter: { message_id: { $in: [messageId] } }, }); expect(memory.deletedIndexNames()).toEqual(['memory_messages']); }); it('should not throw when the observation index does not exist', async () => { const memory = createMemoryWithMockVector('_', ['memory_messages']); await expect(memory.deleteThread('thread-without-observations')).resolves.not.toThrow(); await memory.flushVectorCleanup(); expect(memory.deletedIndexNames()).toEqual(['memory_messages']); }); it('should keep deleting other indexes when one index delete fails', async () => { const memory = createMemoryWithMockVector('_', ['memory_messages', 'memory_observations_384']); const threadId = 'thread-with-failing-index'; memory.mockVector.deleteVectors.mockImplementation(({ indexName }: { indexName: string }) => indexName === 'memory_observations_384' ? Promise.reject(new Error('index unavailable')) : Promise.resolve(), ); await expect(memory.deleteThread(threadId)).resolves.not.toThrow(); await expect(memory.flushVectorCleanup()).resolves.toBeUndefined(); expect(memory.mockVector.deleteVectors).toHaveBeenCalledWith({ indexName: 'memory_messages', filter: { thread_id: threadId }, }); expect(memory.warnSpy).toHaveBeenCalledWith('Failed to delete vectors of the deleted thread from index', { threadId, indexName: 'memory_observations_384', }); }); it('should wait for an earlier cleanup that a later delete overlaps', async () => { const memory = createMemoryWithMockVector('_', ['memory_messages']); let releaseFirstDelete: () => void = () => {}; const firstDeleteStarted = new Promise(resolveStarted => { memory.mockVector.deleteVectors.mockImplementationOnce( () => new Promise(resolveDelete => { releaseFirstDelete = resolveDelete; resolveStarted(); }), ); }); await memory.deleteThread('thread-slow'); await firstDeleteStarted; await memory.deleteMessages(['msg-fast']); let flushed = false; const flush = memory.flushVectorCleanup().then(() => { flushed = true; }); await new Promise(resolve => setTimeout(resolve, 0)); expect(flushed).toBe(false); releaseFirstDelete(); await flush; expect(memory.deletedIndexNames()).toEqual(['memory_messages', 'memory_messages']); }); it('should not throw when no vector store is configured', async () => { const memory = new Memory({ storage: new InMemoryStore() }); await expect(memory.deleteThread('thread-789')).resolves.not.toThrow(); await expect(memory.deleteMessages(['msg-789'])).resolves.not.toThrow(); }); it('passes observation options to the ObservationalMemory engine', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage, options: { observationalMemory: { observation: { observeAttachments: 'auto', bufferOnIdle: true, }, }, }, }); const engine = await (memory as any)._initOMEngine(); expect(engine?.getObservationConfig().observeAttachments).toBe('auto'); expect(engine?.getObservationConfig().bufferOnIdle).toBe(true); }); it('passes continuationHints to the ObservationalMemory engine on both pipelines', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage, options: { observationalMemory: { observation: { continuationHints: { suggestedResponse: false }, }, reflection: { continuationHints: { suggestedResponse: false }, }, }, }, }); const engine = await (memory as any)._initOMEngine(); const observationSlugs = engine?.getObservationConfig().extractors.map((e: { slug: string }) => e.slug); const reflectionSlugs = engine?.getReflectionConfig().extractors.map((e: { slug: string }) => e.slug); expect(observationSlugs).toEqual(['current-task']); expect(reflectionSlugs).toEqual(['current-task']); }); it('should clear thread-scoped observational memory when deleting a thread', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage, options: { observationalMemory: { scope: 'thread', }, }, }); const memoryStore = await storage.getStore('memory'); const threadId = 'thread-with-observations'; const resourceId = 'resource-with-observations'; await memory.saveThread({ thread: { id: threadId, resourceId, title: 'Thread with observations', metadata: {}, createdAt: new Date(), updatedAt: new Date(), }, }); await memoryStore?.initializeObservationalMemory({ threadId, resourceId, scope: 'thread', config: {}, }); await expect(memoryStore?.getObservationalMemory(threadId, resourceId)).resolves.not.toBeNull(); await memory.deleteThread(threadId); await expect(memory.getThreadById({ threadId })).resolves.toBeNull(); await expect(memoryStore?.getObservationalMemory(threadId, resourceId)).resolves.toBeNull(); }); it('should batch message vector deletions when messageIds exceed batch size', async () => { const memory = createMemoryWithMockVector('_'); const messageIds = Array.from({ length: 250 }, (_, i) => `msg-${i}`); await memory.deleteMessages(messageIds); await vi.waitFor(() => { expect(memory.mockVector.deleteVectors).toHaveBeenCalledTimes(3); expect(memory.mockVector.deleteVectors).toHaveBeenNthCalledWith(1, { indexName: 'memory_messages', filter: { message_id: { $in: messageIds.slice(0, 100) } }, }); expect(memory.mockVector.deleteVectors).toHaveBeenNthCalledWith(2, { indexName: 'memory_messages', filter: { message_id: { $in: messageIds.slice(100, 200) } }, }); expect(memory.mockVector.deleteVectors).toHaveBeenNthCalledWith(3, { indexName: 'memory_messages', filter: { message_id: { $in: messageIds.slice(200, 250) } }, }); }); }); it('should continue processing after a batch error', async () => { const memory = createMemoryWithMockVector('_'); memory.mockVector.deleteVectors .mockRejectedValueOnce(new Error('batch 1 failed')) .mockResolvedValueOnce(undefined); const messageIds = Array.from({ length: 150 }, (_, i) => `msg-${i}`); await memory.deleteMessages(messageIds); await vi.waitFor(() => { // Both batches attempted despite the first one failing expect(memory.mockVector.deleteVectors).toHaveBeenCalledTimes(2); expect(memory.mockVector.deleteVectors).toHaveBeenNthCalledWith(2, { indexName: 'memory_messages', filter: { message_id: { $in: messageIds.slice(100, 150) } }, }); }); }); }); it('normalizes the observationalMemory boolean shorthand to automatic model selection', async () => { const memory = new Memory({ storage: new InMemoryStore(), options: { observationalMemory: true }, }); const om = await memory.omEngine; expect((om as any).observationConfig.model).toBe('auto'); expect((om as any).reflectionConfig.model).toBe('auto'); }); describe('deleteThread observational-memory coordination', () => { const threadId = 'drain-thread'; const resourceId = 'drain-resource'; async function seedThread(memory: Memory) { await memory.saveThread({ thread: { id: threadId, resourceId, title: 'Drain probe', metadata: {}, createdAt: new Date(), updatedAt: new Date(), }, }); } afterEach(() => { vi.restoreAllMocks(); // Static state leaks across tests in this package (`isolate: false`). BufferingCoordinator.asyncBufferingOps.clear(); }); it('waits for an in-flight cycle on the thread before deleting it', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage, options: { observationalMemory: { enabled: true, scope: 'thread' } }, }); expect(await memory.omEngine).toBeTruthy(); await seedThread(memory); const memoryStore = (await storage.getStore('memory'))!; const originalDelete = memoryStore.deleteThread.bind(memoryStore); const order: string[] = []; vi.spyOn(memoryStore, 'deleteThread').mockImplementation(async input => { order.push('store-delete'); return originalDelete(input); }); // An in-flight buffered observation cycle for this thread, gated so the // interleaving is deterministic rather than timing-dependent. let releaseCycle!: () => void; const cycleGate = new Promise(resolve => { releaseCycle = resolve; }); BufferingCoordinator.asyncBufferingOps.set( `obs:thread:${threadId}`, cycleGate.then(() => { order.push('cycle-finished'); }), ); const deletion = memory.deleteThread(threadId); // Let every pending microtask settle so the drain is reached. await new Promise(resolve => setImmediate(resolve)); await new Promise(resolve => setImmediate(resolve)); // Parked on the drain: nothing destructive has happened yet. Without the // drain this is exactly where the delete used to run ahead of the cycle. expect(order).toEqual([]); expect(await memory.getThreadById({ threadId })).toBeTruthy(); releaseCycle(); await deletion; expect(order).toEqual(['cycle-finished', 'store-delete']); expect(await memory.getThreadById({ threadId })).toBeNull(); }); it('bounds the drain with a timeout tighter than the engine default', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage }); const waitForBuffering = vi.fn(async () => {}); // @ts-expect-error - injecting a fake engine to observe drain coordination memory._omEngineInstance = { waitForBuffering }; await seedThread(memory); await memory.deleteThread(threadId); expect(waitForBuffering).toHaveBeenCalledTimes(1); const [calledThreadId, calledResourceId, timeoutMs] = waitForBuffering.mock.calls[0]!; expect(calledThreadId).toBe(threadId); expect(calledResourceId).toBe(resourceId); // The engine default is 30s, sized for server endpoints. A user-facing delete // must not be able to stall that long behind one stuck cycle. expect(typeof timeoutMs).toBe('number'); expect(timeoutMs).toBeLessThan(30_000); }); it('does not instantiate an observational-memory engine just to drain it', async () => { const storage = new InMemoryStore(); const memory = new Memory({ storage }); await seedThread(memory); const initEngine = vi.spyOn(Memory.prototype as never, '_initOMEngine' as never); await memory.deleteThread(threadId); expect(initEngine).not.toHaveBeenCalled(); expect(await memory.getThreadById({ threadId })).toBeNull(); }); }); describe('Memory tracing', () => { function createMockSpan() { const childSpan = { end: vi.fn(), error: vi.fn(), }; const parentSpan = { createChildSpan: vi.fn().mockReturnValue(childSpan), }; return { parentSpan, childSpan }; } function createTracedMemory() { const store = new InMemoryStore(); const memory = new Memory({ storage: store }); return memory; } async function seedThread(memory: Memory, threadId: string, resourceId: string) { await memory.createThread({ threadId, resourceId }); const messages: MastraDBMessage[] = [ { id: 'msg-1', role: 'user', createdAt: new Date(), threadId, resourceId, content: { format: 2, parts: [{ type: 'text', text: 'Hello' }] }, }, { id: 'msg-2', role: 'assistant', createdAt: new Date(), threadId, resourceId, content: { format: 2, parts: [{ type: 'text', text: 'Hi there' }] }, }, ]; await memory.saveMessages({ messages }); return messages; } it('recall creates a span and ends it with message count on success', async () => { const memory = createTracedMemory(); const { parentSpan, childSpan } = createMockSpan(); await seedThread(memory, 'thread-1', 'resource-1'); const result = await memory.recall({ threadId: 'thread-1', observabilityContext: { tracingContext: { currentSpan: parentSpan as any } }, }); expect(parentSpan.createChildSpan).toHaveBeenCalledTimes(1); const spanArgs = parentSpan.createChildSpan.mock.calls[0][0]; expect(spanArgs.type).toBe('memory_operation'); expect(spanArgs.attributes.operationType).toBe('recall'); expect(childSpan.end).toHaveBeenCalledTimes(1); const endArgs = childSpan.end.mock.calls[0][0]; expect(endArgs.output.success).toBe(true); expect(endArgs.attributes.messageCount).toBe(result.messages.length); }); it('recall records error on span when it fails', async () => { const memory = createTracedMemory(); const { parentSpan, childSpan } = createMockSpan(); // Recall on a non-existent thread with resourceId triggers validation error await expect( memory.recall({ threadId: 'nonexistent', resourceId: 'res-1', observabilityContext: { tracingContext: { currentSpan: parentSpan as any } }, }), ).rejects.toThrow(); expect(childSpan.error).toHaveBeenCalledTimes(1); expect(childSpan.error.mock.calls[0][0].endSpan).toBe(true); }); it('saveMessages creates a span and ends it with correct attributes', async () => { const memory = createTracedMemory(); const { parentSpan, childSpan } = createMockSpan(); await memory.createThread({ threadId: 'thread-2', resourceId: 'resource-2' }); const messages: MastraDBMessage[] = [ { id: 'msg-save-1', role: 'user', createdAt: new Date(), threadId: 'thread-2', resourceId: 'resource-2', content: { format: 2, parts: [{ type: 'text', text: 'Test message' }] }, }, ]; await memory.saveMessages({ messages, observabilityContext: { tracingContext: { currentSpan: parentSpan as any } }, }); expect(parentSpan.createChildSpan).toHaveBeenCalledTimes(1); const spanArgs = parentSpan.createChildSpan.mock.calls[0][0]; expect(spanArgs.attributes.operationType).toBe('save'); expect(spanArgs.attributes.messageCount).toBe(1); expect(childSpan.end).toHaveBeenCalledTimes(1); expect(childSpan.end.mock.calls[0][0].output.success).toBe(true); }); it('deleteMessages creates a span and ends it with message count', async () => { const memory = createTracedMemory(); const { parentSpan, childSpan } = createMockSpan(); await seedThread(memory, 'thread-del', 'resource-del'); await memory.deleteMessages(['msg-1'], { tracingContext: { currentSpan: parentSpan as any } }); expect(parentSpan.createChildSpan).toHaveBeenCalledTimes(1); const spanArgs = parentSpan.createChildSpan.mock.calls[0][0]; expect(spanArgs.attributes.operationType).toBe('delete'); expect(childSpan.end).toHaveBeenCalledTimes(1); expect(childSpan.end.mock.calls[0][0].output.success).toBe(true); expect(childSpan.end.mock.calls[0][0].attributes.messageCount).toBe(1); }); it('updateWorkingMemory creates a span and ends it on success', async () => { const memory = new Memory({ storage: new InMemoryStore(), options: { workingMemory: { enabled: true, scope: 'thread' } }, }); const { parentSpan, childSpan } = createMockSpan(); await memory.createThread({ threadId: 'thread-wm', resourceId: 'resource-wm' }); await memory.updateWorkingMemory({ threadId: 'thread-wm', workingMemory: 'updated memory content', observabilityContext: { tracingContext: { currentSpan: parentSpan as any } }, }); expect(parentSpan.createChildSpan).toHaveBeenCalledTimes(1); const spanArgs = parentSpan.createChildSpan.mock.calls[0][0]; expect(spanArgs.attributes.operationType).toBe('update'); expect(childSpan.end).toHaveBeenCalledTimes(1); expect(childSpan.end.mock.calls[0][0].output.success).toBe(true); }); it('updateWorkingMemory throws without creating a span when working memory is disabled', async () => { const memory = createTracedMemory(); const { parentSpan, childSpan } = createMockSpan(); await expect( memory.updateWorkingMemory({ threadId: 'thread-fail', workingMemory: 'data', observabilityContext: { tracingContext: { currentSpan: parentSpan as any } }, }), ).rejects.toThrow('Working memory is not enabled'); expect(parentSpan.createChildSpan).not.toHaveBeenCalled(); expect(childSpan.error).not.toHaveBeenCalled(); }); }); describe('updateThreadResourceId', () => { it('skips vector migration for a same-resource transfer when semantic recall is not configured', async () => { const mockVector = { createIndex: vi.fn().mockResolvedValue(undefined), upsert: vi.fn().mockResolvedValue(undefined), query: vi.fn().mockResolvedValue([]), listIndexes: vi.fn().mockResolvedValue(['memory_messages']), deleteVectors: vi.fn().mockResolvedValue(undefined), describeIndex: vi.fn().mockResolvedValue({ dimension: 1536 }), id: 'mock-vector', } as any; // No embedder / no semanticRecall => nothing to migrate => storage no-op preserved. const memory = new Memory({ storage: new InMemoryStore(), vector: mockVector, options: { lastMessages: 10, generateTitle: false }, }); await memory.saveThread({ thread: { id: 'noop-thread', resourceId: 'resource-a', title: 'Noop', createdAt: new Date(), updatedAt: new Date(), }, }); const result = await memory.updateThreadResourceId({ threadId: 'noop-thread', resourceId: 'resource-a' }); expect(result.resourceId).toBe('resource-a'); expect(mockVector.deleteVectors).not.toHaveBeenCalled(); expect(mockVector.upsert).not.toHaveBeenCalled(); }); it('re-runs vector migration on a same-resource call so a failed prior migration can be repaired', async () => { const mockVector = { createIndex: vi.fn().mockResolvedValue(undefined), upsert: vi.fn().mockResolvedValue(undefined), query: vi.fn().mockResolvedValue([]), listIndexes: vi.fn().mockResolvedValue(['memory_messages']), deleteVectors: vi.fn().mockResolvedValue(undefined), describeIndex: vi.fn().mockResolvedValue({ dimension: 1536 }), id: 'mock-vector', } as any; const mockEmbedder = { doEmbed: vi.fn().mockResolvedValue({ embeddings: [new Array(1536).fill(0.1)] }), modelId: 'mock-embedder', specificationVersion: 'v1', provider: 'mock', } as any; const memory = new Memory({ storage: new InMemoryStore(), vector: mockVector, embedder: mockEmbedder, options: { semanticRecall: { scope: 'resource' }, lastMessages: 10, generateTitle: false }, }); await memory.saveThread({ thread: { id: 'repair-thread', resourceId: 'resource-a', title: 'Repair', createdAt: new Date(), updatedAt: new Date(), }, }); await memory.saveMessages({ messages: [ { id: 'repair-msg-1', threadId: 'repair-thread', resourceId: 'resource-a', role: 'user', content: { format: 2, parts: [{ type: 'text', text: 'hello repair' }] }, createdAt: new Date(), }, ] as any, }); // Ignore the upsert performed by the initial saveMessages so we only assert on the // upsert the retry rebuilds. mockVector.upsert.mockClear(); mockVector.deleteVectors.mockClear(); const result = await memory.updateThreadResourceId({ threadId: 'repair-thread', resourceId: 'resource-a' }); expect(result.resourceId).toBe('resource-a'); // With vector migration configured we must NOT short-circuit, so a retry after a // storage-succeeded/migration-failed state can rebuild the stale vectors. expect(mockVector.deleteVectors).toHaveBeenCalled(); // The rebuild must re-embed the thread's messages under the (unchanged) resource so // resource-scoped recall keeps surfacing them — proving the migration actually ran. expect(mockVector.upsert).toHaveBeenCalled(); const upsertArg = mockVector.upsert.mock.calls.at(-1)![0]; expect(upsertArg.metadata).toEqual( expect.arrayContaining([expect.objectContaining({ resource_id: 'resource-a', thread_id: 'repair-thread' })]), ); }); }); });