Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): an incremental sync holds a committed file edit over a database-only page edit instead of publishing it (#6712)
garrytan7142d86e7471
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d7e9575451..16d55bc205 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -752,6 +752,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.276.0', text: 'On a writer-claimed brain, background writes are refused before any receipt, so they spend no write-request id, when their source cannot publish: the worktree is in recovery, or the claim\'s owner verification fails on the owner host (a missing canonical or coordination path, or a physical root whose owner marker .gbrain-owner.json or reservation is gone or changed; a device-only change is still re-stamped by the write). The refusal is owner_unavailable with the fix `gbrain sources writer status --source <id> --json`, checked once per source per run. Background writes are every write not made from an interactive surface: the autopilot cycle and its maintenance phases (extraction, synthesis, patterns, consolidation, fence and content repair, lint fixes), Minion jobs (sync, extract and the other job handlers), connector syncs, delegated serve syncs started as background, the keep-DB reconcile, autopilot and job managed syncs, and the transcript stale-part delete. Interactive CLI, MCP and repair writes are unaffected; a paused (draining) owner still accepts and replays.' },{ since: '0.60.276.0', text: 'The managed purge (autopilot purge phase, the purge job and `gbrain pages purge-deleted`) submits nothing for a source whose writer needs recovery (reported `writer_not_active` with its state and reason) and parks a page after five failed purges (doctor `purge_parked_pages`: actor agent on the CLI, host_admin remotely). The cycle purge phase reports warn, not fail, for either. `gbrain pages purge-deleted --retry-parked` retries parked pages once; it obeys `--older-than` (a parked page younger than the cutoff is not retried) and the rename-recovery hold, and its preview, its consent text (which names the parked count) and its run come from one selector.' },{ since: '0.60.276.0', text: '`gbrain repair content` / `repair slug-conflicts` now clears a frontmatter_slug_conflict hold deterministically (remove_slug) when the only other change autoFixFrontmatter would make is a style-only NESTED_QUOTES re-quote of a valid JSON-style tag or alias array. Only the slug: line is removed; the array is left as written and listed as style_only in the preview, the run result and the content_repair receipt. Such holds used to stay still_invalid and needed `repair frontmatter --include-ambiguous`. When the lane still cannot clear a hold because the frontmatter needs other fixes, the still_invalid message now names those fix codes (for example NULL_BYTES).' },+ { since: '0.60.276.0', text: 'On a managed brain an incremental `gbrain sync` no longer publishes a committed file edit over a page that was also edited in the database since its last import (for example a `put_page` with `sync.write_through` off). The file is held `file_drift` (side `both`) and the page keeps its edit; `gbrain repair file-drift --slug <slug>` previews both sides. Before, only a first sync, `--full` or a failed delta guarded this case, and the plain sync overwrote the database edit with no hold.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/sync-prescreen.ts b/src/core/persistence/sync-prescreen.tsindex 39d3920846..53cd6a674d 100644--- a/src/core/persistence/sync-prescreen.ts+++ b/src/core/persistence/sync-prescreen.ts@@ -12,9 +12,11 @@* - **no baseline concern**: the page is still at the recorded revision (only the file or the parser changed), so the* import cannot overwrite a database-only edit.* - **drift** (`entry.drift`): the page moved since the record and the file did not (`database`), or both moved- * (`both`), or there is no usable record (`unknown`: none, one written before PR 0, or a partial one). `database` is- * guarded in every discovery; `both` and `unknown` in a tree walk (first sync, `--full`, an unreachable checkpoint, a- * re-discovery), where no Git delta says the file is the side that changed. A page whose current revision a+ * (`both`), or there is no usable record (`unknown`: none, one written before PR 0, or a partial one). `database` and+ * `both` are guarded in every discovery: a Git delta proves the file changed, never that the page did not (#6712: an+ * incremental sync published a committed edit over a database-only `put_page`). `unknown` is guarded in a tree walk+ * (first sync, `--full`, an unreachable checkpoint, a re-discovery), where no Git delta says the file is the side that+ * changed. A page whose current revision a* committed managed-sync request of this incarnation wrote, or whose writer's write-through wrote to its file* (`pages.revision_write_request_id`, `fileBackedRevisions`), has no database-only edit to protect and is not guarded. A guarded entry is imported only when the freeze proves the import changes* nothing (`sameContentAtOrigin`); otherwise it is held `file_drift` (sync-run.ts `driftHold`).@@ -52,7 +54,8 @@ export function classifyBaseline(entry: Pick<SyncEntry, 'revision' | 'sourcePathif (fileSame && databaseSame && !input.full && sameParser(record!.parser, expected) && syncOriginPath(record!.origin) === syncOriginPath(entry.sourcePath)) return 'prescreened';if (databaseSame) return null;if (fileSame) return 'database';- return input.treeWalk ? complete ? 'both' : 'unknown' : null;+ if (complete) return 'both';+ return input.treeWalk ? 'unknown' : null;}/**diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 384a87bfe7..a45a100a85 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -233,3 +233,4 @@ test/unbound-source-6536.test.tstest/withdrawal-overlay-concurrency.test.tstest/withdrawal-publication-file.test.tstest/writer-status-owner-backends.test.ts+test/sync-prescreen-both-delta-6712.test.tsdiff --git a/test/sync-prescreen-both-delta-6712.test.ts b/test/sync-prescreen-both-delta-6712.test.tsnew file mode 100644index 0000000000..862742f5e9--- /dev/null+++ b/test/sync-prescreen-both-delta-6712.test.ts@@ -0,0 +1,71 @@+/**+ * #6712: an incremental managed sync whose Git delta changed a file must not publish it over a database-only edit of+ * the same page. Before the fix, `classifyBaseline` guarded the both-moved case only in a tree walk, so a plain delta+ * sync imported the committed edit over a `put_page` written with write-through off: no `file_drift` hold, no backup.+ *+ * Protects:+ * - both moved, delta sync: the page keeps the database edit and the file is held `file_drift` (side `both`);+ * - control: a file-only edit still imports on a delta sync with no hold;+ * - control: a page whose current revision write-through wrote to its file is not guarded (`fileBackedRevisions`), so the+ * committed file edit imports.+ *+ * The first test fails on the base (the page loses the edit and no hold is written). PGLite always; Postgres too when+ * DATABASE_URL is set.+ */+import { expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { readGitHold } from '../src/core/persistence/sync-holds.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { waitFor } from './helpers/wait-for.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const slug of ['notes/a', 'notes/b']) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));+ commit(root, 'notes');+};+const incarnationOf = async (engine: BrainEngine) => (await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text FROM sources WHERE id='default'"))[0]!.incarnation;+const holdOf = async (engine: BrainEngine, path: string) => readGitHold(engine, 'default', await incarnationOf(engine), path);+const bodyOf = async (engine: BrainEngine, slug: string) => (await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth ?? '';+async function putPage(engine: BrainEngine, ctx: OperationContext, slug: string, body: string): Promise<void> {+ const snap = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ const requestId = randomUUID();+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: requestId, expected_revision: snap.revision, content: note(slug, body) } });+ await waitFor(async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]))[0]?.state === 'committed', { timeoutMs: 30_000 });+}++test('a delta sync holds a committed file edit over a database-only put_page instead of publishing it', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await engine.setConfig('sync.write_through', 'false');+ await putPage(engine, ctx, 'notes/a', 'DBONLYMARKER agent edit.');+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'The second committed body.'));+ writeFileSync(join(root, 'notes/b.md'), note('notes/b', 'A file-only edit.'));+ commit(root, 'edit a and b');+ await performManagedSync(engine, OPTS);+ expect(await bodyOf(engine, 'notes/a')).toContain('DBONLYMARKER');+ const hold = await holdOf(engine, 'notes/a.md');+ expect(hold?.code).toBe('file_drift');+ expect(await bodyOf(engine, 'notes/b')).toContain('A file-only edit.');+ expect(await holdOf(engine, 'notes/b.md')).toBeNull();+}, { setup }), 120_000);++test('a page whose revision write-through wrote to its file is not guarded: the committed edit imports', () => managedBrain(async ({ engine, ctx, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await putPage(engine, ctx, 'notes/a', 'A write-through edit.');+ commit(root, 'write-through publication');+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A later committed body.'));+ commit(root, 'edit a');+ await performManagedSync(engine, OPTS);+ expect(await bodyOf(engine, 'notes/a')).toContain('A later committed body.');+ expect(await holdOf(engine, 'notes/a.md')).toBeNull();+}, { setup }), 120_000);