Skip to content

Commit 014cd9d

Browse files
committed
fix(memory): carry the scope registry and the wiki pages through a JSON export and import
The JSON export now holds the brain's memory_scopes rows (with their compile watermark) as scopes and its memory_pages rows as pages. The JSON import brings them back by the rules the SQLite import already follows, now shared in importPages.ts: a scope the brain registers keeps its own row, a page the brain holds is kept and the file's chunks of it stay out, any other page comes in with its chunks written as traces of their own and listed under the ids they were written under, and a message is never merged into a page chunk of the same text. Before, a JSON round trip dropped every page row and left the page chunks in the store with no row that lists them, still recalled. The docs say what the JSON export carries, and that Brain.importFromSqlite refuses a file whose page and registry rows name more than one brain. Signed-off-by: jddunn <[email protected]>
1 parent dccd05f commit 014cd9d

6 files changed

Lines changed: 340 additions & 132 deletions

File tree

‎docs/MEMORY_OPERATIONS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,7 @@ All under [`src/cognition/memory/io/tools/`](https://github.com/framerslab/agent
525525
## Import and Export
526526

527527

528-
> The Memory I/O subsystem exports to four formats and imports from six. The SQLite and JSON exports carry the whole brain: JSON holds traces, graph rows, documents, chunks, images, conversations, and messages. Markdown and Obsidian exports carry the active traces only. Trace deduplication is on by default on import.
528+
> The Memory I/O subsystem exports to four formats and imports from six. The SQLite and JSON exports carry the whole brain: JSON holds traces, graph rows, documents, chunks, images, conversations, messages, the registry of conversation scopes and each subject's wiki pages. Markdown and Obsidian exports carry the active traces only. Trace deduplication is on by default on import.
529529
530530

531531
### Overview
@@ -555,7 +555,7 @@ await mem.export('./backup.sqlite', { format: 'sqlite' });
555555

556556
### JSON (Programmatic)
557557

558-
A single structured JSON document containing the full portable brain payload. Designed for programmatic consumption, browser-safe transfer, and cross-runtime restore.
558+
A single structured JSON document containing the full portable brain payload, with the registry of conversation scopes (`scopes`, each with its compile watermark) and each subject's wiki pages (`pages`, each listing its chunks among `traces`). Designed for programmatic consumption, browser-safe transfer, and cross-runtime restore. Its import brings the scopes and the pages back by the rules of the SQLite import ([Memory storage](memory/MEMORY_STORAGE.md#export-and-backup)).
559559

560560
```ts
561561
await mem.export('./memories.json', { format: 'json' });

‎docs/memory/MEMORY_STORAGE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ await mem.export('./vault/', { format: 'obsidian' });
225225

226226
The `sqlite` export goes through [`Brain.exportToSqlite(targetPath)`](https://github.com/framerslab/agentos/blob/master/src/cognition/memory/retrieval/store/Brain.ts), from a SQLite or a Postgres brain alike: it writes this brain's rows of every portable table to a new file, the registry of conversation scopes (`memory_scopes`) and each subject's wiki pages (`memory_pages`) with them, and throws when the target exists. A Postgres brain, and a SQLite file in WAL mode as `Brain.openSqlite` opens one, are read from one consistent view of the database; a brain on one connection, such as an in-memory SQLite database, is read statement by statement. Its `brain_meta` rows carry the brain's scope-id form record where the brain has one, read before the rows and again after them, and the export copies again when a re-file commits while it reads, so the file's record names the form its rows are in and an import of the file keeps the form ([A Brain's scope-id form](../MEMORY_OPERATIONS.md#a-brains-scope-id-form)).
227227

228-
An import of that file (`mem.importFrom('./backup.sqlite')`, or `Brain.importFromSqlite`) brings the pages and the registry back. A scope the brain already registers keeps its own row and compile watermark, and any other comes in with the file's, so its next compile does not read the same traces again; a message the import stores under a scope the brain had compiled past that message's time moves the scope's watermark back to just before it, so its next compile reads it. A message is never matched as a duplicate of a page chunk of the same text. A file whose `memory_scopes` or `memory_pages` table cannot be read is refused before anything is written, with the reason in `errors`, and a file whose rows of any table, the two tables among them, belong to more than one brain is refused as such. A page the brain already holds, by scope and page id, is kept: the file's page is skipped, and so are that page's chunks. Any other page comes in with its chunks, written as traces of their own, and its row lists the ids they were written under. `Brain.importFromSqlite(file, { strategy: 'replace' })` empties both tables for the brain first, as it empties the portable tables. The JSON, Markdown and Obsidian exports carry traces, the chunks of pages among them, and no page row and no registry row: use the `sqlite` format to move a store whose subjects have pages.
228+
An import of that file (`mem.importFrom('./backup.sqlite')`, or `Brain.importFromSqlite`) brings the pages and the registry back. A scope the brain already registers keeps its own row and compile watermark, and any other comes in with the file's, so its next compile does not read the same traces again; a message the import stores under a scope the brain had compiled past that message's time moves the scope's watermark back to just before it, so its next compile reads it. A message is never matched as a duplicate of a page chunk of the same text. A file whose `memory_scopes` or `memory_pages` table cannot be read is refused before anything is written, with the reason in `errors`, and a file whose rows of any table, the two tables among them, belong to more than one brain is refused as such (`Brain.importFromSqlite` throws, naming the brain ids, when its `brain_meta`, `memory_scopes` and `memory_pages` rows name more than one). A page the brain already holds, by scope and page id, is kept: the file's page is skipped, and so are that page's chunks. Any other page comes in with its chunks, written as traces of their own, and its row lists the ids they were written under. `Brain.importFromSqlite(file, { strategy: 'replace' })` empties both tables for the brain first, as it empties the portable tables. The JSON export carries the registry (`scopes`) and the pages (`pages`) beside the traces, and its import (`mem.importFrom('./backup.json')` or `mem.importFromString(text, 'json')`) brings them back by the same rules. The Markdown and Obsidian exports carry traces, the chunks of pages among them, and no page row and no registry row: use the `sqlite` or `json` format to move a store whose subjects have pages.
229229

230230
The facade has no backup schedule; a host that wants one calls `export()` from a timer:
231231

‎src/cognition/memory/io/JsonExporter.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
* @fileoverview JSON exporter for AgentOS memory brain.
33
*
44
* Serialises all memory traces, knowledge graph nodes/edges, document registry
5-
* rows, document chunks/images, conversations, and conversation messages from
5+
* rows, document chunks/images, conversations, conversation messages, the
6+
* registry of conversation scopes and each subject's wiki pages from
67
* a `Brain` into a single structured JSON file.
78
* Optionally includes raw embedding vectors encoded as base64 strings.
89
*
@@ -17,10 +18,15 @@
1718
* "chunks": [...],
1819
* "images": [...],
1920
* "conversations": [...],
20-
* "messages": [...]
21+
* "messages": [...],
22+
* "scopes": [...],
23+
* "pages": [...]
2124
* }
2225
* ```
2326
*
27+
* `scopes` holds the brain's registry of conversation scopes (`memory_scopes`, each with its compile watermark) and
28+
* `pages` each subject's wiki pages (`memory_pages`, each listing the ids of its chunks among `traces`).
29+
*
2430
* A Brain a learning layer serves writes its record of the encoded scope-id
2531
* form into `meta` (`scope_id_form`), which an import reads as the export's
2632
* form. The record and the rows come from one form: when a re-file commits
@@ -133,6 +139,16 @@ interface MessageRow {
133139
metadata: string;
134140
}
135141

142+
/** A registry or page row with its times as numbers: a BIGINT column can come back as text (Postgres). */
143+
function numericTimes(row: Record<string, unknown>): Record<string, unknown> {
144+
const out: Record<string, unknown> = { ...row };
145+
for (const column of ['created_at', 'compiled_at', 'updated_at']) {
146+
const value = out[column];
147+
if (typeof value === 'string' && value !== '') out[column] = Number(value);
148+
}
149+
return out;
150+
}
151+
136152
// ---------------------------------------------------------------------------
137153
// JsonExporter
138154
// ---------------------------------------------------------------------------
@@ -248,6 +264,19 @@ export class JsonExporter {
248264
? await this.brain.all<MessageRow>('SELECT * FROM messages WHERE brain_id = ?', [brainId])
249265
: [];
250266

267+
// ---- memory_scopes, memory_pages ----
268+
// The registry of conversation scopes and each subject's wiki pages: a page's row lists its chunks among the
269+
// traces, so a restore without the rows would leave chunks no row lists.
270+
const scopes = await this.brain.all<Record<string, unknown>>(
271+
'SELECT scope, scope_id, kind, agent_id, created_at, compiled_at FROM memory_scopes WHERE brain_id = ?',
272+
[brainId],
273+
);
274+
const pages = await this.brain.all<Record<string, unknown>>(
275+
`SELECT scope, scope_id, page_id, content, content_hash, chunk_ids, updated_at
276+
FROM memory_pages WHERE brain_id = ?`,
277+
[brainId],
278+
);
279+
251280
return {
252281
meta,
253282
traces,
@@ -258,6 +287,8 @@ export class JsonExporter {
258287
images,
259288
conversations,
260289
messages,
290+
scopes: scopes.map(numericTimes),
291+
pages: pages.map(numericTimes),
261292
};
262293
}
263294

‎src/cognition/memory/io/JsonImporter.ts‎

Lines changed: 94 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
*
44
* Reads a JSON file produced by `JsonExporter` (or a compatible schema) and
55
* merges traces, graph rows, documents, document chunks/images, conversations,
6-
* and messages into a target `Brain`.
6+
* messages, the registry of conversation scopes and each subject's wiki pages
7+
* into a target `Brain`.
78
*
89
* Trace deduplication is performed inside the trace's scope and scope id by
910
* default: a trace there whose text is the record's, or whose metadata names
@@ -29,6 +30,16 @@
2930
* another id because its id names another trace, or does not write, is
3031
* skipped, with the edges that name it.
3132
*
33+
* The registry of conversation scopes (`scopes`) and the wiki pages (`pages`)
34+
* come in by the rules the SQLite import uses (`importPages.ts`): a scope the
35+
* brain already registers keeps its own row and compile watermark; a page the
36+
* brain already holds, by scope and page id, is kept, and the file's chunks of
37+
* it stay out; any other page comes in with its chunks, written as traces of
38+
* their own, and its row lists the ids they were written under. A message is
39+
* never matched as a duplicate of a page chunk of the same text, and one stored
40+
* under a scope the brain had compiled past its time moves the scope's
41+
* watermark back to just before it.
42+
*
3243
* A Brain a learning layer serves holds its plain `user` and `persona` scope
3344
* ids in the encoded form (`scopeIdForm.ts`), and its export's `meta` names
3445
* the record (`scope_id_form`). An export without it is in the plain form, and
@@ -63,6 +74,13 @@ import {
6374
import { fillScopeIds } from '../retrieval/store/migrations/v2-to-v3.js';
6475
import { keyTraceCopies, storedCopyTraceId } from '../retrieval/store/SqlKnowledgeGraph.js';
6576
import { parseTraceMetadata } from '../retrieval/store/tracePersistence.js';
77+
import {
78+
conversationPagesOf,
79+
type ImportedScopeRow,
80+
mergeImportedScopesAndPages,
81+
registeredConversationScopes,
82+
splitImportedPages,
83+
} from './importPages.js';
6684
import {
6785
ENCODED_SCOPE_ID_FORM,
6886
encodedCopyProperties,
@@ -92,6 +110,10 @@ interface BrainExportPayload {
92110
images?: DocumentImageRecord[];
93111
conversations?: ConversationRecord[];
94112
messages?: MessageRecord[];
113+
/** The registry of conversation scopes (`memory_scopes` rows). */
114+
scopes?: unknown[];
115+
/** Each subject's wiki pages (`memory_pages` rows). */
116+
pages?: unknown[];
95117
}
96118

97119
/** Serialised memory trace from the export file. */
@@ -199,6 +221,12 @@ interface ImportContext {
199221
*/
200222
encodePlainIds: boolean;
201223
traceIds: Map<string, string>;
224+
/** For each payload trace the import wrote: the id it was written under. */
225+
writtenTraceIds: Map<string, string>;
226+
/** The rows the import wrote to `memory_traces`: their scope, scope id, time and tags. */
227+
storedTraces: Array<{ scope: string; scope_id: string; created_at: number; tags: string }>;
228+
/** The payload ids of the chunks of the pages that come in: each is written as a trace of its own. */
229+
pageChunks: ReadonlySet<string>;
202230
/** The payload's trace ids. */
203231
sourceTraceIds: Set<string>;
204232
/** The payload's trace ids the import wrote, or matched as a duplicate, under that same id. */
@@ -327,6 +355,9 @@ export class JsonImporter {
327355
dedup: options?.dedup ?? true,
328356
encodePlainIds: false,
329357
traceIds: new Map<string, string>(),
358+
writtenTraceIds: new Map<string, string>(),
359+
storedTraces: [],
360+
pageChunks: new Set<string>(),
330361
sourceTraceIds: new Set<string>(),
331362
filedTraceIds: new Set<string>(),
332363
skippedNodeIds: new Set<string>(),
@@ -349,7 +380,32 @@ export class JsonImporter {
349380
if (decision.action === 'record') await writeScopeIdFormRecord(trx, this.brain);
350381
// A trace an older release wrote holds scope_id '': filed under its scope id first, it is found there.
351382
if (context.dedup) await fillScopeIds(trx, this.brain.brainId);
352-
await this._importTraces(trx, payload.traces, result, context);
383+
// A page this brain already holds is kept: the file's page of that scope and id is left out, its chunks with it.
384+
// The chunks of a page that comes in are written as traces of their own.
385+
const brainId = this.brain.brainId;
386+
const split = await splitImportedPages(trx, brainId, conversationPagesOf(Array.isArray(payload.pages) ? payload.pages : []));
387+
result.skipped += split.kept;
388+
context.pageChunks = split.chunksIn;
389+
// The scopes this brain registered before the import: a message stored under one of them older than its compile
390+
// is read by its next compile.
391+
const held = await registeredConversationScopes(trx, brainId);
392+
const traces =
393+
split.chunksLeftOut.size > 0
394+
? payload.traces.filter((t) => !(t !== null && typeof t === 'object' && typeof t.id === 'string' && split.chunksLeftOut.has(t.id)))
395+
: payload.traces;
396+
await this._importTraces(trx, traces, result, context);
397+
result.imported += await mergeImportedScopesAndPages(
398+
trx,
399+
brainId,
400+
{
401+
held,
402+
scopes: (Array.isArray(payload.scopes) ? payload.scopes : []) as ImportedScopeRow[],
403+
pages: split.pagesIn,
404+
written: context.writtenTraceIds,
405+
stored: context.storedTraces,
406+
},
407+
result.errors,
408+
);
353409
const memoryNodes = await this._importNodes(trx, payload.nodes ?? [], result, context);
354410
await this._importEdges(trx, payload.edges ?? [], result, context);
355411
// A trace's copy is found by its trace's key: one written under another node id gets the key here.
@@ -421,16 +477,26 @@ export class JsonImporter {
421477
* @param result - Mutable `ImportResult` to accumulate counts.
422478
*/
423479
private async _importTraces(
424-
trx: { run: Brain['run']; get: Brain['get'] },
480+
trx: { run: Brain['run']; get: Brain['get']; all: Brain['all'] },
425481
traces: TraceRecord[],
426482
result: ImportResult,
427483
context: ImportContext,
428484
): Promise<void> {
429485
const brainId = this.brain.brainId;
430-
const checkSql = `SELECT id FROM memory_traces
486+
// A chunk of a wiki page is its page's: a message of the same text is not one with it, or the page's next rewrite,
487+
// which deletes its chunks, would take what a person said. The tags are a JSON array in text, tested below.
488+
const checkSql = `SELECT id, tags FROM memory_traces
431489
WHERE brain_id = ? AND scope = ? AND scope_id = ?
432490
AND ${duplicateTraceCondition(this.brain)}
433-
LIMIT 1`;
491+
LIMIT 50 OFFSET ?`;
492+
const isPageChunk = (tags: string): boolean => {
493+
try {
494+
const parsed: unknown = JSON.parse(tags);
495+
return Array.isArray(parsed) && parsed.includes('wiki');
496+
} catch {
497+
return false;
498+
}
499+
};
434500

435501
const insertSql = `INSERT INTO memory_traces
436502
(brain_id, id, type, scope, content, embedding, strength, created_at, last_accessed,
@@ -454,10 +520,23 @@ export class JsonImporter {
454520
if (scopeId !== '') meta.scopeId = scopeId;
455521
}
456522

457-
if (context.dedup) {
458-
const existing = await trx.get<{ id: string }>(checkSql, [
459-
brainId, scope, scopeId, ...duplicateTraceParams(hash, t.content, importedTurnUserId(meta)),
460-
]);
523+
// A chunk of a page that comes in is a row of its own: merged into a trace the brain holds, the page would list
524+
// a trace that is not its chunk, and its next rewrite would delete it.
525+
if (context.dedup && !(sourceId && context.pageChunks.has(sourceId))) {
526+
// Read 50 candidates at a time until one that is not a page chunk is found: any number of chunks of the same
527+
// text can come first.
528+
let existing: { id: string; tags: string } | undefined;
529+
for (let offset = 0; ; offset += 50) {
530+
const candidates = await trx.all<{ id: string; tags: string }>(checkSql, [
531+
brainId,
532+
scope,
533+
scopeId,
534+
...duplicateTraceParams(hash, t.content, importedTurnUserId(meta)),
535+
offset,
536+
]);
537+
existing = candidates.find((candidate) => !isPageChunk(candidate.tags));
538+
if (existing || candidates.length < 50) break;
539+
}
461540
if (existing) {
462541
if (sourceId) context.traceIds.set(sourceId, existing.id);
463542
if (sourceId && existing.id === sourceId) context.filedTraceIds.add(sourceId);
@@ -481,6 +560,8 @@ export class JsonImporter {
481560
sourceId ?? `mt_${uuidv4()}`,
482561
'mt_',
483562
);
563+
const createdAt = t.created_at ?? Date.now();
564+
const tags = t.tags ?? '[]';
484565

485566
await trx.run(insertSql, [
486567
brainId,
@@ -490,18 +571,20 @@ export class JsonImporter {
490571
t.content,
491572
embeddingBuf,
492573
t.strength ?? 1.0,
493-
t.created_at ?? Date.now(),
574+
createdAt,
494575
t.last_accessed ?? null,
495576
t.retrieval_count ?? 0,
496-
t.tags ?? '[]',
577+
tags,
497578
t.emotions ?? '{}',
498579
JSON.stringify(meta),
499580
t.deleted ?? 0,
500581
scopeId,
501582
]);
502583

503584
if (sourceId) context.traceIds.set(sourceId, id);
585+
if (sourceId) context.writtenTraceIds.set(sourceId, id);
504586
if (sourceId && id === sourceId) context.filedTraceIds.add(sourceId);
587+
context.storedTraces.push({ scope, scope_id: scopeId, created_at: createdAt, tags });
505588
result.imported++;
506589
} catch (err) {
507590
result.errors.push(`Trace import error: ${String(err)}`);

0 commit comments

Comments
 (0)