import { describe, it, expect, beforeEach } from 'vitest'; import { resolveInstructionBlocks } from './instruction-builder'; import { InMemoryDB, InMemoryPromptBlocksStorage } from '@mastra/core/storage'; import type { AgentInstructionBlock } from '@mastra/core/storage'; describe('resolveInstructionBlocks', () => { let db: InMemoryDB; let storage: InMemoryPromptBlocksStorage; beforeEach(() => { db = new InMemoryDB(); storage = new InMemoryPromptBlocksStorage({ db }); }); it('should resolve a static text block', async () => { const blocks: AgentInstructionBlock[] = [{ type: 'text', content: 'You are a helpful assistant.' }]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(result).toBe('You are a helpful assistant.'); }); it('should resolve a text block with template variables', async () => { const blocks: AgentInstructionBlock[] = [{ type: 'text', content: 'Hello {{name}}, your role is {{role}}.' }]; const result = await resolveInstructionBlocks( blocks, { name: 'Alice', role: 'admin' }, { promptBlocksStorage: storage }, ); expect(result).toBe('Hello Alice, your role is admin.'); }); it('should join multiple text blocks with double newlines', async () => { const blocks: AgentInstructionBlock[] = [ { type: 'text', content: 'First block.' }, { type: 'text', content: 'Second block.' }, ]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(result).toBe('First block.\n\nSecond block.'); }); it('should skip empty text blocks', async () => { const blocks: AgentInstructionBlock[] = [ { type: 'text', content: 'First.' }, { type: 'text', content: ' ' }, { type: 'text', content: 'Third.' }, ]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(result).toBe('First.\n\nThird.'); }); it('should resolve a prompt_block_ref from storage', async () => { await storage.create({ promptBlock: { id: 'block-1', name: 'Greeting', content: 'Welcome to our service.', }, }); await storage.update({ id: 'block-1', status: 'published' }); const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'block-1' }]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(result).toBe('Welcome to our service.'); }); it('should apply template rendering to prompt_block_ref content', async () => { await storage.create({ promptBlock: { id: 'block-tmpl', name: 'Personalized greeting', content: 'Hello {{user.name}}, you have {{user.credits}} credits.', }, }); await storage.update({ id: 'block-tmpl', status: 'published' }); const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'block-tmpl' }]; const context = { user: { name: 'Bob', credits: 100 } }; const result = await resolveInstructionBlocks(blocks, context, { promptBlocksStorage: storage }); expect(result).toBe('Hello Bob, you have 100 credits.'); }); it('should skip a prompt_block_ref that is not found in storage', async () => { const blocks: AgentInstructionBlock[] = [ { type: 'text', content: 'Start.' }, { type: 'prompt_block_ref', id: 'nonexistent' }, { type: 'text', content: 'End.' }, ]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(result).toBe('Start.\n\nEnd.'); }); it('should skip a prompt_block_ref with status other than published', async () => { await storage.create({ promptBlock: { id: 'draft-block', name: 'Draft', content: 'Draft content.', }, }); const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'draft-block' }]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(result).toBe(''); }); it.each([ ['should include a prompt_block_ref when rules pass', 'admin', 'You have admin privileges.'], ['should exclude a prompt_block_ref when rules fail', 'viewer', ''], ] as const)('%s', async (_title, role, expected) => { await storage.create({ promptBlock: { id: 'admin-block', name: 'Admin instructions', content: 'You have admin privileges.', rules: { operator: 'AND', conditions: [{ field: 'user.role', operator: 'equals', value: 'admin' }], }, }, }); await storage.update({ id: 'admin-block', status: 'published' }); const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'admin-block' }]; const result = await resolveInstructionBlocks(blocks, { user: { role } }, { promptBlocksStorage: storage }); expect(result).toBe(expected); }); describe('per-usage rules on prompt_block_ref', () => { // Runtime slot with a shared stored default as fallback. The stored block has no rules of its own. // An empty userPrompt counts as missing. const slotWithFallback: AgentInstructionBlock[] = [ { type: 'text', content: 'Follow the platform safety policy.' }, { type: 'prompt_block', content: '{{userPrompt}}', rules: { operator: 'AND', conditions: [ { field: 'userPrompt', operator: 'exists' }, { field: 'userPrompt', operator: 'not_equals', value: '' }, ], }, }, { type: 'prompt_block_ref', id: 'shared-default-user-prompt', rules: { operator: 'OR', conditions: [ { field: 'userPrompt', operator: 'not_exists' }, { field: 'userPrompt', operator: 'equals', value: '' }, ], }, }, ]; beforeEach(async () => { await storage.create({ promptBlock: { id: 'shared-default-user-prompt', name: 'Default user prompt', content: 'Answer in a friendly, balanced style.', }, }); await storage.update({ id: 'shared-default-user-prompt', status: 'published' }); }); it.each([ [ 'uses the runtime slot and skips the fallback ref when userPrompt is present', 'Please answer in a concise engineering-review style.', 'Follow the platform safety policy.\n\nPlease answer in a concise engineering-review style.', ], [ 'uses the fallback ref when userPrompt is an empty string', '', 'Follow the platform safety policy.\n\nAnswer in a friendly, balanced style.', ], ] as const)('%s', async (_title, userPrompt, expected) => { const result = await resolveInstructionBlocks(slotWithFallback, { userPrompt }, { promptBlocksStorage: storage }); expect(result).toBe(expected); }); it('uses the fallback ref when userPrompt is absent', async () => { const result = await resolveInstructionBlocks(slotWithFallback, {}, { promptBlocksStorage: storage }); expect(result).toBe('Follow the platform safety policy.\n\nAnswer in a friendly, balanced style.'); }); it('does not fetch a reference whose own rules fail', async () => { const getByIdResolved = storage.getByIdResolved.bind(storage); storage.getByIdResolved = async (id, options) => { if (id === 'unreachable') throw new Error('storage unavailable'); return getByIdResolved(id, options); }; const blocks: AgentInstructionBlock[] = [ { type: 'text', content: 'Base.' }, { type: 'prompt_block_ref', id: 'unreachable', rules: { operator: 'AND', conditions: [{ field: 'beta', operator: 'equals', value: true }] }, }, { type: 'prompt_block_ref', id: 'shared-default-user-prompt' }, ]; const result = await resolveInstructionBlocks(blocks, { beta: false }, { promptBlocksStorage: storage }); expect(result).toBe('Base.\n\nAnswer in a friendly, balanced style.'); }); it('requires both the ref rules and the stored block rules to pass', async () => { await storage.create({ promptBlock: { id: 'admin-only', name: 'Admin only', content: 'Admin tools are enabled.', rules: { operator: 'AND', conditions: [{ field: 'role', operator: 'equals', value: 'admin' }] }, }, }); await storage.update({ id: 'admin-only', status: 'published' }); const blocks: AgentInstructionBlock[] = [ { type: 'prompt_block_ref', id: 'admin-only', rules: { operator: 'AND', conditions: [{ field: 'beta', operator: 'equals', value: true }] }, }, ]; const deps = { promptBlocksStorage: storage }; expect(await resolveInstructionBlocks(blocks, { role: 'admin', beta: true }, deps)).toBe( 'Admin tools are enabled.', ); expect(await resolveInstructionBlocks(blocks, { role: 'admin', beta: false }, deps)).toBe(''); expect(await resolveInstructionBlocks(blocks, { role: 'viewer', beta: true }, deps)).toBe(''); }); it('applies rules per usage when the same block is referenced twice', async () => { const blocks: AgentInstructionBlock[] = [ { type: 'prompt_block_ref', id: 'shared-default-user-prompt', rules: { operator: 'AND', conditions: [{ field: 'tier', operator: 'equals', value: 'free' }] }, }, { type: 'prompt_block_ref', id: 'shared-default-user-prompt' }, ]; const result = await resolveInstructionBlocks(blocks, { tier: 'pro' }, { promptBlocksStorage: storage }); expect(result).toBe('Answer in a friendly, balanced style.'); }); }); it('should mix text and prompt_block_ref references', async () => { await storage.create({ promptBlock: { id: 'personality', name: 'Personality', content: 'Be friendly and concise.', }, }); await storage.update({ id: 'personality', status: 'published' }); const blocks: AgentInstructionBlock[] = [ { type: 'text', content: 'You are an AI assistant.' }, { type: 'prompt_block_ref', id: 'personality' }, { type: 'text', content: 'Always respond in {{language}}.' }, ]; const result = await resolveInstructionBlocks(blocks, { language: 'English' }, { promptBlocksStorage: storage }); expect(result).toBe('You are an AI assistant.\n\nBe friendly and concise.\n\nAlways respond in English.'); }); // --- Inline prompt_block tests --- it('should resolve an inline prompt_block', async () => { const blocks: AgentInstructionBlock[] = [ { type: 'prompt_block', content: 'You are a security-focused assistant.' }, ]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(result).toBe('You are a security-focused assistant.'); }); it('should resolve an inline prompt_block with template variables', async () => { const blocks: AgentInstructionBlock[] = [ { type: 'prompt_block', content: 'Welcome {{user.name}}, your tier is {{user.tier}}.' }, ]; const result = await resolveInstructionBlocks( blocks, { user: { name: 'Eve', tier: 'gold' } }, { promptBlocksStorage: storage }, ); expect(result).toBe('Welcome Eve, your tier is gold.'); }); it.each([ ['should include an inline prompt_block when rules pass', true, 'You have premium access.'], ['should exclude an inline prompt_block when rules fail', false, ''], ] as const)('%s', async (_title, isPremium, expected) => { const blocks: AgentInstructionBlock[] = [ { type: 'prompt_block', content: 'You have premium access.', rules: { operator: 'AND', conditions: [{ field: 'user.isPremium', operator: 'equals', value: true }], }, }, ]; const result = await resolveInstructionBlocks(blocks, { user: { isPremium } }, { promptBlocksStorage: storage }); expect(result).toBe(expected); }); it('should mix text, prompt_block_ref, and inline prompt_block', async () => { await storage.create({ promptBlock: { id: 'stored-block', name: 'Stored personality', content: 'Be concise and helpful.', }, }); await storage.update({ id: 'stored-block', status: 'published' }); const blocks: AgentInstructionBlock[] = [ { type: 'text', content: 'You are an AI assistant.' }, { type: 'prompt_block_ref', id: 'stored-block' }, { type: 'prompt_block', content: 'User language: {{language}}.', rules: { operator: 'AND', conditions: [{ field: 'language', operator: 'exists' }], }, }, ]; const result = await resolveInstructionBlocks(blocks, { language: 'Spanish' }, { promptBlocksStorage: storage }); expect(result).toBe('You are an AI assistant.\n\nBe concise and helpful.\n\nUser language: Spanish.'); }); it('should handle empty blocks array', async () => { const result = await resolveInstructionBlocks([], {}, { promptBlocksStorage: storage }); expect(result).toBe(''); }); it('should JSON-stringify array template variables in text blocks', async () => { const products = [ { productKey: 'royal-canin', variant: 'rcv31115' }, { productKey: 'zeal-treats', variant: 'dtz0110' }, ]; const blocks: AgentInstructionBlock[] = [{ type: 'text', content: 'Products in cart: {{products}}.' }]; const result = await resolveInstructionBlocks(blocks, { products }, { promptBlocksStorage: storage }); expect(result).toBe(`Products in cart: ${JSON.stringify(products)}.`); }); it('should JSON-stringify object template variables in prompt_block_ref content', async () => { await storage.create({ promptBlock: { id: 'block-obj', name: 'Object block', content: 'User prefs: {{preferences}}', }, }); await storage.update({ id: 'block-obj', status: 'published' }); const preferences = { theme: 'dark', notifications: true }; const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'block-obj' }]; const result = await resolveInstructionBlocks(blocks, { preferences }, { promptBlocksStorage: storage }); expect(result).toBe(`User prefs: ${JSON.stringify(preferences)}`); }); // --- Preview mode tests (includeDrafts) --- it('should include draft prompt_block_ref when includeDrafts is true', async () => { await storage.create({ promptBlock: { id: 'draft-block-preview', name: 'Draft Preview', content: 'Draft content for preview.', }, }); // Note: block is NOT published — status is 'draft' const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'draft-block-preview' }]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage, includeDrafts: true }); expect(result).toBe('Draft content for preview.'); }); it('should still skip draft prompt_block_ref when includeDrafts is false', async () => { await storage.create({ promptBlock: { id: 'draft-block-no-preview', name: 'Draft No Preview', content: 'Draft content should not appear.', }, }); const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'draft-block-no-preview' }]; const result = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage, includeDrafts: false }); expect(result).toBe(''); }); it('should resolve draft prompt_block_ref with template variables in preview mode', async () => { await storage.create({ promptBlock: { id: 'draft-tmpl', name: 'Draft template', content: 'Hello {{name}}, this is a draft preview.', }, }); const blocks: AgentInstructionBlock[] = [{ type: 'prompt_block_ref', id: 'draft-tmpl' }]; const result = await resolveInstructionBlocks( blocks, { name: 'Alice' }, { promptBlocksStorage: storage, includeDrafts: true }, ); expect(result).toBe('Hello Alice, this is a draft preview.'); }); it('should mix published and draft refs in preview mode', async () => { await storage.create({ promptBlock: { id: 'published-block', name: 'Published', content: 'Published content.', }, }); await storage.update({ id: 'published-block', status: 'published' }); await storage.create({ promptBlock: { id: 'draft-block-mix', name: 'Draft', content: 'Draft content.', }, }); const blocks: AgentInstructionBlock[] = [ { type: 'prompt_block_ref', id: 'published-block' }, { type: 'prompt_block_ref', id: 'draft-block-mix' }, ]; // Without preview: only published const resultNormal = await resolveInstructionBlocks(blocks, {}, { promptBlocksStorage: storage }); expect(resultNormal).toBe('Published content.'); // With preview: both const resultPreview = await resolveInstructionBlocks( blocks, {}, { promptBlocksStorage: storage, includeDrafts: true }, ); expect(resultPreview).toBe('Published content.\n\nDraft content.'); }); });