|
| 1 | +/** |
| 2 | + * A soul's identity end to end on every way of building an agent: agent({ soul }), souledAgent() and the GMI path. |
| 3 | + * Runs over the real agent, GMI, generateText, provider manager, Memory store and wiki; only the OpenAI provider class |
| 4 | + * is stubbed (helpers/stubProviders.ts), at its module boundary, and each model call's messages are read from the |
| 5 | + * script. |
| 6 | + */ |
| 7 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 8 | +vi.mock('../../core/llm/providers/implementations/OpenAIProvider', async () => ({ OpenAIProvider: (await import('./helpers/stubProviders')).stubProviderClass('openai') })); |
| 9 | +import * as fs from 'node:fs'; |
| 10 | +import * as os from 'node:os'; |
| 11 | +import * as path from 'node:path'; |
| 12 | +import pino from 'pino'; |
| 13 | +import { agent, type Agent, type AgentOptions } from '../agent'; |
| 14 | +import { gmi } from '../gmi'; |
| 15 | +import { souledAgent } from '../souledAgent'; |
| 16 | +import { SoulLoadError } from '../../cognition/substrate/personas/SoulLoader'; |
| 17 | +import { hardLimitsBlock } from '../../cognition/substrate/personas/hardLimits'; |
| 18 | +import { resetLoggerFactory, setLogger } from '../../core/logging/loggerFactory'; |
| 19 | +import { reply, script, type ProviderScript } from './helpers/stubProviders'; |
| 20 | +import { globalLLMProviderHealth } from '../../core/safety/LLMProviderHealthRegistry'; |
| 21 | + |
| 22 | +let n = 0; |
| 23 | +const key = () => `k-soul-identity-${++n}`; |
| 24 | +const stubbed = (apiKey: string, extra: Record<string, unknown> = {}) => |
| 25 | + ({ provider: 'openai', model: 'stub-model', apiKey, fallbackProviders: [], ...extra }) as unknown as AgentOptions; |
| 26 | + |
| 27 | +const LIMITS = ['Never name a diagnosis.', 'Never promise an outcome.']; |
| 28 | +const BLOCK = hardLimitsBlock(LIMITS)!; |
| 29 | +/** Front matter with an id, traits and hard limits. */ |
| 30 | +const FULL = [ |
| 31 | + 'name: Aria', 'agentId: aria-1', |
| 32 | + 'hexaco:', ' honestyHumility: 0.9', ' extraversion: 0.8', |
| 33 | + 'hardLimits:', ...LIMITS.map((limit) => ` - ${limit}`), |
| 34 | +].join('\n'); |
| 35 | + |
| 36 | +let dir: string; |
| 37 | +const logged: Record<string, unknown>[] = []; |
| 38 | +/** Writes SOUL.md into the test's soul folder. */ |
| 39 | +const writeSoul = (frontmatter: string, body = 'You are Aria.') => |
| 40 | + fs.writeFileSync(path.join(dir, 'SOUL.md'), frontmatter ? `---\n${frontmatter}\n---\n${body}` : body); |
| 41 | + |
| 42 | +beforeEach(() => { |
| 43 | + globalLLMProviderHealth.reset(); |
| 44 | + logged.length = 0; |
| 45 | + setLogger(pino({ level: 'debug', base: undefined }, { write(line: string) { logged.push(JSON.parse(line)); } })); |
| 46 | + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'soul-identity-e2e-')); |
| 47 | +}); |
| 48 | +afterEach(() => { |
| 49 | + resetLoggerFactory(); |
| 50 | + vi.restoreAllMocks(); |
| 51 | + vi.unstubAllEnvs(); |
| 52 | + fs.rmSync(dir, { recursive: true, force: true }); |
| 53 | +}); |
| 54 | + |
| 55 | +/** The log lines of one event. */ |
| 56 | +const events = (name: string) => logged.filter((line) => line.event === name); |
| 57 | +/** Every system text one model call was sent, in order: a string message is one text, a message of parts one text a part. */ |
| 58 | +const systemTexts = (call: ProviderScript['seen'][number]): string[] => |
| 59 | + call.messages |
| 60 | + .filter((m) => m.role === 'system') |
| 61 | + .flatMap((m) => (typeof m.content === 'string' ? [m.content] : (m.content as unknown as Array<{ text?: string }>).map((part) => part.text ?? ''))); |
| 62 | +/** The system text of one model call, joined. */ |
| 63 | +const systemOf = (call: ProviderScript['seen'][number]): string => systemTexts(call).join('\n\n'); |
| 64 | +/** The model calls that are turns: every call but the wiki compile's, which carries no system prompt. */ |
| 65 | +const turnCalls = (s: ProviderScript) => s.seen.filter((call) => !JSON.stringify(call.messages).includes('You maintain a knowledge wiki page')); |
| 66 | + |
| 67 | +describe('a soul that fails to load', () => { |
| 68 | + it('throws SoulLoadError from agent() and gmi() at build, and rejects souledAgent()', async () => { |
| 69 | + const missing = path.join(dir, 'nowhere'); |
| 70 | + const builds: Array<() => Agent> = [ |
| 71 | + () => agent(stubbed(key(), { soul: missing })), |
| 72 | + () => gmi(stubbed(key(), { soul: missing })), |
| 73 | + () => agent(stubbed(key(), { runtime: 'gmi', soul: { path: missing } })), |
| 74 | + ]; |
| 75 | + for (const build of builds) { |
| 76 | + let thrown: unknown; |
| 77 | + try { |
| 78 | + build(); |
| 79 | + } catch (error) { |
| 80 | + thrown = error; |
| 81 | + } |
| 82 | + expect(thrown).toBeInstanceOf(SoulLoadError); |
| 83 | + expect(thrown).toMatchObject({ code: 'SOUL_LOAD_FAILED', source: missing }); |
| 84 | + } |
| 85 | + await expect(souledAgent({ ...stubbed(key()), soul: missing } as never)).rejects.toBeInstanceOf(SoulLoadError); |
| 86 | + expect(events('soul.load_failed')).toEqual([]); |
| 87 | + }); |
| 88 | + |
| 89 | + it('throws naming the field when the front matter has a field of the wrong type', async () => { |
| 90 | + writeSoul('name: Aria\nhardLimits: never'); |
| 91 | + const message = "front matter field 'hardLimits' must be a list of strings"; |
| 92 | + expect(() => agent(stubbed(key(), { soul: dir }))).toThrow(message); |
| 93 | + expect(() => gmi(stubbed(key(), { soul: dir }))).toThrow(message); |
| 94 | + expect(() => agent(stubbed(key(), { soul: { content: '---\nhardLimits: never\n---\nHi.' } }))).toThrow(message); |
| 95 | + await expect(souledAgent({ ...stubbed(key()), soul: dir } as never)).rejects.toThrow(message); |
| 96 | + }); |
| 97 | + |
| 98 | + it.each([ |
| 99 | + ['agent()', (k: string, soul: unknown) => agent(stubbed(k, { soul }))], |
| 100 | + ['gmi()', (k: string, soul: unknown) => gmi(stubbed(k, { soul }))], |
| 101 | + ['souledAgent()', (k: string, soul: unknown) => souledAgent({ ...stubbed(k), soul } as never)], |
| 102 | + ] as const)('%s with optional: true runs without the soul and writes one soul.load_failed line', async (_name, build) => { |
| 103 | + const missing = path.join(dir, 'nowhere'); |
| 104 | + const k = key(); |
| 105 | + const s = script('openai', k, { whole: true, replies: [reply.text('Hello.')] }); |
| 106 | + const a = await build(k, { path: missing, optional: true }); |
| 107 | + try { |
| 108 | + expect((await a.session('s').send('Hi.')).text).toBe('Hello.'); |
| 109 | + } finally { |
| 110 | + await a.close(); |
| 111 | + } |
| 112 | + expect(s.seen).toHaveLength(1); |
| 113 | + const lines = events('soul.load_failed'); |
| 114 | + expect(lines).toHaveLength(1); |
| 115 | + expect(lines[0]).toMatchObject({ optional: 'yes', type: 'Error' }); |
| 116 | + // The line names no path and carries no message. |
| 117 | + expect(JSON.stringify(lines[0])).not.toContain('nowhere'); |
| 118 | + expect(lines[0]).not.toHaveProperty('msg'); |
| 119 | + }); |
| 120 | +}); |
0 commit comments