Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(import): frontmatter key order alone is not a content change (#5158)
garrytanae3fa2d37012
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 1e990f18d0..a519684097 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -1,5 +1,5 @@import { assertUnmanagedCanonicalWriter } from './persistence/maintenance.ts';-import { assertImportBase, sameCanonicalImport } from './page-state/import-guard.ts';+import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';import { decideImportIdentity, collidingSlugOwner, fileOriginUri } from './import-identity.ts';import { readSourceFileSync } from './minions/source-filesystem.ts';@@ -683,14 +683,30 @@ export async function importFromContent(await assertImportBase(tx, slug, sourceId ?? 'default', existing);if (refreshBody) await tx.refreshPageBody(slug, sourceId ?? 'default', parsed.compiled_truth, parsed.timeline || '', hash);await refreshSourcePath(tx, slug, sourceId, opts.sourcePath, existing, originUri);- if (opts.beforeCommit) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');+ if (opts.beforeCommit) await verifyPageReadable(tx, slug, refreshBody ? hash : existing?.content_hash ?? hash, sourceId, 'importFromContent');await opts.beforeCommit?.(tx, slug);});};// Rebuild stale projections without granting --force-rechunk's external-ID dedup override.const needsProjectionRebuild = !opts.prepare && existing && existing.text_projection_revision !== existing.knowledge_revision;- if (existing?.content_hash === hash && !existing.deleted_at && !opts.forceRechunk && !needsProjectionRebuild && (!opts.prepare || sameCanonicalImport(existingSnapshot, parsedPage))) {+ // #3694 one-time reconcile: a row written by the PRE-fix putPage formula+ // carries the legacy hash. When the parsed file matches that legacy hash,+ // the content is unchanged — stamp the canonical hash via the narrow+ // refreshPageBody UPDATE (no chunk churn, no re-embed, no version snapshot)+ // and skip. The next import then hits the fast path below.+ const legacyHashMatch = !!existing && !existing.deleted_at && !opts.prepare && !opts.forceRechunk && !needsProjectionRebuild+ && typeof engine.refreshPageBody === 'function' && existing.content_hash === contentHashLegacy({+ title: parsed.title,+ type: parsed.type,+ compiled_truth: parsed.compiled_truth,+ timeline: parsed.timeline,+ frontmatter: parsed.frontmatter,+ });+ const unchanged = !!existing && !existing.deleted_at && !opts.forceRechunk && !needsProjectionRebuild && (existing.content_hash === hash+ ? !opts.prepare || sameCanonicalImport(existingSnapshot, parsedPage)+ : !legacyHashMatch && await sameContentAnyKeyOrder(engine, existing, existingSnapshot?.tags ?? null, parsedPage, sourceId ?? 'default'));+ if (existing && unchanged) {// #5050: unchanged content chunked before the safe-chunk fence is re-sealed// projection-only; the canonical write stays a no-op.const reseal = await projectionBelowSafeFence(engine, existing.id);@@ -705,24 +721,10 @@ export async function importFromContent(return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}) };}- // #3694 one-time reconcile: a row written by the PRE-fix putPage formula- // carries the legacy hash. When the parsed file matches that legacy hash,- // the content is unchanged — stamp the canonical hash via the narrow- // refreshPageBody UPDATE (no chunk churn, no re-embed, no version snapshot)- // and skip. The next import then hits the fast path above.- if (existing && !existing.deleted_at && !opts.prepare && !opts.forceRechunk && !needsProjectionRebuild && typeof engine.refreshPageBody === 'function') {- const legacyHash = contentHashLegacy({- title: parsed.title,- type: parsed.type,- compiled_truth: parsed.compiled_truth,- timeline: parsed.timeline,- frontmatter: parsed.frontmatter,- });- if (existing.content_hash === legacyHash) {- await persistUnchanged(true);- const resealed = await projectionBelowSafeFence(engine, existing.id) ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;- return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}) };- }+ if (existing && legacyHashMatch) {+ await persistUnchanged(true);+ const resealed = await projectionBelowSafeFence(engine, existing.id) ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;+ return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}) };}// Identity dedup (#1309): move, skip a true duplicate, or index both.diff --git a/src/core/page-state/import-guard.ts b/src/core/page-state/import-guard.tsindex 14e8389f32..ded901b839 100644--- a/src/core/page-state/import-guard.ts+++ b/src/core/page-state/import-guard.ts@@ -14,11 +14,27 @@ export async function assertImportBase(tx: BrainEngine, slug: string, sourceId:}assertPageRevision(current ? { revision: current.knowledge_revision! } : null, existing ? { expectedRevision: existing.knowledge_revision } : {});}+const canonicalFields = (p: Page | ParsedPage) => ({ type: p.type, title: p.title, compiled_truth: p.compiled_truth,+ timeline: p.timeline ?? '', frontmatter: p.frontmatter });+/** Content hashes omit volatile metadata; a prepared no-op must compare all canonical fields. */export function sameCanonicalImport(existing: PageSnapshot | null, parsed: ParsedPage): boolean {if (!existing) return false;- const fields = (p: Page | ParsedPage) => ({ type: p.type, title: p.title, compiled_truth: p.compiled_truth,- timeline: p.timeline ?? '', frontmatter: p.frontmatter });const tags = [...new Set([...existing.tags, ...parsed.tags])].sort();- return stableJson(fields(existing.page)) === stableJson(fields(parsed)) && stableJson([...existing.tags].sort()) === stableJson(tags);+ return stableJson(canonicalFields(existing.page)) === stableJson(canonicalFields(parsed)) && stableJson([...existing.tags].sort()) === stableJson(tags);+}++/**+ * #5158: the stored content_hash digests frontmatter in insertion order, so a+ * file whose keys were only reordered hashes differently. This key-sorted+ * comparison of every canonical field and the exact tag set recognizes it as+ * unchanged without touching the stored hash formula.+ */+export async function sameContentAnyKeyOrder(engine: Pick<BrainEngine, 'getTags'>, existing: Page, existingTags: string[] | null,+ parsed: ParsedPage, sourceId: string): Promise<boolean> {+ if (existing.deleted_at || existing.type !== parsed.type || existing.title !== parsed.title+ || existing.compiled_truth !== parsed.compiled_truth || (existing.timeline ?? '') !== (parsed.timeline ?? '')) return false;+ if (stableJson(canonicalFields(existing)) !== stableJson(canonicalFields(parsed))) return false;+ const tags = existingTags ?? await engine.getTags(existing.slug, { sourceId });+ return stableJson([...tags].sort()) === stableJson([...parsed.tags].sort());}diff --git a/test/import-frontmatter-key-order-5158.test.ts b/test/import-frontmatter-key-order-5158.test.tsnew file mode 100644index 0000000000..eb812a177b--- /dev/null+++ b/test/import-frontmatter-key-order-5158.test.ts@@ -0,0 +1,60 @@+/**+ * #5158: reordering frontmatter keys is not a content change.+ *+ * Protects: re-importing a page whose file differs from the stored row only in+ * frontmatter key order (top-level or nested) writes nothing: status skipped,+ * same chunks, same stored content_hash, no version snapshot. A real value,+ * tag or body change still imports.+ * Fails when: the importer trusts only the insertion-order content_hash, so a+ * key reorder re-chunks (and on an embedding brain, re-embeds) the page.+ * Seams: none; PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const A = '---\ntitle: Synthetic note\ntype: note\ntags: [alpha, beta]\nalpha: one\nbeta: two\nnested:\n x: 1\n y: 2\n---\n\nIdentical synthetic body.\n';+const REORDERED = '---\nnested:\n y: 2\n x: 1\nbeta: two\ntags: [beta, alpha]\ntype: note\nalpha: one\ntitle: Synthetic note\n---\n\nIdentical synthetic body.\n';++for (const backend of testBackends()) describe(`#5158 frontmatter key order (${backend})`, () => {+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 120_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });++ const state = async (slug: string) => {+ const page = (await engine.getPage(slug))!;+ const [{ n: versions }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_versions WHERE page_id=$1', [page.id]);+ const chunks = await engine.executeRaw<{ id: number }>('SELECT id FROM content_chunks WHERE page_id=$1 ORDER BY id', [page.id]);+ return { hash: page.content_hash, updated: String(page.updated_at), versions, chunks: chunks.map(c => Number(c.id)) };+ };++ test('a key-order-only re-import writes nothing and keeps the stored hash', async () => {+ expect((await importFromContent(engine, 'notes/key-order', A, { noEmbed: true })).status).toBe('imported');+ const before = await state('notes/key-order');+ for (let i = 0; i < 2; i++) {+ const result = await importFromContent(engine, 'notes/key-order', REORDERED, { noEmbed: true });+ expect(result).toMatchObject({ status: 'skipped', chunks: 0 });+ expect(await state('notes/key-order')).toEqual(before);+ }+ });++ test('a changed value, tag or body still imports', async () => {+ await importFromContent(engine, 'notes/key-order-change', A, { noEmbed: true });+ for (const changed of [+ REORDERED.replace('alpha: one', 'alpha: three'),+ REORDERED.replace(' x: 1', ' x: 9'),+ REORDERED.replace('tags: [beta, alpha]', 'tags: [beta, alpha, gamma]'),+ REORDERED.replace('Identical synthetic body.', 'A different synthetic body.'),+ ]) {+ const before = await state('notes/key-order-change');+ expect((await importFromContent(engine, 'notes/key-order-change', changed, { noEmbed: true })).status).toBe('imported');+ expect((await state('notes/key-order-change')).hash).not.toBe(before.hash);+ }+ });+});