Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a both-moved entry imports when the page still holds what the recorded blob imports; tests follow the hold (#6712)

garrytan311b26c9f4f7
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 16d55bc205..ea1a155a16 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -752,7 +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.' },
+ { 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. A page deleted in the database is held the same way instead of being recreated from the file. A database change an import keeps (a tag, say) holds nothing: the edit imports and the tag stays. 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-discovery.ts b/src/core/persistence/sync-discovery.ts
index 905000729d..457c2858ff 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -46,6 +46,8 @@ 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. */
+ 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[];
/** #6729 x #6727: the one legacy page carries an explicit frontmatter id that differs from the file's, so it is another document; held `legacy_slug_conflict` (`explicit_id_conflict`). */
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index f7a7ffcccc..7a330232bd 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -504,7 +504,9 @@ function canonicalWritebackNeeded(row: WriteRequest, p: SyncIntent, pinned: stri
}
/** A managed-sync preparation; a Markdown import also carries the provenance its publication records, which a no-op waiver records instead. */
-export type SyncPreparedMutation = PreparedMutation & { importProvenance?: SyncImportProvenanceBase };
+export type SyncPreparedMutation = PreparedMutation & { importProvenance?: SyncImportProvenanceBase;
+ /** The import leaves the page as it is (only a canonical writeback of the file may remain); #6712 drift baseline check in sync-run.ts. */
+ pageUnchanged?: boolean };
export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock,
screening?: { unsaved: true }): Promise<SyncPreparedMutation> {
@@ -715,6 +717,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr
const preparedImport: SyncPreparedMutation = { observedRevision: snapshot?.revision ?? null, trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath), importProvenance,
// Tells the #5470 screen the content is unchanged; publication still queues its effects.
contentUnchanged: ready.noop && !moved && !writeback,
+ pageUnchanged: ready.noop && !moved,
...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),
validate: async tx => { await validate(tx); await ready.validate(tx); },
deferEmbedding: p.processingOptions?.noEmbed || p.embedDeferred === true,
diff --git a/src/core/persistence/sync-prescreen.ts b/src/core/persistence/sync-prescreen.ts
index 53cd6a674d..79670c3fd7 100644
--- a/src/core/persistence/sync-prescreen.ts
+++ b/src/core/persistence/sync-prescreen.ts
@@ -16,7 +16,8 @@
* `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
+ * changed. A `both` entry whose page still holds what the recorded disk blob imports (the database changed only what an
+ * import keeps: tags, links) imports (sync-run.ts `unchangedSinceBaseline`). 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`).
@@ -88,11 +89,11 @@ export async function prescreenSyncEntries(engine: BrainEngine, discovered: Sync
const side = classifyBaseline(entry, records.get(Number(entry.pageId)), blobs.get(gitPathOf(entry)), syncImportParserFor(entry.sourcePath, pack?.identity ?? null),
{ full: input.full || !!hold, treeWalk: input.treeWalk || hold?.code === 'file_drift' });
if (side === 'prescreened') entry.prescreened = true;
- else if (side) { entry.drift = side; guarded.push(entry); }
+ else if (side) { entry.drift = side; if (side === 'both') entry.driftBaseline = records.get(Number(entry.pageId))!.disk_blob_oid!; guarded.push(entry); }
}
if (!guarded.length) return;
const backed = await fileBackedRevisions(engine, discovered, guarded.map(entry => Number(entry.pageId)));
- const drifted = guarded.filter(entry => backed.has(Number(entry.pageId)) ? (delete entry.drift, false) : true);
+ const drifted = guarded.filter(entry => backed.has(Number(entry.pageId)) ? (delete entry.drift, delete entry.driftBaseline, false) : true);
await releaseKeepDbDrift(engine, discovered, drifted, input.dryRun);
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index aea3685072..71f6c7c054 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -45,7 +45,7 @@ import { managedSyncResumeArgs } from '../sync-reconcile.ts';
import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';
import { isContentRefusal } from '../import-screen.ts';
import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
-import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
+import { readBlobContents, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { dryRunScreen, heldImageEntry, isSyncReadBound, loadSyncScreenRun, oversizeHold, pinnedBlob, pinnedContent, pinnedImageBytes, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { frozenImageIntent, sameImageBytes } from './sync-image.ts';
import { fenceReceiptLocation } from '../fence-repair/refusal.ts';
@@ -441,7 +441,8 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
}
// #6712 PR 1: an import whose page moved since its file was last imported runs only as a proven no-op (sync-prescreen.ts).
if (entry.drift && !occupantRebound && content !== null && snapshot && !(image ? sameImageBytes(imageBytes, snapshot.page)
- : await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal))) {
+ : await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal)
+ || await unchangedSinceBaseline(engine, cursor, entry, key, snapshot, run.signal))) {
if (!holdsOn) throw syncRunRefusal('file_drift', 'An import would overwrite a database version of the page that sync never saw.', retry, `Page ${slug} in source ${cursor.sourceId} changed in the database since ${entry.path} was last imported, and the file differs from it, so the run stopped before admitting it (sync.holds=fail).`);
const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: null }); assertActive();
return { hold: fileDriftHold(entry, slug, pageId, frozenIntent, { sides: entry.drift, revision: snapshot.revision, proof, sharedOrigin: await sharedOriginSurvivor(engine, cursor.sourceId, entry.sourcePath) }) };
@@ -928,6 +929,30 @@ async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: C
}
}
+/**
+ * #6712: both the file and the page moved since the last recorded import, but the page still holds exactly what the
+ * recorded disk blob imports (the database side changed only what an import keeps: tags, links, withdrawals). The
+ * newer file then overwrites nothing the database alone holds, so the entry imports.
+ */
+async function unchangedSinceBaseline(engine: BrainEngine, cursor: Cursor, entry: Cursor['entries'][number], key: string,
+ snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, signal?: AbortSignal): Promise<boolean> {
+ if (entry.drift !== 'both' || !entry.driftBaseline || !snapshot || snapshot.page.deleted_at != null) return false;
+ const baseline = readBlobContents(cursor.gitRoot, [{ oid: entry.driftBaseline, size: 0 }]).get(entry.driftBaseline);
+ if (baseline === undefined) return false;
+ const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: snapshot.revision, sourcePath: entry.sourcePath, path: entry.path, rawHash: sha256(baseline),
+ content: baseline, lineEndingOnly: false, processingOptions: cursor.processingOptions, ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority,
+ cursorKey: key, runId: cursor.runId, slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: false };
+ try {
+ const budgetMs = await syncPreparationBudgetMs(engine);
+ const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: snapshot.page.slug,
+ page_id: snapshot.page.id, worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent }), { engine: engine.kind }, startClaimPhase(Date.now(), undefined, budgetMs)), budgetMs, signal);
+ return (prepared.pageUnchanged === true || prepared.noop === true) && prepared.observedRevision === snapshot.revision;
+ } catch (error) {
+ if (signal?.aborted) throw error;
+ return false;
+ }
+}
+
/** Counts a committed page into the cursor, as the single path does. */
function countCommitted(counts: Cursor['counts'], pending: Pending, outcome: WriteRequest['outcome']): void {
if (outcome?.noop !== true) {
diff --git a/test/managed-sync-page-fault-holds.test.ts b/test/managed-sync-page-fault-holds.test.ts
index 00db2ae7bd..a255e70dae 100644
--- a/test/managed-sync-page-fault-holds.test.ts
+++ b/test/managed-sync-page-fault-holds.test.ts
@@ -267,14 +267,16 @@ test('a page edited in the database after the manifest froze is held concurrent_
expect(resumed.held![0]!.fix.argv).toEqual(['gbrain', 'sources', 'reconcile', f.id, 'b', '--preview']);
expect(await readGitHold(engine, f.id, source.incarnation, 'c.md')).toBeNull();
expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);
- // A page deleted in the database after the freeze holds the same way; the page stays deleted.
+ // A page deleted in the database after the freeze holds the same way; the page stays deleted. #6712: b still holds its
+ // database-only edit, so the next committed edit of b.md is held file_drift instead of overwriting it.
for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(f.root, `${name}.md`), note(`${name} three.`));
const pin3 = commit(f.root, 'version three');
await interruptedAfter(engine, f.opts, 1);
await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.softDeletePage('d', { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));
const third = await performManagedSync(engine, f.opts);
expect(third).toMatchObject({ status: 'synced', toCommit: pin3 });
- expect(third.held?.map(hold => [hold.path, hold.code])).toEqual([['d.md', 'concurrent_write']]);
+ expect(third.held?.map(hold => [hold.path, hold.code])).toEqual([['b.md', 'file_drift'], ['d.md', 'concurrent_write']]);
+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toBe('Beta, edited straight in the database.');
expect(await engine.getPage('d', { sourceId: f.id })).toBeNull();
}
}), 120_000);
diff --git a/test/persistence-sync-fence-holds.test.ts b/test/persistence-sync-fence-holds.test.ts
index a3c0c7b1dd..f7deee1f10 100644
--- a/test/persistence-sync-fence-holds.test.ts
+++ b/test/persistence-sync-fence-holds.test.ts
@@ -31,6 +31,7 @@ import { printSyncResult, type SyncOpts, type SyncResult } from '../src/commands
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
+import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { waitFor } from './helpers/wait-for.ts';
import { readFileSync } from 'node:fs';
@@ -391,6 +392,8 @@ test('TE1: a stored take whose prior fence did not parse is updated by its norma
await tx.executeRaw("UPDATE pages SET compiled_truth=$3 WHERE source_id=$1 AND slug=$2", [s.id, 'people/probe', bad.split('---\n').slice(2).join('---\n')]);
await tx.executeRaw("INSERT INTO takes(page_id,row_num,claim,kind,holder,weight) SELECT id,2,'Second take','assessment','brain',0.7 FROM pages WHERE source_id=$1 AND slug=$2", [s.id, 'people/probe']);
}, TEST_WRITE_ATTRIBUTION));
+ // That older writer recorded no import provenance (a recorded database-only edit is held #6712 file_drift instead).
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'page_id'=(SELECT id::text FROM pages WHERE source_id=$2 AND slug=$3)", [SYNC_IMPORT_PROVENANCE_OP, s.id, 'people/probe']);
s.write('people/probe.md', bad); commit(s.root, 'invented kind');
const result = await s.sync();
expect(result).toMatchObject({ status: 'synced', fences_normalized: { count: 1, by_class: { kind_map: 1 } } });
diff --git a/test/persistence-sync-overtaken-cursor-5522.test.ts b/test/persistence-sync-overtaken-cursor-5522.test.ts
index 02a3d3408c..fe52b7d4cc 100644
--- a/test/persistence-sync-overtaken-cursor-5522.test.ts
+++ b/test/persistence-sync-overtaken-cursor-5522.test.ts
@@ -14,6 +14,7 @@ import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { withEnv } from './helpers/with-env.ts';
+import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
// #5522: a commit-driven cursor and a --working-tree cursor of one source used
// different cursor keys. When the working-tree run imports a file the sliced
@@ -132,6 +133,9 @@ test('#5522 a page soft-deleted at that origin, or a pinned page deleted and rec
await legacy(engine, `${pinned.id}-commit`, () => performManagedSync(engine, pinned.base, { maxPages: 1, maxMs: 60_000 }));
const before = await engine.getPage('b', { sourceId: pinned.id });
await engine.transaction(tx => withCoordinatedWrite(tx, [pinned.id], () => tx.softDeletePage('b', { sourceId: pinned.id }), TEST_WRITE_ATTRIBUTION));
+ // The older gbrain recorded no import provenance, so its working-tree run recreates the page (#6712 holds it when a record
+ // shows the database side moved).
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'page_id'=$2", [SYNC_IMPORT_PROVENANCE_OP, String(before!.id)]);
await legacy(engine, `${pinned.id}-working`, () => performManagedSync(engine, pinned.working), `${pinned.id}-commit`);
const after = await engine.getPage('b', { sourceId: pinned.id });
expect(after?.compiled_truth).toContain('Revised observation b');
diff --git a/test/sync-prescreen-both-delta-6712.test.ts b/test/sync-prescreen-both-delta-6712.test.ts
index cd0fac3243..2eca9c46a5 100644
--- a/test/sync-prescreen-both-delta-6712.test.ts
+++ b/test/sync-prescreen-both-delta-6712.test.ts
@@ -6,6 +6,8 @@
* 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 database-only change an import keeps (a tag) is not guarded: the page still holds what the recorded disk
+ * blob imports (`unchangedSinceBaseline`), so the committed edit imports and the tag stays;
* - control: a page whose current revision write-through wrote to its file is not guarded (`fileBackedRevisions`), so the
* committed file edit imports.
*
@@ -22,7 +24,9 @@ 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 { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { managedBrain } from './helpers/managed-brain.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.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();
@@ -60,6 +64,18 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DAT
expect(await holdOf(engine, 'notes/b.md')).toBeNull();
}, { setup, databaseUrl }), 120_000);
+ test('a database-only tag does not guard the page: the committed edit imports and keeps the tag', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await engine.setConfig('sync.write_through', 'false');
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.addTag('notes/a', 'kept-in-brain', { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));
+ writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'The second committed body.'));
+ commit(root, 'edit a');
+ await performManagedSync(engine, OPTS);
+ expect(await bodyOf(engine, 'notes/a')).toContain('The second committed body.');
+ expect((await engine.readPageSnapshot('notes/a', { sourceId: 'default' }))?.tags).toContain('kept-in-brain');
+ expect(await holdOf(engine, 'notes/a.md')).toBeNull();
+ }, { setup, databaseUrl }), 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.');