Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: an unknown-side file_drift hold from the screen before #7340 is screened once more, so a legacy page's Git edit imports
garrytan14ff9e24e75b
diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 5675fc6ed3..009bb0fae2 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -148,6 +148,8 @@ export interface GitHoldMeta {page_revision?: string;/** #6712 PR 1 `file_drift`: which side moved since the page's last recorded import (`unknown`: no usable record); `page_revision` is the page's revision when held. */sides?: 'database' | 'both' | 'unknown';+ /** GBRA-133 `file_drift`: the drift screen that held it; an unknown-side hold from an older screen is re-screened (#7340). */+ drift_version?: number;/*** #6712 PR 4b `file_drift`: which side a Decision is about (design v3.2 §4): `both` (the file and the page moved), `unknown`* (no import record says which), `deleted` (one side is a deletion, named by `state`). Absent on holds an older gbrain@@ -583,6 +585,9 @@ export async function holdBasisMoved(engine: Pick<BrainEngine, 'executeRaw'>, so* under the same blob id), so it re-screens on every sync; a `page_write_failed` hold of a freeze fault (origin `freeze`,* S-63) is re-tested by every sync until it has been held `HOLD_ATTEMPTS_NEEDS_HUMAN` times, so a transient fault clears.*/+/** GBRA-133: the `file_drift` screen version; 1 is #7340's rule (a page with no import record compares its file at the baseline commit). */+export const FILE_DRIFT_VERSION = 1;+export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression', 'content_rejected', 'write_gate_rejected', 'purged_content', 'legacy_slug_conflict', 'origin_conflict', 'page_identity_changed', 'git_object_missing'].includes(record.code)// #6712: a transient hold (the write owner stalled, not the file) is retried by every sync until it has been held HOLD_ATTEMPTS_NEEDS_HUMAN times.@@ -590,6 +595,9 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re|| (record.code === 'managed_image_sync_unsupported' && isMultimodalEnabled())|| record.meta.recovery_version < RECOVERY_VERSION|| (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)+ // GBRA-133: an unknown-side drift held before #7340's baseline rule (a Git edit to a page with no import record) imports+ // now when the page still holds its file at the baseline commit, so it is screened once more.+ || (record.code === 'file_drift' && fileDriftSide(record.meta) === 'unknown' && (record.meta.drift_version ?? 0) < FILE_DRIFT_VERSION)|| (outOfAttemptsHold(record.code) && record.meta.stall?.gbrain_version !== VERSION)// GBRA-130 A-6: an owner fault is the writer's, not the file's: an upgrade re-tests the path.|| (record.code === 'page_write_failed' && record.meta.write_failure?.gbrain_version !== VERSION)diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.tsindex e0664cb733..a38be8f21a 100644--- a/src/core/persistence/sync-page-fault.ts+++ b/src/core/persistence/sync-page-fault.ts@@ -36,7 +36,7 @@ import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry, type Synimport { readTreeBlobs } from './sync-blobs.ts';import type { SyncIntent } from './sync-prepare.ts';import type { HeldEntry } from './sync-screen.ts';-import type { GitHoldMeta, GitHoldRecord, PageWriteFailureMeta } from './sync-holds.ts';+import { FILE_DRIFT_VERSION, type GitHoldMeta, type GitHoldRecord, type PageWriteFailureMeta } from './sync-holds.ts';import { classifyTerminal } from './terminal-classify.ts';import { VERSION } from '../../version.ts';import { concurrentWriteHold, concurrentWriteProof } from './sync-concurrent-write.ts';@@ -151,7 +151,7 @@ export function fileDriftHold(entry: HoldEntry, slug: string, pageId: number | n: 'there is no import record to tell which side changed';return base(entry, slug, pageId, 'file_drift',`${entry.path}: ${by} since the file was last imported and ${file}, so sync held the import instead of overwriting the database version; the rest of the source synced.`,- intent.content ?? null, intent.blobOid, { sides: observed.sides, ...(observed.sides !== 'database' ? { side: observed.sides } : {}), ...(observed.revision ? { page_revision: observed.revision } : {}),+ intent.content ?? null, intent.blobOid, { sides: observed.sides, drift_version: FILE_DRIFT_VERSION, ...(observed.sides !== 'database' ? { side: observed.sides } : {}), ...(observed.revision ? { page_revision: observed.revision } : {}),...(observed.proof ? { competing_request_id: observed.proof.request_id, competing_operation: observed.proof.operation } : {}),...(observed.sharedOrigin ? { shared_origin: true as const } : {}) });}diff --git a/test/sync-unknown-drift-rescreen-gbra133.test.ts b/test/sync-unknown-drift-rescreen-gbra133.test.tsnew file mode 100644index 0000000000..5c5b1fec06--- /dev/null+++ b/test/sync-unknown-drift-rescreen-gbra133.test.ts@@ -0,0 +1,72 @@+/**+ * GBRA-133 (#7340 follow-up): before #7340's fix, a Git edit to a page with no import record was held `file_drift` with an+ * unknown side. The fix imports such an edit when the page still holds its file at the baseline commit, but only for new+ * edits: a hold written by the older screen stayed "at its level" (its blob unchanged) and was never screened again, so the+ * page stayed stale. Such a hold (no `drift_version`) is now re-screened once: it imports when the page still holds its+ * baseline file, and otherwise stays held, stamped with the current screen so it is not re-screened again.+ */+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 { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.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';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++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 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 holds = async (engine: BrainEngine) => (await engine.executeRaw<{ r: { path: string; code: string; meta: { side?: string; drift_version?: number } } }>(+ "SELECT completed_keys->0 AS r FROM op_checkpoints WHERE op='sync-hold' ORDER BY fingerprint")).map(({ r }) => `${r.path} ${r.code} ${r.meta.side ?? ''} v${r.meta.drift_version ?? 0}`);+const body = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ t: string }>(+ "SELECT compiled_truth AS t FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.t;++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const slug of ['notes/a', 'notes/b', 'notes/other']) writeFileSync(join(root, `${slug}.md`), note(slug, `The committed body of ${slug}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+ };++ test(`GBRA-133 [${backend}]: an unknown-side file_drift hold from the screen before #7340 is screened again and imports the Git edit`, () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const coordinated = (sql: string, params: unknown[] = []) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+ // Older imports: no import record, a revision no request wrote. notes/b also moved on in the database.+ await coordinated(`DELETE FROM op_checkpoints WHERE op='sync-import-provenance'+ AND completed_keys->0->>'page_id' IN (SELECT id::text FROM pages WHERE source_id='default' AND slug IN ('notes/a', 'notes/b'))`);+ for (const slug of ['notes/a', 'notes/b']) await coordinated(`UPDATE pages SET knowledge_revision = $1::uuid, revision_write_request_id = NULL,+ updated_at = now() - interval '1 hour' WHERE source_id='default' AND slug=$2`, [randomUUID(), slug]);+ await coordinated(`UPDATE pages SET compiled_truth = compiled_truth || ' Edited in the database.', knowledge_revision = $1::uuid WHERE source_id='default' AND slug='notes/b'`, [randomUUID()]);+ for (const slug of ['notes/a', 'notes/b']) writeFileSync(join(root, `${slug}.md`), note(slug, `A Git edit of ${slug}.`));+ git(root, 'commit', '-qam', 'edit a and b');+ // The holds the screen before #7340 wrote for those edits: unknown side, the edited blob, no drift_version.+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ for (const slug of ['notes/a', 'notes/b']) {+ const path = `${slug}.md`, page = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation, path, source_path: path, slug, page_id: Number(page.page.id), code: 'file_drift',+ message: `${path}: page ${slug} changed in the database since the file was last imported and there is no import record to tell which side changed`,+ upstream_version: null, observed_at: new Date().toISOString(), run_id: null, mode: 'managed',+ meta: { recovery_version: RECOVERY_VERSION, sides: 'unknown', side: 'unknown', blob_oid: git(root, 'rev-parse', `HEAD:${path}`), page_revision: page.revision } }));+ }+ expect(await holds(engine)).toEqual(['notes/a.md file_drift unknown v0', 'notes/b.md file_drift unknown v0']);++ await performManagedSync(engine, OPTS);+ expect(await body(engine, 'notes/a')).toContain('A Git edit of notes/a.');+ expect(await body(engine, 'notes/b')).toContain('Edited in the database.');+ expect(await holds(engine)).toEqual(['notes/b.md file_drift unknown v1']);++ writeFileSync(join(root, 'notes/other.md'), note('notes/other', 'An unrelated edit.')); git(root, 'commit', '-qam', 'edit other');+ await performManagedSync(engine, OPTS);+ expect(await holds(engine)).toEqual(['notes/b.md file_drift unknown v1']);+ expect(await body(engine, 'notes/b')).toContain('Edited in the database.');+ }, { databaseUrl, setup }), 180_000);+}