Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): preserve divergent file and database bodies

garrytan53308ee65f2f
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index ede5db7749..45a04ed16a 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -35,14 +35,13 @@
*/
import { execFileSync } from '../spawn.ts';
-import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, appendFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, appendFileSync, rmSync } from 'node:fs';
import { dirname, isAbsolute, relative } from 'node:path';
import type { BrainEngine, NewFact, FactVisibility, FactKind, FactAttribution } from '../engine.ts';
import type { ResolutionSource } from '../entities/resolve.ts';
import { inferTypeFromPack, parseMarkdown } from '../markdown.ts';
import { yamlScalar } from '../frontmatter-inference.ts';
-import { sanitizeText } from '../batch-rows.ts';
import { loadActivePackBestEffort } from '../schema-pack/best-effort.ts';
import { withPageLock } from '../page-lock.ts';
import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';
@@ -52,7 +51,6 @@ import { isDurabilityHardened, commitWriteThroughFile } from '../brain-repo-dura
import { upsertFactRow, parseFactsFence, formatFenceDate } from '../facts-fence.ts';
import { unparsedFenceRefusal } from '../fence-repair/refusal.ts';
import type { OperationError } from '../ops/contract.ts';
-import { contentHash } from '../utils.ts';
import { extractFactsFromFenceText } from './extract-from-fence.ts';
import { logStubGuardEvent } from './stub-guard-audit.ts';
import { isFactWithdrawn } from './withdrawal.ts';
@@ -64,6 +62,8 @@ import { recordFlaggedRow, type GatedRowDecision } from '../write-gate-store.ts'
import type { TaintInput, WriteTrust } from '../trust/tier.ts';
import { gitChildEnv } from '../git-env.ts';
import { urlCloneReadOnly } from '../url-clone.ts';
+import { bodyUnread } from '../page-body/page-shape.ts';
+import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';
/** Resolved source binding for the entity page. */
export interface FenceTarget {
@@ -119,7 +119,9 @@ export interface FenceWriteResult {
/** True when the path fell through to DB-only: local_path unset, `sync.write_through` off, or a gbrain-owned clone (`databaseOnlyReason`). */
legacyFallback?: true;
/** #6946: why a `legacyFallback` is expected — `url_clone`: the source is a clone gbrain owns and pulls (url-clone.ts), so its checkout is never written. */
- databaseOnlyReason?: 'url_clone';
+ databaseOnlyReason?: 'url_clone' | 'file_database_drift';
+ /** A held file mirror's typed diagnostic and repair instructions; facts take the DB-only fallback. */
+ warning?: string;
/** True when fence parse-validate failed; rows were NOT inserted, .tmp quarantined. */
fenceWriteFailed?: true;
/**
@@ -392,8 +394,23 @@ export async function writeFactsToFence(
// 1. Read existing body or stub-create.
let body: string;
const fromFile = existsSync(filePath);
+ const stored = fromFile ? await readStoredBody(engine, target.sourceId, target.slug) : null;
+ const drift = (when: 'before' | 'during'): FenceWriteResult => {
+ const warning = fileDatabaseDriftToken(target.slug, target.sourceId, when);
+ console.warn(`[facts.fence] ${warning}`);
+ return { inserted: 0, ids: [], legacyFallback: true, databaseOnlyReason: 'file_database_drift', warning, ...withdrawnSkipped };
+ };
if (fromFile) {
body = readFileSync(filePath, 'utf-8');
+ const refusal = refuseUnparsedFence(body, target, filePath);
+ if (refusal) return { inserted: 0, ids: [], fenceWriteFailed: true, fenceRefusal: refusal, ...withdrawnSkipped };
+ const page = await engine.getPage(target.slug, { sourceId: target.sourceId });
+ if (page && bodyUnread(page)) {
+ const warning = `${target.slug} (page_body_segmented: its file is not compared or rewritten here; facts are recorded database-only)`;
+ console.warn(`[facts.fence] ${warning}`);
+ return { inserted: 0, ids: [], legacyFallback: true, warning, ...withdrawnSkipped };
+ }
+ if (stored ? !fileBodyMatchesStored(body, target.slug, stored) : page !== null) return drift('before');
} else {
// Stub-creation guard, two arms:
//
@@ -454,6 +471,8 @@ export async function writeFactsToFence(
body = stubEntityPage(target.slug, activePack?.manifest ?? null);
}
+ const fileBefore = fromFile ? body : null;
+
// 2. Upsert each fact onto the fence in input order. row_num
// monotonically increases (max-existing + 1 per call, append-only).
//
@@ -543,42 +562,6 @@ export async function writeFactsToFence(
return { inserted: 0, ids: [], fenceWriteFailed: true };
}
- // 5. Rename .tmp → file. POSIX atomic; the canonical file is
- // either the old content or the new content, never partial.
- renameSync(tmpPath, filePath);
-
- // #4872: mirror the rewritten file into pages.compiled_truth. get_page
- // and the extract_facts reconcile read the DB body, not the file — left
- // stale, a plain get→put round-trip flattens the new row off disk and
- // the next reconcile deletes it from the facts table. Same recipe as
- // forget.ts (#4696): parse + sanitize the FILE bytes as import-file.ts
- // does. Body-only: content_chunks are untouched, so the row KEEPS its
- // old content_hash and the next sync re-imports + re-chunks. Stamping
- // the importer's hash here made sync skip the page and left search
- // blind to the new row forever. Never persist an EMPTY hash: a row
- // that had none gets a row-shaped hash of its pre-mirror content,
- // which the rewritten file can't match. Best-effort: the file is
- // already committed; sync creates a stub's row; only a real file's body is mirrored (#6398).
- try {
- const reparsed = parseMarkdown(tmpBody, `${target.slug}.md`);
- const existing = fromFile ? await engine.getPage(target.slug, { sourceId: target.sourceId }) : null;
- if (existing) {
- // #5575 ENG-1: the appended rows carry their own tier; the page keeps its tier.
- await maintenanceTransaction(engine, tx => withPageTierKept(tx, target, () => tx.refreshPageBody(target.slug, target.sourceId,
- sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
- existing.content_hash || contentHash(existing))));
- }
- } catch (err) {
- // The file is committed; the page cache stays stale until the next
- // sync (reconcile refuses destructive work meanwhile). Say so.
- console.warn(`[facts.fence] FACTS_PAGE_MIRROR_FAILED: ${target.slug} (source ${target.sourceId}): ${err instanceof Error ? err.message : String(err)}; pages cache stale until the next sync`);
- }
-
- // 6. Stamp the DB. extractFactsFromFenceText handles the
- // validFrom/validUntil date derivation + the strikethrough
- // semantic distinction. We only want to insert the NEW rows
- // (those with row_nums in assignedRowNums), so filter the
- // re-parsed facts to that subset.
const allExtracted = extractFactsFromFenceText(parsed.facts, target.slug, target.sourceId);
const newRowSet = new Set(assignedRowNums);
const toInsert = allExtracted.filter(r => newRowSet.has(r.row_num));
@@ -595,7 +578,25 @@ export async function writeFactsToFence(
source_session: facts[i].sessionId,
}));
- const result = await insertFenceRows(engine, target.sourceId, enriched, facts, derivation);
+ const result = await maintenanceTransaction(engine, async tx => {
+ if (fileBefore === null ? existsSync(filePath) : !existsSync(filePath) || readFileSync(filePath, 'utf-8') !== fileBefore) return null;
+ if (stored && !await withPageTierKept(tx, target, () => mirrorFileBody(tx, target.sourceId, target.slug, tmpBody, stored))) return null;
+ if (!stored && await readStoredBody(tx, target.sourceId, target.slug, true)) return null;
+ const inserted = await insertFenceRows(tx, target.sourceId, enriched, facts, derivation);
+ if (fileBefore === null ? existsSync(filePath) : !existsSync(filePath) || readFileSync(filePath, 'utf-8') !== fileBefore) {
+ throw new FenceFileChanged();
+ }
+ assertSourceFilesystemActive();
+ renameSync(tmpPath, filePath);
+ return inserted;
+ }).catch(err => {
+ if (err instanceof FenceFileChanged) return null;
+ throw err;
+ });
+ if (!result) {
+ rmSync(tmpPath, { force: true });
+ return drift('during');
+ }
// v0.46 (#3014) — an unresolvable `superseded by #N` reference (self
// / dangling / struck target) leaves superseded_by NULL; log it rather
// than swallow it. The row still lands (expired_at set for struck
@@ -619,6 +620,8 @@ export async function writeFactsToFence(
);
}
+class FenceFileChanged extends Error {}
+
/**
* The DB stamp of new fence rows in one attributed transaction: at the
* deriver's tier when it declared one, with input edges, and the flag receipt
diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.ts
index f09db2fdb1..ce46a83d14 100644
--- a/src/core/facts/file-body-guard.ts
+++ b/src/core/facts/file-body-guard.ts
@@ -21,6 +21,15 @@ export interface StoredBody {
timeline: string | null;
}
+/** The diagnostic and repair choices for a held unmanaged file/body mirror. */
+export function fileDatabaseDriftToken(slug: string, sourceId: string, when: 'before' | 'during',
+ disposition = 'its rows stay unfenced, active and searchable until they agree'): string {
+ return `${slug} (file_database_drift: the canonical file and the database body ${when === 'before' ? 'differ' : 'changed while the fence step ran'}, `
+ + `so neither was replaced and ${disposition}. If the file holds the newer edit, `
+ + `gbrain sync --source ${sourceId} imports it; if the database copy is newer, re-save it with write-through on `
+ + `(gbrain get ${slug} --source ${sourceId}, then gbrain put ${slug} --source-id ${sourceId}); when both changed, ask the user which edit wins)`;
+}
+
/** The file's body and timeline as the mirror would store them. */
export function mirroredBody(fileBytes: string, slug: string): { compiled_truth: string; timeline: string } {
const parsed = parseMarkdown(fileBytes, `${slug}.md`);
diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.ts
index 889ba67422..b289370f7c 100644
--- a/src/core/facts/forget.ts
+++ b/src/core/facts/forget.ts
@@ -11,15 +11,13 @@
*/
import { randomUUID } from 'node:crypto';
-import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
+import { existsSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import { withPageLock } from '../page-lock.ts';
import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';
-import { resolvePageWriteTarget } from '../write-through.ts';
+import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
import { parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';
-import { parseMarkdown } from '../markdown.ts';
-import { sanitizeText } from '../batch-rows.ts';
import { contentHash } from '../utils.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { rewriteLiveSegmentedFences } from '../page-body/segment-rewrite.ts';
@@ -27,7 +25,9 @@ import type { BodyRegion } from '../page-body/types.ts';
import { recordFactWithdrawal } from './withdrawal.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { markBeliefCommits } from '../belief/append.ts';
+import { classifyItemFailure } from '../item-failure.ts';
import { withdrawnFact } from './withdrawal-overlay.ts';
+import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';
export interface ForgetFactResult {
/** True iff the row was found AND a forget was applied (fence or DB). */
@@ -36,6 +36,8 @@ export interface ForgetFactResult {
path: 'fence' | 'legacy_db' | 'not_found' | 'already_expired';
/** Human-readable reason captured in `context`; mirrors back what was written. */
reason: string;
+ /** A held mirror does not undo the authoritative withdrawal or expiry. */
+ warning?: string;
}
interface FactDbRow {
@@ -197,9 +199,11 @@ export async function forgetFactInFence(
return strikeFenceRow(fence, row.row_num!, strikeRow) ?? fence;
}));
};
+ let mirrorWarning: string | undefined;
const strikeDbBody = async (): Promise<void> => {
if (row.row_num === null || row.source_markdown_slug === null) return;
const slug = row.source_markdown_slug;
+ const expected = await readStoredBody(engine, row.source_id, slug);
const page = await engine.getPage(slug, { sourceId: row.source_id });
if (!page) return;
if (isSegmentedPage(page)) return strikeSegments(page.id, ['truth']);
@@ -210,8 +214,16 @@ export async function forgetFactInFence(
// content_chunks with the live claim for good. A row-shaped hash over the
// struck body can never equal the unchanged file's, so the next sync
// re-imports + re-chunks through the withdrawal overlay.
- await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id, struck, page.timeline ?? '',
- contentHash({ ...page, compiled_truth: struck })));
+ await maintenanceTransaction(engine, async tx => {
+ const current = await readStoredBody(tx, row.source_id, slug, true);
+ if (!current || !expected || current.compiled_truth !== expected.compiled_truth || current.timeline !== expected.timeline) {
+ mirrorWarning = `${slug} (revision_conflict: the database body changed while the withdrawal mirror ran; the withdrawal or supersession remains authoritative. Read the current page and re-save it to refresh the physical mirror)`;
+ console.warn(`[facts.forget] ${mirrorWarning}`);
+ return;
+ }
+ await tx.createVersion(slug, { sourceId: row.source_id });
+ await tx.refreshPageBody(slug, row.source_id, struck, page.timeline ?? '', contentHash({ ...page, compiled_truth: struck }));
+ });
};
// DB-only path: the withdrawal remains authoritative during reimport.
@@ -223,9 +235,9 @@ export async function forgetFactInFence(
if (ok && row.source_markdown_slug !== null) {
const slug = row.source_markdown_slug;
await (locked ? strikeDbBody() : withPageLock(slug, strikeDbBody, { timeoutMs: 5_000 }))
- .catch(() => { /* best-effort, see above */ });
+ .catch(err => { if (classifyItemFailure(err).scope === 'run') throw err; });
}
- return { ok, path: 'legacy_db', reason };
+ return { ok, path: 'legacy_db', reason, ...(mirrorWarning ? { warning: mirrorWarning } : {}) };
};
// Fence path requires: v51 columns set + source.local_path set.
@@ -235,6 +247,7 @@ export async function forgetFactInFence(
row.entity_slug !== null;
if (!canFence) return legacyExpire();
+ if (await isWriteThroughDisabled(engine)) return legacyExpire();
// Look up source.local_path.
const sources = await engine.executeRaw<SourceRow>(
@@ -269,6 +282,15 @@ export async function forgetFactInFence(
return withPageLock(slug, async () => {
const body = readFileSync(filePath, 'utf-8');
+ const page = await engine.getPage(slug, { sourceId: row.source_id });
+ const segmented = page && isSegmentedPage(page);
+ const stored = segmented ? null : await readStoredBody(engine, row.source_id, slug);
+ const held = (when: 'before' | 'during'): ForgetFactResult => {
+ const warning = fileDatabaseDriftToken(slug, row.source_id, when, 'the withdrawal or supersession remains authoritative; only its page mirror is held');
+ console.warn(`[facts.forget] ${warning}`);
+ return { ok: true, path: 'legacy_db', reason, warning };
+ };
+ if (!segmented && (stored ? !fileBodyMatchesStored(body, slug, stored) : page !== null)) return held('before');
// Fence missing the row (DB drifted from markdown) or its markers (race /
// corruption): fall through to legacy expire so the user's intent
// succeeds; doctor surfaces the drift separately.
@@ -285,6 +307,24 @@ export async function forgetFactInFence(
// DB expire so the user's forget intent still succeeds.
return legacyExpire(true);
}
+ if (!segmented) {
+ const written = await maintenanceTransaction(engine, async tx => {
+ if (!existsSync(filePath) || readFileSync(filePath, 'utf-8') !== body) return false;
+ if (stored ? !await mirrorFileBody(tx, row.source_id, slug, tmpBody, stored) : await readStoredBody(tx, row.source_id, slug, true)) return false;
+ if (!existsSync(filePath) || readFileSync(filePath, 'utf-8') !== body) throw new WithdrawalFileChanged();
+ assertSourceFilesystemActive();
+ renameSync(tmpPath, filePath);
+ return true;
+ }).catch(err => {
+ if (err instanceof WithdrawalFileChanged) return false;
+ throw err;
+ });
+ if (!written) {
+ rmSync(tmpPath, { force: true });
+ return held('during');
+ }
+ return { ok: true, path: 'fence', reason };
+ }
renameSync(tmpPath, filePath);
// Stamp the DB to match: valid_until = today, expired_at = now().
@@ -309,17 +349,11 @@ export async function forgetFactInFence(
// hash of its pre-mirror content, which the rewritten file can't match.
// Best-effort — file + facts row are already correct.
try {
- const reparsed = parseMarkdown(tmpBody, `${slug}.md`);
const page = await engine.getPage(slug, { sourceId: row.source_id });
// The withdrawal already struck the segmented row with the overlay's reason; it takes the file's row, as the
// inline body takes the file's text, so the caller's reason reaches the stored body.
const fileRow = parseFactsFence(tmpBody).facts.find(f => f.rowNum === targetRowNum);
if (page && isSegmentedPage(page)) await strikeSegments(page.id, ['truth', 'timeline'], fileRow ? () => fileRow : strike);
- else if (page) {
- await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id,
- sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
- page.content_hash || contentHash(page)));
- }
} catch { /* degrades to the pre-#4696 window (stale until the next sync) */ }
return { ok: true, path: 'fence', reason };
@@ -329,3 +363,5 @@ export async function forgetFactInFence(
? mirrorWithdrawal()
: withSourceFilesystemLock(engine, resolved.writeRoot, mirrorWithdrawal);
}
+
+class WithdrawalFileChanged extends Error {}
diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.ts
index d21ae1f086..ff717378cb 100644
--- a/src/core/facts/proposal-supersede.ts
+++ b/src/core/facts/proposal-supersede.ts
@@ -20,13 +20,12 @@ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'nod
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { formatFenceDate, parseFactsFence, type ParsedFact } from '../facts-fence.ts';
-import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
-import { assertInlineBody } from '../page-body/page-shape.ts';
-import { sanitizeText } from '../batch-rows.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { assertInlineBody, bodyUnread } from '../page-body/page-shape.ts';
import { contentHash } from '../utils.ts';
import { withPageLock } from '../page-lock.ts';
import { assertSourceFilesystemActive, withSourceFilesystemLock } from '../minions/source-filesystem.ts';
-import { resolvePageWriteTarget } from '../write-through.ts';
+import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { getProposal, transitionProposal, type ProposalRow } from '../ai/decide/proposals-store.ts';
@@ -37,6 +36,7 @@ import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
import { noteBelief } from '../belief/ledger.ts';
import { beliefStreamSlugs, lockedBeliefBatch } from '../belief/writers.ts';
+import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody, type StoredBody } from './file-body-guard.ts';
export const DECIDE_PROPOSAL_OPERATION = 'decide_proposal';
@@ -210,7 +210,13 @@ async function recordedPair(tx: BrainEngine, proposal: PairProposal, action: Pro
await lockedBeliefBatch(tx, { sourceId: proposal.source_id, slugs, op: DECIDE_PROPOSAL_OPERATION, remote: false, cause: { proposal: proposal.id, action } }, fn);
}
-function publishFile(filePath: string, body: string): void {
+class ProposalFileDrift extends ProposalConflictError {}
+
+const proposalDrift = (slug: string, sourceId: string, when: 'before' | 'during') =>
+ fileDatabaseDriftToken(slug, sourceId, when, 'the proposal and its facts are unchanged');
+
+function publishFile(filePath: string, body: string, expected: string, slug: string, sourceId: string): void {
+ if (!existsSync(filePath) || readFileSync(filePath, 'utf-8') !== expected) throw new ProposalFileDrift(proposalDrift(slug, sourceId, 'during'));
const tmp = `${filePath}.tmp`;
assertSourceFilesystemActive();
writeFileSync(tmp, body, 'utf-8');
@@ -222,21 +228,26 @@ function publishFile(filePath: string, body: string): void {
}
/** 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): Promise<string | null> {
+async function mirrorBody(tx: BrainEngine, slug: string, sourceId: string, body: string, fromFile: boolean, expected: StoredBody | null): Promise<string | null> {
+ if (fromFile) {
+ if (!expected || !await mirrorFileBody(tx, sourceId, slug, body, expected)) throw new ProposalFileDrift(proposalDrift(slug, sourceId, 'during'));
+ return (await tx.readPageSnapshot(slug, { sourceId }))?.revision ?? null;
+ }
+ const current = await readStoredBody(tx, sourceId, slug, true);
+ if (!current || !expected || current.compiled_truth !== expected.compiled_truth || current.timeline !== expected.timeline) {
+ throw new ProposalFileDrift(`${slug} (revision_conflict: the database body changed while the proposal ran; nothing changed. Read the current page before deciding the proposal again)`);
+ }
const page = await tx.getPage(slug, { sourceId });
if (!page) return null;
assertInlineBody(page, 'proposal fence mirror');
- if (fromFile) {
- const reparsed = parseMarkdown(body, `${slug}.md`);
- await tx.refreshPageBody(slug, sourceId, sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline), page.content_hash || contentHash(page));
- } else {
- await tx.refreshPageBody(slug, sourceId, body, page.timeline ?? '', contentHash({ ...page, compiled_truth: body }));
- }
+ await tx.createVersion(slug, { sourceId });
+ await tx.refreshPageBody(slug, sourceId, body, page.timeline ?? '', contentHash({ ...page, compiled_truth: body }));
return (await tx.readPageSnapshot(slug, { sourceId }))?.revision ?? null;
}
async function withFenceLocks<T>(engine: BrainEngine, slug: string | null, sourceId: string, run: (filePath: string | null) => Promise<T>): Promise<T> {
if (!slug) return run(null);
+ if (await isWriteThroughDisabled(engine)) return withPageLock(slug, () => run(null), { timeoutMs: 5_000 });
const target = await resolvePageWriteTarget(engine, slug, sourceId);
if (!target.ok) return withPageLock(slug, () => run(null), { timeoutMs: 5_000 });
return withSourceFilesystemLock(engine, target.writeRoot, () => withPageLock(slug, () => run(target.filePath), { timeoutMs: 5_000 }));
@@ -256,7 +267,12 @@ async function acceptUnmanaged(engine: BrainEngine, proposal: PairProposal, stor
const slug = oldF!.source_markdown_slug;
const fileBody = filePath && existsSync(filePath) ? readFileSync(filePath, 'utf-8') : null;
const snapshot = slug ? await engine.readPageSnapshot(slug, { sourceId: fresh.source_id }) : null;
- const body = fileBody ?? snapshot?.page.compiled_truth ?? null;
+ if (snapshot && bodyUnread(snapshot.page)) return { id: fresh.id, action: 'accept', status: 'refused', reason: `${slug} (page_body_segmented: this proposal needs an inline page; nothing changed)` };
+ const stored = slug ? await readStoredBody(engine, fresh.source_id, slug) : null;
+ if (fileBody !== null && (!stored || !fileBodyMatchesStored(fileBody, slug!, stored))) {
+ return { id: fresh.id, action: 'accept', status: 'refused', reason: proposalDrift(slug!, fresh.source_id, 'before') };
+ }
+ const body = fileBody ?? stored?.compiled_truth ?? null;
const plan = slug && body !== null ? planAcceptFence(body, oldF!, newF!, formatFenceDate(new Date())) : null;
const fence = (row: ParsedFact, revision: string | null): FenceState => ({ slug: slug!, row_num: oldF!.row_num!, row, page_revision: revision, file: fileBody !== null });
const before: SupersedeState = { old: factFields(oldF!), new: factFields(newF!), fence: plan ? fence(plan.before, snapshot?.revision ?? null) : null };
@@ -264,13 +280,14 @@ async function acceptUnmanaged(engine: BrainEngine, proposal: PairProposal, stor
try {
// The strike edits a managed fence without authoring the page: it keeps its trust tier (#5575 ENG-1).
await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => recordedPair(tx, fresh, 'accept', async () => {
- const revision = plan ? await mirrorBody(tx, slug!, fresh.source_id, plan.body, fileBody !== null) : null;
+ const revision = plan ? await mirrorBody(tx, slug!, fresh.source_id, plan.body, fileBody !== null, stored) : null;
await expireOld(tx, fresh);
await finishAccept(tx, fresh, before, plan ? fence(plan.after, revision) : null, store);
- if (plan && fileBody !== null) { publishFile(filePath!, plan.body); published = true; }
+ 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 (err instanceof ProposalFileDrift) return { id: fresh.id, action: 'accept', status: 'refused', reason: err.message };
throw err;
}
return { id: fresh.id, action: 'accept', status: 'accepted' };
@@ -290,23 +307,31 @@ async function undoUnmanaged(engine: BrainEngine, proposal: PairProposal, store:
const { before, after } = states;
let plan: { body: string } | null = null;
let fileBody: string | null = null;
+ let stored: StoredBody | null = null;
if (before.fence && after.fence) {
fileBody = before.fence.file && filePath && existsSync(filePath) ? readFileSync(filePath, 'utf-8') : null;
- if (before.fence.file && fileBody === null) return { id: fresh.id, action: 'undo', status: 'refused', reason: 'fence_file_missing' };
- const body = fileBody ?? (await engine.getPage(before.fence.slug, { sourceId: fresh.source_id }))?.compiled_truth ?? null;
+ if (before.fence.file && fileBody === null && !await isWriteThroughDisabled(engine)) return { id: fresh.id, action: 'undo', status: 'refused', reason: 'fence_file_missing' };
+ const page = await engine.getPage(before.fence.slug, { sourceId: fresh.source_id });
+ if (page && bodyUnread(page)) return { id: fresh.id, action: 'undo', status: 'refused', reason: `${before.fence.slug} (page_body_segmented: this proposal needs an inline page; nothing changed)` };
+ stored = await readStoredBody(engine, fresh.source_id, before.fence.slug);
+ const body = fileBody ?? stored?.compiled_truth ?? null;
const planned = body === null ? 'changed' : planUndoFence(body, before.fence, after.fence);
if (planned === 'changed') return { id: fresh.id, action: 'undo', status: 'refused', reason: 'fence_changed' };
+ if (fileBody !== null && (!stored || !fileBodyMatchesStored(fileBody, before.fence.slug, stored))) {
+ return { id: fresh.id, action: 'undo', status: 'refused', reason: proposalDrift(before.fence.slug, fresh.source_id, 'before') };
+ }
plan = planned;
}
let published = false;
try {
await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => recordedPair(tx, fresh, 'undo', async () => {
- if (plan) await mirrorBody(tx, before.fence!.slug, fresh.source_id, plan.body, fileBody !== null);
+ if (plan) await mirrorBody(tx, before.fence!.slug, fresh.source_id, plan.body, fileBody !== null, stored);
await applyUndoDb(tx, fresh, before, after, store);
- if (plan && fileBody !== null) { publishFile(filePath!, plan.body); published = true; }
+ 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 (err instanceof ProposalFileDrift) return { id: fresh.id, action: 'undo', status: 'refused', reason: err.message };
throw err;
}
return { id: fresh.id, action: 'undo', status: 'undone' };
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
index 56969dcb95..493a88bcfe 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -75,7 +75,7 @@ import type { WriteAuthority } from '../persistence/model.ts';
import { UNBOUND_WRITE_KEY } from '../persistence/unbound-source.ts';
import { contentHash } from '../utils.ts';
import { bodyUnread } from '../page-body/page-shape.ts';
-import { fileBodyMatchesStored, mirrorFileBody, readStoredBody } from './file-body-guard.ts';
+import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
import { commitFactFenceFile, gitPathState } from './fence-write.ts';
import { isOwnedClone } from '../url-clone.ts';
@@ -546,18 +546,6 @@ async function fenceDatabaseOnlyPage(engine: BrainEngine, sourceId: string, enti
}
}
-/**
- * #6982: the `failed_pages` entry for an unmanaged page whose canonical file and database body differ, so its rows stay
- * unfenced and neither copy is replaced. Which side is newer is not knowable here: an unimported file edit and a newer
- * database-only edit look the same, and replacing either would lose the other.
- */
-export function fileDatabaseDriftToken(slug: string, sourceId: string, when: 'before' | 'during'): string {
- return `${slug} (file_database_drift: the canonical file and the database body ${when === 'before' ? 'differ' : 'changed while the fence step ran'}, `
- + `so neither was replaced and its rows stay unfenced, active and searchable until they agree. If the file holds the newer edit, `
- + `gbrain sync --source ${sourceId} imports it; if the database copy is newer, re-save it with write-through on `
- + `(gbrain get ${slug} --source ${sourceId}, then gbrain put ${slug} --source-id ${sourceId}); when both changed, ask the user which edit wins)`;
-}
-
/**
* One unmanaged page (#6982): the fence is planned on the file only when the file and the database body agree
* (`fileMatchesSnapshot`, the coordinator's drift comparison), so mirroring the fenced file back can only add the fence.
diff --git a/test/fence-write.test.ts b/test/fence-write.test.ts
index 27c95261f9..efc8737c63 100644
--- a/test/fence-write.test.ts
+++ b/test/fence-write.test.ts
@@ -804,8 +804,8 @@ describe('writeFactsToFence — durability latch recovery', () => {
installFakeDurabilityHook(brainDir);
const filePath = join(brainDir, 'people/race.md');
- // Gate writer A between its rename and its commit (insertFacts sits
- // between the two), so writer B arrives while A's content is renamed
+ // Gate writer A after its publishing transaction and before its git commit,
+ // so writer B arrives while A's content is renamed
// into place but not yet committed — the false preexisting_dirty
// shape from the out-of-lock prewrite snapshot.
let release: () => void = () => {};
@@ -813,11 +813,11 @@ describe('writeFactsToFence — durability latch recovery', () => {
let gated = false;
const gatedEngine = Object.create(engine) as typeof engine;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- // The insert runs on a transaction engine derived from gatedEngine: delegate with `this`.
- (gatedEngine as any).insertFacts = async function (this: typeof engine, rows: unknown, opts: unknown) {
- if (!gated) { gated = true; await gate; }
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return (engine as any).insertFacts.call(this, rows, opts);
+ // The transaction engine is derived from gatedEngine: delegate with `this`.
+ (gatedEngine as any).transaction = async function (this: typeof engine, fn: Parameters<typeof engine.transaction>[0]) {
+ const result = await engine.transaction.call(this, fn);
+ if (!gated && existsSync(filePath) && readFileSync(filePath, 'utf-8').includes('Writer A fact')) { gated = true; await gate; }
+ return result;
};
const a = writeFactsToFence(
diff --git a/test/pathological/d2-fence-write-overwrite.test.ts b/test/pathological/d2-fence-write-overwrite.test.ts
new file mode 100644
index 0000000000..8be00b3a05
--- /dev/null
+++ b/test/pathological/d2-fence-write-overwrite.test.ts
@@ -0,0 +1,43 @@
+/**
+ * D-2 (GBRA-131, #6982): appending facts never mirrors a different checkout body over the database.
+ * Protects: database-newer, file-newer and concurrent edits retain exact bytes; the writer returns a DB-only
+ * fallback, and writeSingleFact records the unfenced fact. Agreeing copies still append with history.
+ * Fails when: the pre-fix whole-file mirror overwrites the DB after publishing the file.
+ * Existing coverage checks missing files, not divergent live copies or publication races.
+ * Seams: engine proxy injects a real edit before the prepared fence transaction; no production-only hook.
+ */
+import { describe, expect, test } from 'bun:test';
+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';
+
+for (const { backend, databaseUrl } of pathologicalArms()) describe(`D-2 fence writes (${backend})`, () => {
+ for (const mode of ['database', 'file', 'late-database', 'late-file'] as const) test(`${mode} edit preserves both copies and falls back`, async () => {
+ await withFactsBrain(databaseUrl, async b => {
+ if (mode === 'database') await b.dbEdit();
+ if (mode === 'file') b.fileEdit();
+ const before = { file: b.bytes(), body: await b.body() };
+ const racing = mode.startsWith('late-') ? editWhenPrepared(b, () => mode === 'late-database' ? b.dbEdit() : b.fileEdit()) : b.engine;
+ const result = await b.append(racing);
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({
+ file: before.file + (mode === 'late-file' ? EDIT : ''), body: before.body + (mode === 'late-database' ? EDIT : ''),
+ });
+ expect(result).toMatchObject({ inserted: 0, legacyFallback: true, databaseOnlyReason: 'file_database_drift' });
+ expect(result.warning).toContain(`${SLUG} (file_database_drift`);
+ expect(result.warning).toContain('gbrain sync --source default');
+ expect((await writeSingleFact(b.engine, 'default', { fact: CLAIM, entity: SLUG, provenance: 'test', visibility: 'world' })).status).toBe('inserted');
+ expect(await b.engine.executeRaw('SELECT fact, row_num FROM facts')).toEqual([{ fact: CLAIM, row_num: null }]);
+ });
+ }, 180_000);
+
+ test('agreeing copies append and preserve the prior body', async () => {
+ await withFactsBrain(databaseUrl, async b => {
+ const before = await b.body();
+ expect((await b.append()).inserted).toBe(1);
+ expect(parseFactsFence(b.bytes()).facts.map(f => f.claim)).toEqual([CLAIM]);
+ expect(parseFactsFence(await b.body()).facts.map(f => f.claim)).toEqual([CLAIM]);
+ expect(await b.engine.executeRaw('SELECT compiled_truth FROM page_versions WHERE compiled_truth = $1', [before])).toHaveLength(1);
+ });
+ }, 180_000);
+});
diff --git a/test/pathological/d3-forget-overwrite.test.ts b/test/pathological/d3-forget-overwrite.test.ts
new file mode 100644
index 0000000000..4ca27fc912
--- /dev/null
+++ b/test/pathological/d3-forget-overwrite.test.ts
@@ -0,0 +1,83 @@
+/**
+ * D-3 (GBRA-131, #6982): withdrawal is authoritative even when its file mirror is held.
+ * Protects: differing or concurrently edited copies keep their exact bodies; withdrawal still commits and is
+ * reported with file_database_drift. Agreeing copies still strike the file and stored body.
+ * Fails when: forget strikes the file and unconditionally mirrors all its prose over the database.
+ * Existing forget tests cover withdrawal durability but not divergent copies of a live page.
+ * Seams: engine transaction proxy lands real file/DB edits after fence preparation; no production hook.
+ */
+import { describe, expect, test } from 'bun:test';
+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';
+
+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 () => {
+ await withFactsBrain(databaseUrl, async b => {
+ const id = (await b.append()).ids[0]!;
+ if (mode === 'database') await b.dbEdit();
+ if (mode === 'file') b.fileEdit();
+ const before = { file: b.bytes(), body: await b.body() };
+ const racing = mode.startsWith('late-') ? editWhenPrepared(b, () => mode === 'late-database' ? b.dbEdit() : b.fileEdit()) : b.engine;
+ const result = await forgetFactInFence(racing, id, action === 'supersession' ? { supersededBy: { rowNum: null } } : {});
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({
+ file: before.file + (mode === 'late-file' ? EDIT : ''), body: before.body + (mode === 'late-database' ? EDIT : ''),
+ });
+ expect(result).toMatchObject({ ok: true, path: 'legacy_db' });
+ expect(result.warning).toContain(`${SLUG} (file_database_drift`);
+ expect(await b.engine.executeRaw('SELECT id FROM facts WHERE expired_at IS NULL')).toEqual([]);
+ expect(await b.engine.executeRaw('SELECT fact_hash FROM fact_withdrawals')).toHaveLength(action === 'withdrawal' ? 1 : 0);
+ });
+ }, 180_000);
+
+ test('agreeing copies are struck in file and database', async () => {
+ await withFactsBrain(databaseUrl, async b => {
+ const id = (await b.append()).ids[0]!;
+ expect((await forgetFactInFence(b.engine, id)).path).toBe('fence');
+ expect(parseFactsFence(b.bytes()).facts[0]!.active).toBe(false);
+ expect(parseFactsFence(await b.body()).facts[0]!.active).toBe(false);
+ });
+ }, 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]!;
+ await b.dbEdit();
+ const before = b.bytes();
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ expect((await forgetFactInFence(b.engine, id)).path).toBe('legacy_db');
+ expect(b.bytes()).toBe(before);
+ expect(await b.body()).toContain(EDIT.trim());
+ expect(parseFactsFence(await b.body()).facts[0]!.active).toBe(false);
+ });
+ }, 180_000);
+
+ test('write-through off holds a database-only mirror when a late edit lands', async () => {
+ await withFactsBrain(databaseUrl, async b => {
+ const id = (await b.append()).ids[0]!;
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ const before = { file: b.bytes(), body: await b.body() };
+ let transactions = 0;
+ const racing = editWhenPrepared(b, () => b.dbEdit(), () => ++transactions === 2);
+ const result = await forgetFactInFence(racing, id);
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: before.file, body: before.body + EDIT });
+ expect(result.warning).toContain(`${SLUG} (revision_conflict`);
+ expect(await b.engine.executeRaw('SELECT id FROM facts WHERE expired_at IS NULL')).toEqual([]);
+ });
+ }, 180_000);
+
+ test('a run-scoped database-only mirror failure still throws after withdrawal commits', async () => {
+ for (const fault of runScopedErrors()) await withFactsBrain(databaseUrl, async b => {
+ const id = (await b.append()).ids[0]!;
+ await b.engine.executeRaw("UPDATE sources SET local_path = NULL WHERE id = 'default'");
+ let transactions = 0;
+ const racing = editWhenPrepared(b, () => { throw fault.error(); }, () => ++transactions === 2);
+ await expect(forgetFactInFence(racing, id)).rejects.toThrow();
+ expect(await b.engine.executeRaw('SELECT id FROM facts WHERE expired_at IS NULL')).toEqual([]);
+ });
+ }, 180_000);
+});
diff --git a/test/pathological/d4-proposal-overwrite.test.ts b/test/pathological/d4-proposal-overwrite.test.ts
new file mode 100644
index 0000000000..b3906369cb
--- /dev/null
+++ b/test/pathological/d4-proposal-overwrite.test.ts
@@ -0,0 +1,81 @@
+/**
+ * D-4 (GBRA-131, #6982): proposal accept/undo refuses one divergent page instead of overwriting either copy.
+ * Protects: database/file-newer and concurrent edits preserve exact bodies, facts and proposal status;
+ * 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.
+ */
+import { describe, expect, test } from 'bun:test';
+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';
+
+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 () => {
+ 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: 'synthetic-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');
+ if (mode === 'database') await b.dbEdit();
+ if (mode === 'file') b.fileEdit();
+ const before = { file: b.bytes(), body: await b.body(), facts: await b.engine.executeRaw('SELECT expired_at::text, superseded_by FROM facts ORDER BY id') };
+ const racing = mode.startsWith('late-') ? editWhenPrepared(b, () => mode === 'late-database' ? b.dbEdit() : b.fileEdit(), () => true) : b.engine;
+ const result = await applyProposalAction(racing, id, action);
+ if (mode === 'agree') {
+ expect(result.status).toBe(action === 'accept' ? 'accepted' : 'undone');
+ expect(b.bytes()).not.toBe(before.file);
+ expect(await b.body()).not.toBe(before.body);
+ return;
+ }
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: before.file + (mode === 'late-file' ? EDIT : ''), body: before.body + (mode === 'late-database' ? EDIT : '') });
+ expect(result.status).toBe('refused');
+ expect(result.reason).toContain(`${SLUG} (file_database_drift`);
+ expect(await b.engine.executeRaw('SELECT expired_at::text, superseded_by FROM facts ORDER BY id')).toEqual(before.facts);
+ expect(await b.engine.executeRaw('SELECT status FROM decide_proposals WHERE id = $1', [id])).toEqual([{ status: action === 'accept' ? 'pending' : 'accepted' }]);
+ });
+ }, 180_000);
+
+ test('write-through off accepts and undoes on the newer database body without writing the 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: 'db-only-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' }))!;
+ await b.dbEdit();
+ const before = b.bytes();
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ expect((await applyProposalAction(b.engine, id, 'accept')).status).toBe('accepted');
+ expect(b.bytes()).toBe(before);
+ expect(await b.body()).toContain(EDIT.trim());
+ expect((await applyProposalAction(b.engine, id, 'undo')).status).toBe('undone');
+ expect(b.bytes()).toBe(before);
+ expect(await b.body()).toContain(EDIT.trim());
+ });
+ }, 180_000);
+
+ for (const action of ['accept', 'undo'] as const) test(`database-only ${action} holds a late database edit`, 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: 'db-race-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' }))!;
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ if (action === 'undo') expect((await applyProposalAction(b.engine, id, 'accept')).status).toBe('accepted');
+ const before = { file: b.bytes(), body: await b.body(), facts: await b.engine.executeRaw('SELECT expired_at::text, superseded_by FROM facts ORDER BY id') };
+ const result = await applyProposalAction(editWhenPrepared(b, () => b.dbEdit(), () => true), id, action);
+ expect({ file: b.bytes(), body: await b.body() }).toEqual({ file: before.file, body: before.body + EDIT });
+ expect(result.status).toBe('refused');
+ expect(result.reason).toContain(`${SLUG} (revision_conflict`);
+ expect(await b.engine.executeRaw('SELECT expired_at::text, superseded_by FROM facts ORDER BY id')).toEqual(before.facts);
+ });
+ }, 180_000);
+});
diff --git a/test/pathological/facts-overwrite-fixture.ts b/test/pathological/facts-overwrite-fixture.ts
new file mode 100644
index 0000000000..14e1df64b7
--- /dev/null
+++ b/test/pathological/facts-overwrite-fixture.ts
@@ -0,0 +1,70 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { writeFactsToFence } from '../../src/core/facts/fence-write.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+export const SLUG = 'people/alice-example';
+export const CLAIM = 'Alice Example leads research';
+export const EDIT = '\n\nAn independent edit that must survive.\n';
+
+export async function withFactsBrain(databaseUrl: string | undefined, run: (b: FactsBrain) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'facts-overwrite-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ _resetWriteThroughCacheForTest();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const root = join(home, 'brain');
+ const file = join(root, `${SLUG}.md`);
+ mkdirSync(dirname(file), { recursive: true });
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);
+ await engine.putPage(SLUG, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example\n\nA person.\n' });
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));
+ const b: FactsBrain = {
+ engine, root, file,
+ bytes: () => readFileSync(file, 'utf8'),
+ body: async () => (await engine.executeRaw<{ compiled_truth: string }>("SELECT compiled_truth FROM pages WHERE source_id = 'default' AND slug = $1", [SLUG]))[0]!.compiled_truth,
+ async append(on = engine, claim = CLAIM) {
+ return writeFactsToFence(on, { sourceId: 'default', localPath: root, slug: SLUG, resolutionSource: 'exact_page' },
+ [{ fact: claim, kind: 'fact', notability: 'medium', source: 'test', visibility: 'world', embedding: null, sessionId: null }]);
+ },
+ async dbEdit() {
+ await engine.executeRaw("UPDATE pages SET compiled_truth = compiled_truth || $2 WHERE source_id = 'default' AND slug = $1", [SLUG, EDIT]);
+ },
+ fileEdit() { writeFileSync(file, readFileSync(file, 'utf8') + EDIT); },
+ };
+ await run(b);
+ } finally { await close(); _resetWriteThroughCacheForTest(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+export interface FactsBrain {
+ engine: BrainEngine;
+ root: string;
+ file: string;
+ bytes(): string;
+ body(): Promise<string>;
+ append(on?: BrainEngine, claim?: string): ReturnType<typeof writeFactsToFence>;
+ dbEdit(): Promise<void>;
+ fileEdit(): void;
+}
+
+/** Land an edit after planning, immediately before the transaction that publishes the prepared fence. */
+export function editWhenPrepared(b: FactsBrain, edit: () => Promise<void> | void, prepared = () => existsSync(`${b.file}.tmp`)): BrainEngine {
+ let fired = false;
+ return new Proxy(b.engine, { get(target, prop) {
+ if (prop === 'transaction') return async (...args: unknown[]) => {
+ if (!fired && prepared()) { fired = true; await edit(); }
+ return (target.transaction as (...a: unknown[]) => unknown).apply(target, args);
+ };
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}