Skip to content

Commit 9591cc9

Browse files
committed
test(souls): pin that a soul that fails to load throws at build, and that an optional one runs without it
Signed-off-by: jddunn <[email protected]>
1 parent 728cb4b commit 9591cc9

2 files changed

Lines changed: 143 additions & 18 deletions

File tree

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
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+
});

‎src/api/__tests__/souledAgent.e2e.test.ts‎

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
* souledAgent() and agent({ soul }) end to end over the real agent, generateText, provider manager, Memory store and
33
* wiki; only the OpenAI provider class is stubbed (helpers/stubProviders.ts), at its module boundary.
44
*
5-
* - A soul that fails to load warns once per agent build, in production too.
5+
* - A soul given `optional: true` that fails to load writes one `soul.load_failed` line per agent build, in production
6+
* too.
67
* - The recall block a souled agent adds to a turn keeps to the turn's memory token budget.
78
* - Text migrated from a legacy MEMORY.md stays in memory/index.md, and so in the system prompt, after the wiki
89
* writes its catalog, even when it holds the end marker itself.
@@ -12,11 +13,13 @@ vi.mock('../../core/llm/providers/implementations/OpenAIProvider', async () => (
1213
import * as fs from 'node:fs';
1314
import * as os from 'node:os';
1415
import * as path from 'node:path';
16+
import pino from 'pino';
1517
import { agent, buildSystemPrompt, type AgentOptions } from '../agent';
1618
import { souledAgent } from '../souledAgent';
1719
import { reply, script, type ProviderScript } from './helpers/stubProviders';
1820
import { loadSoulSync } from '../../cognition/substrate/personas/SoulLoader';
1921
import { globalLLMProviderHealth } from '../../core/safety/LLMProviderHealthRegistry';
22+
import { resetLoggerFactory, setLogger } from '../../core/logging/loggerFactory';
2023

2124
let n = 0;
2225
const key = () => `k-souled-${++n}`;
@@ -35,36 +38,38 @@ afterEach(() => {
3538
fs.rmSync(dir, { recursive: true, force: true });
3639
});
3740

38-
/** Every console.warn line, its arguments joined. */
39-
const linesOf = (warn: { mock: { calls: unknown[][] } }) => warn.mock.calls.map((call) => call.map(String).join(' '));
40-
4141
/** The text of every system message one model call was sent. */
4242
const systemTexts = (call: ProviderScript['seen'][number]) =>
4343
call.messages.filter((m) => m.role === 'system').map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content)));
4444

45-
describe('a soul that fails to load', () => {
46-
it('warns once for agent() and once for souledAgent(), with NODE_ENV=production', async () => {
45+
describe('a soul given optional: true that fails to load', () => {
46+
const logged: Record<string, unknown>[] = [];
47+
const loadFailures = () => logged.filter((line) => line.event === 'soul.load_failed');
48+
beforeEach(() => {
49+
logged.length = 0;
50+
setLogger(pino({ level: 'debug', base: undefined }, { write(line: string) { logged.push(JSON.parse(line)); } }));
51+
});
52+
afterEach(() => resetLoggerFactory());
53+
54+
it('writes one line for agent() and one for souledAgent(), with NODE_ENV=production', async () => {
4755
vi.stubEnv('NODE_ENV', 'production');
48-
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
49-
const soulWarnings = () => linesOf(warn).filter((line) => line.includes('/no/such/soul'));
5056

51-
agent({ provider: 'openai', model: 'gpt-4o', soul: '/no/such/soul' });
52-
expect(soulWarnings()).toHaveLength(1);
53-
expect(soulWarnings()[0]).toMatch(/soul/i);
57+
agent({ provider: 'openai', model: 'gpt-4o', soul: { path: '/no/such/soul', optional: true } });
58+
expect(loadFailures()).toHaveLength(1);
59+
expect(JSON.stringify(loadFailures()[0])).not.toContain('/no/such/soul');
5460

55-
warn.mockClear();
56-
await souledAgent({ provider: 'openai', model: 'gpt-4o', soul: '/no/such/soul' });
57-
expect(soulWarnings()).toHaveLength(1);
61+
logged.length = 0;
62+
await souledAgent({ provider: 'openai', model: 'gpt-4o', soul: { path: '/no/such/soul', optional: true } });
63+
expect(loadFailures()).toHaveLength(1);
5864
});
5965

60-
it("warns once for an agent on runtime: 'gmi' that answers a turn", async () => {
66+
it("writes one line for an agent on runtime: 'gmi' that answers a turn", async () => {
6167
vi.stubEnv('NODE_ENV', 'production');
62-
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
6368
const k = key();
6469
script('openai', k, { replies: [reply.text('Hello.')] });
65-
const session = agent(stubbed(k, { runtime: 'gmi', soul: '/no/such/soul-gmi' } as Partial<AgentOptions>)).session('s');
70+
const session = agent(stubbed(k, { runtime: 'gmi', soul: { path: '/no/such/soul-gmi', optional: true } } as Partial<AgentOptions>)).session('s');
6671
expect((await session.send('hi')).text).toBe('Hello.');
67-
expect(linesOf(warn).filter((line) => line.includes('/no/such/soul-gmi'))).toHaveLength(1);
72+
expect(loadFailures()).toHaveLength(1);
6873
});
6974
});
7075

0 commit comments

Comments
 (0)