Skip to content

Commit dccd05f

Browse files
committed
test(memory): pin JSON page round trips, one compile at a time, seat page reads and store close on a failed open
Each new test fails on the branch as it stands: - a JSON export and import drop the scope registry and the page rows, and leave the page chunks with no row that lists them - two compiles of one scope at once send its traces to the model twice - Brain.importFromSqlite takes pages and registry rows of another brain than the file's brain_meta names - a wiki folder indexed for one agent id is not indexed again for another - a seat session whose id equals a user id reads that user's pages - a souled agent that fails after opening its store leaves the store open Signed-off-by: jddunn <[email protected]>
1 parent 88d9864 commit dccd05f

3 files changed

Lines changed: 183 additions & 1 deletion

File tree

‎src/api/__tests__/souledAgent.scoped-memory.gmi.e2e.test.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,24 @@ describe('sharedMemory, as it is given', () => {
645645
});
646646
});
647647

648+
describe('a souled agent that cannot open', () => {
649+
it('refuses an agent id no key can be built from before any store is made', async () => {
650+
writeSoul('aria\u0000');
651+
await expect(open()).rejects.toThrow(TypeError);
652+
expect(fs.existsSync(path.join(dir, 'memory', '.store'))).toBe(false);
653+
});
654+
655+
it('closes the store it opened when the agent is refused after it', async () => {
656+
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
657+
const closed = vi.spyOn(Memory.prototype, 'close');
658+
// A default-runtime agent refuses agencies.launch, once the store is open.
659+
await expect(souledAgent({ ...stubbed(key()), soul: dir, agencies: { launch: true } } as never)).rejects.toThrow(
660+
'agencies.launch runs on the GMI path',
661+
);
662+
expect(closed).toHaveBeenCalledTimes(1);
663+
});
664+
});
665+
648666
describe("the folder a souled agent's store is kept in", () => {
649667
it('is kept out of version control', async () => {
650668
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
@@ -1663,6 +1681,27 @@ describe("a souled agent on runtime: 'gmi', beyond its own sessions", () => {
16631681
}
16641682
});
16651683

1684+
it("a seat session's page tool reads the operator's pages, never those of the user its session id names", async () => {
1685+
writePage('concepts/ops', OPS);
1686+
const { a, s } = await openedWith({ runtime: 'gmi' }, [...readsPage({ list: true }, 'c1'), ...readsPage({ id: 'concepts/notes' }, 'c2')]);
1687+
try {
1688+
await writeOwnPage(a, userKey('bob'), OWL_PAGE);
1689+
const seat = sessionSeat(a as never, { sessionId: 'bob' });
1690+
1691+
await seat.generate('What can I read?');
1692+
const listed = toolAnswerIn(lastCall(s));
1693+
expect(listed).toContain('concepts/ops');
1694+
expect(listed).not.toContain('concepts/notes');
1695+
1696+
await seat.generate('Open the notes.');
1697+
const answer = toolAnswerIn(lastCall(s));
1698+
expect(answer).toContain('No memory page found with id');
1699+
expect(answer).not.toContain(OWL_PAGE);
1700+
} finally {
1701+
await a.close();
1702+
}
1703+
});
1704+
16661705
it("with cognitive memory on, a user reaches their pages through the listing and nobody else's", async () => {
16671706
const embeddings = key();
16681707
script('openai', embeddings, { replies: [] });
@@ -1694,7 +1733,7 @@ describe('the options cognitive memory does not reach', () => {
16941733
it.each<[string, Record<string, unknown>]>([
16951734
['memoryPolicy', { memoryPolicy: () => ({ longTerm: 'off' }) }],
16961735
['screen', { screen: async (text: string) => text }],
1697-
['sharedMemory', { sharedMemory: { as: 'johnny', reason: 'one-persons-machine' } }],
1736+
['sharedMemory', { sharedMemory: { as: 'me', reason: 'one-persons-machine' } }],
16981737
])('%s is refused at the open of an agent whose cognitive memory is on', async (_name, hook) => {
16991738
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
17001739
const embeddings = key();

‎src/cognition/memory/io/facade/__tests__/Memory.conversation-scope.e2e.test.ts‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,32 @@ describe.each(STORES)('the compile per scope on %s', (store) => {
621621
expect(compiledAt.get(B)).toBe(b1.createdAt);
622622
});
623623

624+
it('two compiles at once send the traces of a scope to the model once', async () => {
625+
const { memory } = await open(store);
626+
let release!: () => void;
627+
const gate = new Promise<void>((resolve) => {
628+
release = resolve;
629+
});
630+
const prompts = attachRows(memory, {
631+
llm: async () => {
632+
await gate;
633+
return 'Merged notes.';
634+
},
635+
});
636+
await memory.remember('Alice likes tea.', { scope: 'conversation', scopeId: A });
637+
await memory.remember('Alice has a cat.', { scope: 'conversation', scopeId: A });
638+
639+
// The second compile reads the scopes to compile while the first one's model call is held.
640+
const first = memory.compileWiki();
641+
const second = memory.compileWiki();
642+
for (let i = 0; i < 400 && prompts.length < 1; i += 1) await pause(5);
643+
await pause(50);
644+
release();
645+
await Promise.all([first, second]);
646+
647+
expect(prompts).toHaveLength(1);
648+
});
649+
624650
it('compiles nothing a second time, and only the scope with a new trace the third', async () => {
625651
const { memory } = await open(store);
626652
const prompts = attachRows(memory);
@@ -1217,6 +1243,75 @@ describe.each(STORES)('scopes kept apart on every path, on %s', (store) => {
12171243
expect(await traceIdsUnder(brain, A)).toEqual(chunkIdsOf(rows[0]!));
12181244
});
12191245

1246+
/** A brain that holds alice's page, one message of hers and a compile watermark, exported as JSON text. */
1247+
const exportedJson = async (): Promise<{ json: string; scopes: Awaited<ReturnType<Memory['listScopes']>> }> => {
1248+
const { memory, brain } = await open(store);
1249+
await new UserWikiStore({ scopeId: A, pages: memory, chunk }).writePage(P('Alice likes tea.\n\nAlice has a cat.', ['t1']));
1250+
await memory.remember('Alice said she likes tea.', { scope: 'conversation', scopeId: A });
1251+
await brain.run('UPDATE memory_scopes SET compiled_at = ? WHERE brain_id = ? AND scope_id = ?', [1_700_000_000_000, brain.brainId, A]);
1252+
return { json: await memory.exportToString(), scopes: await memory.listScopes() };
1253+
};
1254+
1255+
it("a JSON export carries each subject's pages and the scope registry, and an import brings them back", async () => {
1256+
const { json, scopes } = await exportedJson();
1257+
const { memory, brain } = await open(store);
1258+
1259+
const result = await memory.importFromString(json, 'json');
1260+
1261+
expect(result.errors).toEqual([]);
1262+
const pages = new UserWikiStore({ scopeId: A, pages: memory, chunk });
1263+
const page = await pages.readPage('concepts/notes');
1264+
expect(bodyOf(page)).toBe('Alice likes tea.\n\nAlice has a cat.');
1265+
expect(page?.sources).toEqual(['t1']);
1266+
// The row lists the chunks the import wrote, so no chunk is left that no row lists.
1267+
const rows = await pageRows(brain);
1268+
expect(rows).toHaveLength(1);
1269+
expect(chunkIdsOf(rows[0]!)).toEqual(await chunkTraceIdsUnder(brain, A));
1270+
expect(chunkIdsOf(rows[0]!)).toHaveLength(2);
1271+
expect(await contentsUnder(brain, A)).toEqual(['Alice has a cat.', 'Alice likes tea.', 'Alice said she likes tea.']);
1272+
// The scope comes with its watermark, so its next compile does not read the same traces again.
1273+
expect(await memory.listScopes()).toEqual(scopes);
1274+
expect(scopes.map((row) => row.compiledAt)).toEqual([1_700_000_000_000]);
1275+
1276+
// The page's next rewrite takes the chunks the import wrote, and leaves what alice said.
1277+
await pages.writePage(P('Alice drinks espresso.'));
1278+
expect(await contentsUnder(brain, A)).toEqual(['Alice drinks espresso.', 'Alice said she likes tea.']);
1279+
});
1280+
1281+
it("a JSON import keeps a page the brain already holds, and brings none of the file's chunks for it", async () => {
1282+
const { json } = await exportedJson();
1283+
const { memory, brain } = await open(store);
1284+
const pages = new UserWikiStore({ scopeId: A, pages: memory, chunk });
1285+
await pages.writePage(P('Alice drinks espresso.'));
1286+
const held = await chunkTraceIdsUnder(brain, A);
1287+
1288+
const result = await memory.importFromString(json, 'json');
1289+
1290+
expect(result.errors).toEqual([]);
1291+
expect(bodyOf(await pages.readPage('concepts/notes'))).toBe('Alice drinks espresso.');
1292+
expect(await chunkTraceIdsUnder(brain, A)).toEqual(held);
1293+
expect(chunkIdsOf((await pageRows(brain))[0]!)).toEqual(held);
1294+
expect(await contentsUnder(brain, A)).toEqual(['Alice drinks espresso.', 'Alice said she likes tea.']);
1295+
// The brain keeps its own watermark for a scope it already holds.
1296+
expect((await memory.listScopes()).map((row) => [row.scopeId, row.compiledAt])).toEqual([[A, null]]);
1297+
});
1298+
1299+
it("a JSON-imported message with the text of one of the brain's page chunks is stored as a trace of its own", async () => {
1300+
const source = await open(store);
1301+
await source.memory.remember('Alice likes tea.', { scope: 'conversation', scopeId: A });
1302+
const json = await source.memory.exportToString();
1303+
const { memory, brain } = await open(store);
1304+
const pages = new UserWikiStore({ scopeId: A, pages: memory, chunk });
1305+
await pages.writePage(P('Alice likes tea.'));
1306+
1307+
const result = await memory.importFromString(json, 'json');
1308+
1309+
expect(result.errors).toEqual([]);
1310+
expect(await contentsUnder(brain, A)).toEqual(['Alice likes tea.', 'Alice likes tea.']);
1311+
await pages.writePage(P('Alice drinks espresso.'));
1312+
expect(await contentsUnder(brain, A)).toEqual(['Alice drinks espresso.', 'Alice likes tea.']);
1313+
});
1314+
12201315
// These run the consolidation loop on a store of its own, or write and read a SQLite export file.
12211316
if (store === 'sqlite') {
12221317
/** A facade on a fresh SQLite file, with the options given. */
@@ -1359,6 +1454,31 @@ describe.each(STORES)('scopes kept apart on every path, on %s', (store) => {
13591454
expect(await pageRows(brain)).toEqual([]);
13601455
});
13611456

1457+
it('a merge of a brain file whose pages and registry rows name another brain than its meta is refused', async () => {
1458+
const { memory: source, dir } = await openWith({ selfImprove: false });
1459+
await source.writePageRow(A, { pageId: 'concepts/notes', content: 'Alice likes tea.\n', contentHash: 'h-alice' });
1460+
const file = path.join(dir, 'pages.sqlite');
1461+
await source.export(file, { format: 'sqlite' });
1462+
await editFile(file, async (db) => {
1463+
await db.run(
1464+
`INSERT INTO memory_scopes (brain_id, scope, scope_id, kind, agent_id, created_at)
1465+
VALUES ('another-brain', 'conversation', ?, 'user', 'aria-1', 1)`,
1466+
[B],
1467+
);
1468+
await db.run(
1469+
`INSERT INTO memory_pages (brain_id, scope, scope_id, page_id, content, content_hash, chunk_ids, updated_at)
1470+
VALUES ('another-brain', 'conversation', ?, 'concepts/notes', 'Bob plays cello.', 'h-bob', '[]', 1)`,
1471+
[B],
1472+
);
1473+
});
1474+
const { brain } = await openWith({ selfImprove: false });
1475+
1476+
await expect(brain.importFromSqlite(file, { strategy: 'merge' })).rejects.toThrow('multiple brain_ids');
1477+
1478+
expect(await pageRows(brain)).toEqual([]);
1479+
expect(await scopeRows(brain)).toEqual([]);
1480+
});
1481+
13621482
it("an imported message with the text of one of the brain's page chunks is stored as a trace of its own", async () => {
13631483
const source = await openWith({ selfImprove: false });
13641484
await source.memory.remember('Alice likes tea.', { scope: 'conversation', scopeId: A });

‎src/cognition/substrate/memory/wiki/__tests__/WikiMemoryStore.index.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,29 @@ describe('WikiMemoryStore.index', () => {
9292
expect(meta.pages).toEqual({});
9393
});
9494

95+
it("indexes every page again under the agent's own key when the folder's index names another agent's", async () => {
96+
const port = fakePort();
97+
const first = new WikiMemoryStore({ memoryDir, port, agentId: 'a1' });
98+
await first.writePage({ id: 'concepts/ops', type: 'concept', summary: '', updated: '', sources: [], body: 'Open nine to five.', links: [] });
99+
await first.index();
100+
expect(port.remembered[0].options.scopeId).toBe('c1:o:2:a1:0:;');
101+
102+
// The same folder opened as another agent: its pages are unchanged, and their chunks sit under the first key.
103+
const second = new WikiMemoryStore({ memoryDir, port, agentId: 'a2' });
104+
const res = await second.index();
105+
106+
expect(res.indexed).toEqual(['concepts/ops']);
107+
expect(port.remembered).toHaveLength(2);
108+
expect(port.remembered[1].options).toMatchObject({ scope: 'conversation', scopeId: 'c1:o:2:a2:0:;' });
109+
// The chunks under the first key, which no turn of this agent reads, are deleted.
110+
expect(res.removed).toEqual(['t1']);
111+
expect(port.deleted).toEqual([['t1']]);
112+
113+
// An unchanged page is skipped while the key stays the same.
114+
expect((await second.index()).skipped).toEqual(['concepts/ops']);
115+
expect(port.remembered).toHaveLength(2);
116+
});
117+
95118
it('indexes no page a compile wrote, and none whose sources it cannot read', async () => {
96119
const port = fakePort();
97120
const store = new WikiMemoryStore({ memoryDir, port, agentId: 'a1' });

0 commit comments

Comments
 (0)