Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a Git edit to a page with no import record imports when the page still holds its baseline file (#7338)
garrytan70448fb90f81
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 098f269b70..0175d25dae 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -51,7 +51,7 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'prescreened?: true;/** #6712 PR 1: the page moved since its last recorded import (or has no record); imported only when the freeze proves it a no-op, else held `file_drift`. */drift?: SyncDriftSide;- /** #6712: for `both`, the blob the last recorded import left on disk; the freeze imports when the page still holds what that blob imports. */+ /** #6712: for `both`, the blob the last recorded import left on disk; #7338: for `unknown`, the file at the baseline commit. The freeze imports when the page still holds what that blob imports. */driftBaseline?: string;/** #6727: live pages with no recorded origin whose slugs fold to this file's slug, several or one the importer cannot write; the freeze holds it `legacy_slug_conflict`. */legacySlugs?: string[];diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 3b4e46c664..831938998e 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -190,7 +190,9 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh// #6887: a both-moved import imports when the page still holds what its recorded disk blob imports (sync-screen.ts driftBaselineContent).const bothDrift = imports.filter(entry => entry.result.cls === 'drift' && entry.result.side === 'both' && entry.pageId !== null);const baselineRecords = await readSyncImportProvenances(engine, level.sourceId, level.incarnation, bothDrift.map(entry => entry.pageId!));- const driftBaseline = (entry: ShadowPath) => entry.result.side === 'both' && entry.pageId !== null ? baselineRecords.get(entry.pageId)?.disk_blob_oid ?? undefined : undefined;+ // #7338: a page with no import record (imported by an older gbrain) has its file at the incarnation's baseline commit as its baseline.+ const driftBaseline = (entry: ShadowPath) => entry.pageId === null ? undefined : entry.result.side === 'both' ? baselineRecords.get(entry.pageId)?.disk_blob_oid ?? undefined+ : entry.result.side === 'unknown' ? entry.state.baseline ?? undefined : undefined;const entries: PassEntry[] = [], collisions: SyncSlugCollision[] = [], skipped: ShadowPath[] = [], identity: Array<{ entry: ShadowPath; origin: ShadowPath | null; slug: string; ids: { page: string; file: string } }> = [];const claims = new Map<string, ShadowPath[]>();for (const entry of imports) {diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex 9b3392bb03..f2dcad868f 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -83,10 +83,12 @@ export function pinnedBlob(cursor: PinnedCursor, path: string): TreeBlob | null/*** A `both` entry's recorded disk blob (`driftBaseline`), or null. When the page still holds what it imports (sync-run.ts* `sameContentAtOrigin`, `pageOnly`), the database changed only what an import keeps (tags, links), so the newer file- * overwrites nothing the database alone holds and the entry imports.+ * overwrites nothing the database alone holds and the entry imports. #7338: an `unknown` entry (a page with no import+ * record, imported by an older gbrain) carries its file at the incarnation's baseline commit: a page that still holds that+ * file changed only in Git, so the edit imports instead of being held `file_drift`.*/export function driftBaselineContent(gitRoot: string, entry: Pick<SyncEntry, 'drift' | 'driftBaseline'>): string | null {- if (entry.drift !== 'both' || !entry.driftBaseline) return null;+ if ((entry.drift !== 'both' && entry.drift !== 'unknown') || !entry.driftBaseline) return null;try { return readBlobContents(gitRoot, [{ oid: entry.driftBaseline, size: SYNC_READ_BOUND }]).get(entry.driftBaseline) ?? null; } catch { return null; }}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex eefa5ac111..e2fc2844c6 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -432,6 +432,7 @@ test/sync-handler-drain-6706.test.tstest/sync-import-provenance-disk.test.tstest/sync-inexact-rename-6729.test.tstest/sync-landing-gaps.test.ts+test/sync-legacy-edit-import-7338.test.tstest/sync-legacy-holds.test.tstest/sync-legacy-retry-actions-6696.test.tstest/sync-legacy-slug-adoption-6727.test.tsdiff --git a/test/sync-legacy-edit-import-7338.test.ts b/test/sync-legacy-edit-import-7338.test.tsnew file mode 100644index 0000000000..8f02850ab3--- /dev/null+++ b/test/sync-legacy-edit-import-7338.test.ts@@ -0,0 +1,76 @@+/**+ * #7338: a managed source activated over pages an older gbrain imported (no import record) sweeps those pages a bounded+ * number per pass (#7189). Before the fix, a Git edit to a page the sweep had not reached yet classified `drift` with an+ * unknown side and was held `file_drift`, so the edit never became searchable. That's what turned the managed serve-watch+ * freshness cells red. A page that still holds its file at the baseline commit changed only in Git, so the edit imports.+ */+import { expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { drainProjections } from '../src/core/page-state/projections.ts';+import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';+import { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';+import { PASS_LEGACY_SWEEP_MAX } from '../src/core/persistence/sync-pass-apply.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const N = PASS_LEGACY_SWEEP_MAX + 40;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const name = (i: number) => `n${String(i).padStart(4, '0')}`;+const body = (i: number, text: string) => `---\ntype: concept\ntitle: notes/${name(i)}\n---\n\n${text}\n`;++/** Turns the synced pages into pages an older gbrain imported: the same rows with no import record, and no pass row. */+async function legacyPages(engine: BrainEngine): Promise<void> {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ const cols = 'source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, source_path';+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT ${cols} FROM pages WHERE source_id='default'`);+ await engine.executeRaw("DELETE FROM pages WHERE source_id='default'");+ for (const row of rows) await engine.executeRaw(`INSERT INTO pages(${cols}) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9)`,+ [row.source_id, row.slug, row.type, row.title, row.compiled_truth, row.timeline, JSON.stringify(row.frontmatter), row.content_hash, row.source_path]);+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op IN ($1,$2)', [SYNC_IMPORT_PROVENANCE_OP, MANAGED_SYNC_PASS_OP]);+ while ((await drainProjections(engine, { limit: 100 })).rebuilt > 0);+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ test(`#7338 [${backend}]: a Git edit to a legacy page the sweep has not reached imports instead of being held file_drift`, () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toMatch(/^(first_sync|synced)$/);+ await legacyPages(engine);+ // The activation pass sweeps at most PASS_LEGACY_SWEEP_MAX legacy pages in path order, so the last pages stay unrecorded.+ await performManagedSync(engine, OPTS);+ const last = N - 1, slug = `notes/${name(last)}`;+ const unrecorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints c JOIN pages p ON p.id=(c.completed_keys->0->>'page_id')::int WHERE c.op=$1 AND p.slug=$2", [SYNC_IMPORT_PROVENANCE_OP, slug]);+ expect(unrecorded).toHaveLength(0);++ writeFileSync(join(root, `notes/${name(last)}.md`), body(last, 'An edited body naming acme-example.'));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'edit');+ const result = await performManagedSync(engine, OPTS);+ expect(result.status).toBe('synced');+ const holds = await engine.executeRaw<{ code: string }>("SELECT completed_keys->0->>'code' AS code FROM op_checkpoints WHERE op='sync-hold' AND completed_keys->0->>'path'=$1", [`notes/${name(last)}.md`]);+ expect(holds).toEqual([]);+ expect((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth).toContain('acme-example');++ // A database edit to another unrecorded page still holds its Git edit: the database side moved since the baseline.+ const other = N - 2, otherSlug = `notes/${name(other)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ await engine.executeRaw("UPDATE pages SET compiled_truth=compiled_truth || ' A database-only line.', knowledge_revision=gen_random_uuid() WHERE source_id='default' AND slug=$1", [otherSlug]);+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ writeFileSync(join(root, `notes/${name(other)}.md`), body(other, 'A second Git edit.'));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'edit 2');+ await performManagedSync(engine, OPTS);+ const held = await engine.executeRaw<{ code: string }>("SELECT completed_keys->0->>'code' AS code FROM op_checkpoints WHERE op='sync-hold' AND completed_keys->0->>'path'=$1", [`notes/${name(other)}.md`]);+ expect(held.map(row => row.code)).toEqual(['file_drift']);+ }, { databaseUrl, setup: ({ root }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (let i = 0; i < N; i++) writeFileSync(join(root, `notes/${name(i)}.md`), body(i, `The committed body of notes/${name(i)}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+ } }), 300_000);+}