Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): preserve extension-bearing page identities (#5841, #5840)

garrytanbab19beb0e0c
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index f32ebea465..7a0763b8c8 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -124,7 +124,8 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
if (!Buffer.from(text).equals(raw)) throw new OperationError('invalid_params', 'The canonical file must contain valid UTF-8.');
try { parseDataFrontmatter(text); }
catch { throw new OperationError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.'); }
- const parsed = parseMarkdown(text, slug, { validate: true, expectedSlug: slug });
+ // Preserve a terminal .md in the page key while parsing the canonical Markdown.
+ const parsed = parseMarkdown(text, `${slug}.md`, { validate: true, expectedSlug: slug });
const errors = parsed.errors?.filter(e => !['MISSING_OPEN', 'MISSING_CLOSE', 'EMPTY_FRONTMATTER'].includes(e.code)) ?? [];
if (errors.length || parsed.errors?.some(e => e.code === 'MISSING_CLOSE') || parsed.slug !== slug) {
throw new OperationError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.');
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 4c90c74983..0db36750f9 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -193,7 +193,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (renamed && (base?.page.id !== renamed.pageId || base.revision !== renamed.revision || base.page.deleted_at != null)) {
throw new OperationError('revision_conflict', 'The renamed page changed after sync admission.');
}
- const parsedInput = parseMarkdown(p.content, row.slug, { activePack });
+ // row.slug is already resolved; parseMarkdown expects a filename, as in importFromContent.
+ const parsedInput = parseMarkdown(p.content, `${row.slug}.md`, { activePack });
resolveParsedSubtype(parsedInput, base?.page);
const expectedSlug = resolveSlugForPath(p.sourcePath);
const retainedWindowsOrigin = process.platform === 'win32' && snapshot?.page.source_path != null &&
@@ -209,7 +210,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
// The checkpoint may advance past the pinned commit's bytes because the working tree wins, as for any local edit.
const working = renamed ? null : readSyncFile(root, p.path);
if (!working || sha256(working) !== p.rawHash
- || !sameCanonicalImport(base, parseMarkdown(working.toString('utf8'), row.slug, { activePack }))) {
+ || !sameCanonicalImport(base, parseMarkdown(working.toString('utf8'), `${row.slug}.md`, { activePack }))) {
throw new OperationError('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.');
}
return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,
@@ -237,7 +238,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
// guarded proof about the other identity. Keep the cursor explicitly blocked.
throw new OperationError('revision_conflict', 'A different page already owns this file identity; resolve the duplicate before syncing.');
}
- const parsed = parseMarkdown(p.content, row.slug, { activePack });
+ const parsed = parseMarkdown(p.content, `${row.slug}.md`, { activePack });
resolveParsedSubtype(parsed, base?.page);
const tags = [...new Set([...(base?.tags ?? []), ...ready.parsedPage.tags])].sort();
const renderedPage = { ...(base?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index e8e1b8016e..d4a15be775 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -447,3 +447,51 @@ test('continuous foreground arrivals cannot starve a bounded sync batch', async
}finally{stopping=true;clearInterval(timer);await Promise.all(admitted);await disposePersistenceConsumer(engine);}
}
}),120_000);
+
+// Page identity must survive repeated suffixes. Existing sync cases only used
+// extension-free slugs; this exercises actual publication, without a new seam.
+test('managed sync preserves extension-bearing slugs and their distinct extension-free siblings', async () =>
+ withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const content = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\n---\n${body}\n`;
+ const ordinary = content('Ordinary', 'The ordinary page remains separate.');
+ const extended = content('Extended', 'The extension-bearing page keeps its identity.');
+ // No explicit title: the overlay comparison must use the same filename fallback as import.
+ const repeated = '---\ntype: note\n---\nThe repeated-extension page is separate too.\n';
+ const f = await fixture(engine, {
+ 'notes/example.md': ordinary,
+ 'notes/example.md.md': extended,
+ 'notes/example.md.md.md': repeated,
+ });
+ const opts = { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true };
+ expect(await performManagedSync(engine, opts)).toMatchObject({ status: 'first_sync', added: 3 });
+ const slugs = ['notes/example', 'notes/example.md', 'notes/example.md.md'];
+ const before = await Promise.all(slugs.map(slug => engine.getPage(slug, { sourceId: f.id })));
+ expect(new Set(before.map(page => page?.id)).size).toBe(3);
+ expect(before.map(page => page?.title)).toEqual(['Ordinary', 'Extended', 'Example.Md.Md']);
+ expect(before.map(page => page?.source_path)).toEqual(slugs.map(slug => `${slug}.md`));
+ expect(readFileSync(join(f.root, 'notes/example.md.md.md'), 'utf8')).toBe(repeated);
+ for (const slug of slugs) expect(readFileSync(join(f.root, `${slug}.md`), 'utf8')).not.toContain('slug:');
+ writeFileSync(join(f.root, 'notes/example.md.md'), content('Extended', 'Updated extension-bearing content.'));
+ const head = commit(f.root, 'update extension-bearing page');
+ expect(await performManagedSync(engine, opts)).toMatchObject({ status: 'synced', modified: 1, toCommit: head });
+ const after = await Promise.all(slugs.map(slug => engine.getPage(slug, { sourceId: f.id })));
+ expect(after.map(page => page?.id)).toEqual(before.map(page => page?.id));
+ expect(after[0]?.compiled_truth).toBe(before[0]?.compiled_truth);
+ expect(after[1]?.compiled_truth).toContain('Updated extension-bearing content.');
+ expect(after[2]?.compiled_truth).toBe(before[2]?.compiled_truth);
+ expect(await performManagedSync(engine, opts)).toMatchObject({ status: 'up_to_date' });
+ }
+ }), 120_000);
+
+test('managed sync still rejects conflicting explicit slugs on extension-bearing paths', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, { 'notes/example.md.md':
+ '---\ntype: note\ntitle: Example\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' });
+ expect(await performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true }))
+ .toMatchObject({ status: 'blocked_by_failures', failedFiles: 1 });
+ expect(await engine.getPage('notes/example.md', { sourceId: f.id })).toBeNull();
+ expect(await engine.getPage('notes/other', { sourceId: f.id })).toBeNull();
+ }
+ }), 120_000);
diff --git a/test/persistence-reconcile.test.ts b/test/persistence-reconcile.test.ts
index dd9ff49c5e..fb1bcea43d 100644
--- a/test/persistence-reconcile.test.ts
+++ b/test/persistence-reconcile.test.ts
@@ -43,16 +43,16 @@ afterAll(async () => {
});
await closePostgres?.(); rmSync(home, { recursive: true, force: true });
});
-async function fixture(engine: BrainEngine, enabled = false, body = 'A useful durable example observation.') {
+async function fixture(engine: BrainEngine, enabled = false, body = 'A useful durable example observation.', slug = 'notes/example') {
await disposePersistenceConsumer(engine);
await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
- const id = `reconcile-${randomUUID().slice(0, 12)}`, root = join(home, id), slug = 'notes/example';
+ const id = `reconcile-${randomUUID().slice(0, 12)}`, root = join(home, id);
mkdirSync(join(root, 'notes'), { recursive: true });
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
const content = `---\ntype: note\ntitle: Example\ncustom_database: kept\nprofile:\n role: example-role\n---\n${body}\n`;
- await importFromContent(engine, slug, content, { sourceId: id, sourcePath: 'notes/example.md', noEmbed: true });
+ await importFromContent(engine, slug, content, { sourceId: id, sourcePath: `${slug}.md`, noEmbed: true });
const snapshot = (await engine.readPageSnapshot(slug, { sourceId: id }))!;
- const file = join(root, 'notes/example.md');
+ const file = join(root, `${slug}.md`);
writeFileSync(file, serializePageToMarkdown({ ...snapshot.page, frontmatter: { profile: { location: 'example-place' }, custom_file: 'kept' } }, snapshot.tags));
const binding = await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=$1 WHERE singleton=1', [enabled]);
@@ -644,3 +644,29 @@ test('candidate-origin fanout stops at a bounded verification limit rather than
expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toHaveLength(0);
});
}), 120_000);
+
+// The parser must not normalize an already-resolved identity a second time.
+// Existing reconcile cases only covered extension-free page keys.
+test.each(['notes/example.md', 'notes/example.md.md'])('reconciliation preserves extension-bearing identity %s', async slug =>
+ isolated(async engine => {
+ const f = await fixture(engine, true, 'A durable extension-bearing observation.', slug);
+ expect(readFileSync(f.file, 'utf8')).not.toContain('slug:');
+ await local(engine, f.registration, async () => {
+ const { preview, status } = await runReconcilePreview(engine, { source_id: f.id, slug });
+ expect(status).toBe('ready');
+ expect(preview.preconditions.slug).toBe(slug);
+ const receipt = await runReconcileApply(engine, { source_id: f.id, slug, preview, request_id: randomUUID() });
+ expect(receipt.state).toBe('committed');
+ const page = await engine.getPage(slug, { sourceId: f.id });
+ expect(page?.id).toBe(f.snapshot.page.id);
+ expect(page?.source_path).toBe(`${slug}.md`);
+ expect(page?.compiled_truth).toContain('A durable extension-bearing observation.');
+ expect(page?.frontmatter).toMatchObject({ custom_database: 'kept', custom_file: 'kept' });
+ expect(await engine.getPage(slug.slice(0, -3), { sourceId: f.id })).toBeNull();
+ const file = readFileSync(f.file, 'utf8');
+ writeFileSync(f.file, file.replace('---\n', '---\nslug: notes/other\n'));
+ await expect(runReconcilePreview(engine, { source_id: f.id, slug })).rejects.toMatchObject({ code: 'invalid_params' });
+ expect((await engine.getPage(slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect(await engine.getPage('notes/other', { sourceId: f.id })).toBeNull();
+ });
+ }), 120_000);