Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): preserve editor saves after proposal rollback

garrytan93a8011b2bca
diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.ts
index ff717378cb..a088456066 100644
--- a/src/core/facts/proposal-supersede.ts
+++ b/src/core/facts/proposal-supersede.ts
@@ -227,6 +227,18 @@ function publishFile(filePath: string, body: string, expected: string, slug: str
renameSync(tmp, filePath);
}
+/** Restore a failed publication only while the checkout still carries this operation's published bytes. */
+function restorePublishedFile(filePath: string, before: string, published: string, slug: string, sourceId: string): void {
+ if (existsSync(filePath) && readFileSync(filePath, 'utf-8') === published) {
+ writeFileSync(filePath, before, 'utf-8');
+ return;
+ }
+ console.warn(`[facts.proposal] ${slug} (file_database_drift: the proposal transaction failed after publication and the file changed again, `
+ + `so its current bytes were preserved instead of restoring the old file. Check the database copy before retrying the proposal. `
+ + `Import the editor's file with gbrain sync --source ${sourceId}; if the database copy should win, re-save it with write-through on; `
+ + `when both changed, ask the user which edit wins)`);
+}
+
/** Mirror the page body the fence change produced (the #4696 rule: keep the old hash so sync re-imports). */
async function mirrorBody(tx: BrainEngine, slug: string, sourceId: string, body: string, fromFile: boolean, expected: StoredBody | null): Promise<string | null> {
if (fromFile) {
@@ -286,7 +298,7 @@ async function acceptUnmanaged(engine: BrainEngine, proposal: PairProposal, stor
if (plan && fileBody !== null) { publishFile(filePath!, plan.body, fileBody, slug!, fresh.source_id); published = true; }
})));
} catch (err) {
- if (published) writeFileSync(filePath!, fileBody!, 'utf-8');
+ if (published) restorePublishedFile(filePath!, fileBody!, plan!.body, slug!, fresh.source_id);
if (err instanceof ProposalFileDrift) return { id: fresh.id, action: 'accept', status: 'refused', reason: err.message };
throw err;
}
@@ -330,7 +342,7 @@ async function undoUnmanaged(engine: BrainEngine, proposal: PairProposal, store:
if (plan && fileBody !== null) { publishFile(filePath!, plan.body, fileBody, before.fence!.slug, fresh.source_id); published = true; }
})));
} catch (err) {
- if (published) writeFileSync(filePath!, fileBody!, 'utf-8');
+ if (published) restorePublishedFile(filePath!, fileBody!, plan!.body, before.fence!.slug, fresh.source_id);
if (err instanceof ProposalFileDrift) return { id: fresh.id, action: 'undo', status: 'refused', reason: err.message };
throw err;
}
diff --git a/test/pathological/d2-fence-write-overwrite.test.ts b/test/pathological/d2-fence-write-overwrite.test.ts
index bf9ce00620..03ddd051e9 100644
--- a/test/pathological/d2-fence-write-overwrite.test.ts
+++ b/test/pathological/d2-fence-write-overwrite.test.ts
@@ -15,7 +15,7 @@ import { runFactsPipeline } from '../../src/core/facts/backstop.ts';
import { writeSingleFact } from '../../src/core/facts/write-single.ts';
import { parseFactsFence } from '../../src/core/facts-fence.ts';
import { pathologicalArms } from './harness.ts';
-import { CLAIM, EDIT, SLUG, editWhenPrepared, withFactsBrain } from './facts-overwrite-fixture.ts';
+import { CLAIM, EDIT, SLUG, editAfterWrite, editWhenPrepared, withFactsBrain } from './facts-overwrite-fixture.ts';
afterEach(() => { __setChatTransportForTests(null); resetGateway(); });
@@ -48,6 +48,20 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-2 fence w
});
}, 180_000);
+ test('an editor save after fact insertion rolls back the mirror, rows and versions before rename', async () => {
+ await withFactsBrain(databaseUrl, async b => {
+ const before = { file: b.bytes(), body: await b.body(), versions: await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id') };
+ let saved = '';
+ const result = await b.append(editAfterWrite(b, 'insertFacts', () => { b.fileEdit(); saved = b.bytes(); }));
+ expect(saved).toBe(before.file + EDIT);
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: saved, body: before.body });
+ expect(result).toMatchObject({ inserted: 0, legacyFallback: true, databaseOnlyReason: 'file_database_drift' });
+ expect(result.warning).toContain(`${SLUG} (file_database_drift`);
+ expect(await b.engine.executeRaw('SELECT id FROM facts')).toEqual([]);
+ expect(await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id')).toEqual(before.versions);
+ });
+ }, 180_000);
+
for (const mode of ['database', 'file'] as const) test(`${mode} drift keeps an authorized inferred subject and both bodies`, async () => {
await withFactsBrain(databaseUrl, async b => {
if (mode === 'database') await b.dbEdit();
diff --git a/test/pathological/d3-forget-overwrite.test.ts b/test/pathological/d3-forget-overwrite.test.ts
index 4ca27fc912..4c1cdbcc79 100644
--- a/test/pathological/d3-forget-overwrite.test.ts
+++ b/test/pathological/d3-forget-overwrite.test.ts
@@ -11,7 +11,7 @@ import { forgetFactInFence } from '../../src/core/facts/forget.ts';
import { parseFactsFence } from '../../src/core/facts-fence.ts';
import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
import { pathologicalArms, runScopedErrors } from './harness.ts';
-import { EDIT, SLUG, editWhenPrepared, withFactsBrain } from './facts-overwrite-fixture.ts';
+import { EDIT, SLUG, editAfterWrite, editWhenPrepared, withFactsBrain } from './facts-overwrite-fixture.ts';
for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-3 forget mirrors (${backend})`, () => {
for (const action of ['withdrawal', 'supersession'] as const) for (const mode of ['database', 'file', 'late-database', 'late-file'] as const) test(`${action}: ${mode} edit holds the mirror but commits expiry`, async () => {
@@ -41,6 +41,22 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-3 forget
});
}, 180_000);
+ test('an editor save after the body mirror rolls back that mirror and its version before rename', async () => {
+ await withFactsBrain(databaseUrl, async b => {
+ const id = (await b.append()).ids[0]!;
+ const before = { file: b.bytes(), body: await b.body(), versions: await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id') };
+ let saved = '';
+ const racing = editAfterWrite(b, 'refreshPageBody', () => { b.fileEdit(); saved = b.bytes(); });
+ const result = await forgetFactInFence(racing, id, { supersededBy: { rowNum: null } });
+ expect(saved).toBe(before.file + EDIT);
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: saved, body: before.body });
+ expect(result).toMatchObject({ ok: true, path: 'legacy_db' });
+ expect(result.warning).toContain(`${SLUG} (file_database_drift`);
+ expect(await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id')).toEqual(before.versions);
+ expect(await b.engine.executeRaw('SELECT id FROM facts WHERE expired_at IS NULL')).toEqual([]);
+ });
+ }, 180_000);
+
test('write-through off keeps the file untouched and strikes the newer database body', async () => {
await withFactsBrain(databaseUrl, async b => {
const id = (await b.append()).ids[0]!;
diff --git a/test/pathological/d4-proposal-overwrite.test.ts b/test/pathological/d4-proposal-overwrite.test.ts
index b3906369cb..183c33854f 100644
--- a/test/pathological/d4-proposal-overwrite.test.ts
+++ b/test/pathological/d4-proposal-overwrite.test.ts
@@ -4,13 +4,30 @@
* agreeing copies still accept and undo. Existing proposal coverage changes fence rows, not independent prose.
* Fails when: unmanaged proposal planning prefers file bytes and mirrors them over a different database body.
* Seams: engine transaction proxy injects an edit after the planning snapshot; no production-only seam.
+ * Post-publication rollback: a real transaction throws after the callback published the file, with or without
+ * a subsequent editor save. An editor's later bytes must survive while database/proposal/version changes roll back.
*/
import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
import { insertProposal } from '../../src/core/ai/decide/proposals-store.ts';
import { applyProposalAction } from '../../src/core/facts/proposal-supersede.ts';
import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
import { pathologicalArms } from './harness.ts';
-import { EDIT, SLUG, editWhenPrepared, withFactsBrain } from './facts-overwrite-fixture.ts';
+import { EDIT, SLUG, editWhenPrepared, withFactsBrain, type FactsBrain } from './facts-overwrite-fixture.ts';
+
+function failAfterPublication(b: FactsBrain, beforeFile: string, failure: Error, after: () => void): BrainEngine {
+ let fired = false;
+ return new Proxy(b.engine, { get(target, prop) {
+ if (prop === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>, opts?: Parameters<BrainEngine['transaction']>[1]) =>
+ target.transaction(async tx => {
+ const result = await run(tx);
+ if (!fired && b.bytes() !== beforeFile) { fired = true; after(); throw failure; }
+ return result;
+ }, opts);
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-4 proposal mirrors (${backend})`, () => {
for (const action of ['accept', 'undo'] as const) for (const mode of ['database', 'file', 'late-database', 'late-file', 'agree'] as const) test(`${action}: ${mode}`, async () => {
@@ -78,4 +95,31 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-4 proposa
expect(await b.engine.executeRaw('SELECT expired_at::text, superseded_by FROM facts ORDER BY id')).toEqual(before.facts);
});
}, 180_000);
+
+ for (const action of ['accept', 'undo'] as const) for (const editor of [false, true]) test(`${action}: a post-publication failure ${editor ? 'preserves the later editor save' : 'restores its unchanged published file'}`, async () => {
+ await withFactsBrain(databaseUrl, async b => {
+ const old = (await b.append()).ids[0]!;
+ const fresh = (await b.append(b.engine, 'Alice Example leads design')).ids[0]!;
+ const id = (await insertProposal(b.engine, { source_id: 'default', sweep_id: 'post-publication-sweep', pair_index: 0,
+ old_fact_id: old, new_fact_id: fresh, direction: 'new_supersedes_old', p_supersede: 0.8, threshold: 0.8,
+ proposal_floor: 0.5, model_resolved: 'synthetic-model' }))!;
+ if (action === 'undo') expect((await applyProposalAction(b.engine, id, 'accept')).status).toBe('accepted');
+ const before = { file: b.bytes(), body: await b.body(), versions: await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id'),
+ facts: await b.engine.executeRaw('SELECT expired_at::text, valid_until::text, superseded_by FROM facts ORDER BY id') };
+ let published = '';
+ let saved = '';
+ const failure = Object.assign(new Error('forced transaction failure after publication'), { code: '08006' });
+ const racing = failAfterPublication(b, before.file, failure, () => {
+ published = b.bytes();
+ if (editor) { b.fileEdit(); saved = b.bytes(); }
+ });
+ await expect(applyProposalAction(racing, id, action)).rejects.toBe(failure);
+ expect(published).not.toBe(before.file);
+ if (editor) expect(saved).toBe(published + EDIT);
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: editor ? saved : before.file, body: before.body });
+ expect(await b.engine.executeRaw('SELECT expired_at::text, valid_until::text, superseded_by FROM facts ORDER BY id')).toEqual(before.facts);
+ expect(await b.engine.executeRaw('SELECT id FROM page_versions ORDER BY id')).toEqual(before.versions);
+ expect(await b.engine.executeRaw('SELECT status FROM decide_proposals WHERE id = $1', [id])).toEqual([{ status: action === 'accept' ? 'pending' : 'accepted' }]);
+ });
+ }, 180_000);
});
diff --git a/test/pathological/facts-overwrite-fixture.ts b/test/pathological/facts-overwrite-fixture.ts
index 14e1df64b7..53d308a6dd 100644
--- a/test/pathological/facts-overwrite-fixture.ts
+++ b/test/pathological/facts-overwrite-fixture.ts
@@ -68,3 +68,20 @@ export function editWhenPrepared(b: FactsBrain, edit: () => Promise<void> | void
return typeof value === 'function' ? value.bind(target) : value;
} });
}
+
+/** An editor saves after the awaited database write, inside the real transaction, before the final rename. */
+export function editAfterWrite(b: FactsBrain, method: 'insertFacts' | 'refreshPageBody', edit: () => void): BrainEngine {
+ let fired = false;
+ const wrap = (engine: BrainEngine): BrainEngine => new Proxy(engine, { get(target, prop) {
+ if (prop === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>, opts?: Parameters<BrainEngine['transaction']>[1]) =>
+ target.transaction(tx => run(wrap(tx)), opts);
+ if (prop === method) return async (...args: unknown[]) => {
+ const result = await (target[method] as (...a: unknown[]) => Promise<unknown>).apply(target, args);
+ if (!fired && existsSync(`${b.file}.tmp`)) { fired = true; edit(); }
+ return result;
+ };
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ return wrap(b.engine);
+}
diff --git a/test/trust-write-gate-drift.test.ts b/test/trust-write-gate-drift.test.ts
index c23e743997..f111f65889 100644
--- a/test/trust-write-gate-drift.test.ts
+++ b/test/trust-write-gate-drift.test.ts
@@ -33,6 +33,7 @@ const EXEMPT: Record<string, string> = {
'src/core/embedding-dim-check.ts': 'embedding columns only',
'src/core/extract/receipt-writer.ts': 'gbrain-generated extraction receipt page (counts, cost, model id); no external text',
'src/core/facts/derivation-inputs.ts': 'derivation edge ledger; ids only',
+ 'src/core/facts/file-body-guard.ts': 'row-locked compare-and-swap body mirror: fence-write callers gate newly appended rows; forget, proposal-supersede, unfenced-facts and phantom-redirect only strike, adopt or relocate facts already stored; this helper adds no independently sourced text',
'src/core/facts/forget.ts': 'withdrawal strike (lifecycle)',
'src/core/facts/ontology-rekey.ts': 'drops duplicate copies of existing ontology rows before a re-key (placement)',
'src/core/facts/proposal-supersede.ts': 'checked supersede of existing rows (lifecycle)',