Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): the unfenced-facts fence step never mirrors a file over a differing database body (#6982)

garrytan32f384900065
diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.ts
new file mode 100644
index 0000000000..f09db2fdb1
--- /dev/null
+++ b/src/core/facts/file-body-guard.ts
@@ -0,0 +1,94 @@
+/**
+ * #6982: the guard every unmanaged writer that mirrors a checkout file into `pages` runs first. A fence writer plans
+ * its edit on the file and then copies the file's body over the page's database body (`refreshPageBody`, a narrow
+ * UPDATE with no version of its own). That copy is only safe when the database body is the file's body: otherwise the
+ * database holds an edit the file lacks (a database-only write with `sync.write_through` off, a remote write, a
+ * failed write-through) or the file holds one sync has not imported, and the copy silently drops one of them.
+ *
+ * The comparison is the one the mirror can lose: the parsed and sanitized file body and timeline against the stored
+ * ones, trimmed as the importer trims them. Frontmatter, title, type and tags are not compared because the mirror
+ * never writes them. `mirrorFileBody` re-reads the stored body under a row lock inside the caller's transaction and
+ * writes only when it still equals the body the caller compared, keeping the replaced body in page_versions first.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import type { BrainEngine } from '../engine.ts';
+import { sanitizeText } from '../batch-rows.ts';
+import { parseMarkdown } from '../markdown.ts';
+import { contentHash, contentHashFrontmatterAndTags } from '../utils.ts';
+
+export interface StoredBody {
+ compiled_truth: string | null;
+ timeline: string | null;
+}
+
+/** 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`);
+ return { compiled_truth: sanitizeText(parsed.compiled_truth), timeline: sanitizeText(parsed.timeline ?? '') };
+}
+
+/** Whether mirroring `fileBytes` over `stored` would replace nothing but whitespace the importer trims. */
+export function fileBodyMatchesStored(fileBytes: string, slug: string, stored: StoredBody): boolean {
+ const file = mirroredBody(fileBytes, slug);
+ return file.compiled_truth.trim() === (stored.compiled_truth ?? '').trim() && file.timeline.trim() === (stored.timeline ?? '').trim();
+}
+
+/** The live page's stored body, or null when there is no live page. `lock` takes the row lock (inside a transaction). */
+export async function readStoredBody(engine: BrainEngine, sourceId: string, slug: string, lock = false): Promise<StoredBody | null> {
+ const [row] = await engine.executeRaw<StoredBody>(
+ `SELECT compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL${lock ? ' FOR UPDATE' : ''}`,
+ [sourceId, slug]);
+ return row ?? null;
+}
+
+/**
+ * Inside `tx`: lock the page, and when its stored body is still `expected` (the body the caller compared with the file
+ * before planning), keep it in page_versions and mirror `fileBytes` over it. The row keeps its content_hash, so the
+ * next sync re-imports and re-chunks the page. Returns false, writing nothing, when the page is gone or moved.
+ */
+export async function mirrorFileBody(tx: BrainEngine, sourceId: string, slug: string, fileBytes: string, expected: StoredBody): Promise<boolean> {
+ const current = await readStoredBody(tx, sourceId, slug, true);
+ if (!current || current.compiled_truth !== expected.compiled_truth || current.timeline !== expected.timeline) return false;
+ const page = await tx.getPage(slug, { sourceId });
+ if (!page) return false;
+ await tx.createVersion(slug, { sourceId });
+ const body = mirroredBody(fileBytes, slug);
+ await tx.refreshPageBody(slug, sourceId, body.compiled_truth, body.timeline, page.content_hash || contentHash(page));
+ return true;
+}
+
+/** Page states a checkout file is compared with: the live row, then its newest page_versions rows. */
+const HISTORY_ROWS = 20;
+
+interface StoredState extends StoredBody { frontmatter: Record<string, unknown> | null }
+
+/** Whether the file's body, timeline and every frontmatter key it carries (ephemeral keys aside) equal `state`'s. */
+function fileHeldBy(fileBytes: string, slug: string, state: StoredState): boolean {
+ if (!fileBodyMatchesStored(fileBytes, slug, state)) return false;
+ const file = contentHashFrontmatterAndTags({ frontmatter: parseMarkdown(fileBytes, `${slug}.md`).frontmatter });
+ const stored = contentHashFrontmatterAndTags({ frontmatter: state.frontmatter ?? {} });
+ return Object.entries(file.frontmatter).every(([key, value]) => JSON.stringify(value) === JSON.stringify(stored.frontmatter[key]));
+}
+
+/**
+ * #6982, the database→file direction: whether gbrain may replace or remove the checkout file at `filePath` for page
+ * `slug` without losing an edit. It may when the file is absent, or when the file holds nothing the database lacks:
+ * its body, timeline and frontmatter equal the live page's or one of its newest page_versions rows (the state before
+ * the database write being published). Otherwise the file carries an edit only it holds (a hand edit sync has not
+ * imported, or an unindexed file at the path), and the caller leaves it and reports the page.
+ *
+ * `expectedFileBytes` is what the caller passes to `writePageThrough` (null: the file must still be absent), so a file
+ * that changes between this check and the write is refused there too.
+ */
+export async function replaceableFile(engine: BrainEngine, sourceId: string, slug: string, filePath: string):
+ Promise<{ ok: true; expectedFileBytes: string | null } | { ok: false }> {
+ if (!existsSync(filePath)) return { ok: true, expectedFileBytes: null };
+ const bytes = readFileSync(filePath, 'utf-8');
+ const states = await engine.executeRaw<StoredState>(
+ `(SELECT compiled_truth, timeline, frontmatter FROM pages WHERE source_id = $1 AND slug = $2)
+ UNION ALL
+ (SELECT v.compiled_truth, v.timeline, v.frontmatter FROM page_versions v JOIN pages p ON p.id = v.page_id
+ WHERE p.source_id = $1 AND p.slug = $2 AND v.compiled_truth IS NOT NULL ORDER BY v.id DESC LIMIT ${HISTORY_ROWS})`,
+ [sourceId, slug]);
+ return states.some(state => fileHeldBy(bytes, slug, state)) ? { ok: true, expectedFileBytes: bytes } : { ok: false };
+}
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
index a2be5bd424..56969dcb95 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -52,7 +52,7 @@
* durability-hardened checkout commits the file.
* A page that fails is reported in `failed_pages`; the others still fence.
*/
-import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import { sanitizeText } from '../batch-rows.ts';
@@ -74,7 +74,9 @@ import { assertPersistenceAccepting } from '../persistence/service.ts';
import type { WriteAuthority } from '../persistence/model.ts';
import { UNBOUND_WRITE_KEY } from '../persistence/unbound-source.ts';
import { contentHash } from '../utils.ts';
-import { resolvePageWriteTarget } from '../write-through.ts';
+import { bodyUnread } from '../page-body/page-shape.ts';
+import { fileBodyMatchesStored, 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';
@@ -303,10 +305,15 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:
}
const filePaths = new Map<string, string>();
const databaseOnly = new Map<string, NonNullable<WriteAuthority['databaseOnlyReason']>>();
+ const writeThroughOff = !managed && await isWriteThroughDisabled(engine);
for (const [key, group] of managed ? [] : [...groups]) {
const [sourceId, entitySlug] = key.split('\0');
const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
- if (target.ok && existsSync(target.filePath)) { filePaths.set(key, target.filePath); continue; }
+ if (target.ok && existsSync(target.filePath)) {
+ if (writeThroughOff) databaseOnly.set(key, 'disabled_by_config');
+ else filePaths.set(key, target.filePath);
+ continue;
+ }
const placement = await databaseOnlyPlacement(engine, sourceId, entitySlug);
if (placement.kind === 'fence') { databaseOnly.set(key, placement.reason); continue; }
groups.delete(key);
@@ -539,14 +546,44 @@ async function fenceDatabaseOnlyPage(engine: BrainEngine, sourceId: string, enti
}
}
-/** One unmanaged page: file first (atomic), then the page mirror and row stamps in one maintenance transaction. */
+/**
+ * #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.
+ * The page row is then locked and re-read in a maintenance transaction: when the database or the file moved since the
+ * comparison, nothing is written. Otherwise the prior body is kept in page_versions, the body is mirrored, the rows are
+ * stamped, and the `.tmp` is renamed into place last, so a rolled-back transaction leaves the file as it was.
+ */
async function fenceFilePage(engine: BrainEngine, sourceId: string, entitySlug: string, filePath: string,
group: UnfencedFactRow[], outcome: UnfencedFactsOutcome, lockRoot?: string): Promise<void> {
const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
if (!target.ok) { outcome.skipped_no_page += group.length; return; }
const { writeRoot } = target;
const write = () => withPageLock(entitySlug, async () => {
- const fence = await planFence(engine, sourceId, entitySlug, readFileSync(filePath, 'utf-8'), group);
+ const bytes = readFileSync(filePath, 'utf-8');
+ const page = await engine.getPage(entitySlug, { sourceId });
+ const stored = page && await readStoredBody(engine, sourceId, entitySlug);
+ if (!page || !stored) { outcome.skipped_no_page += group.length; return; }
+ if (bodyUnread(page)) {
+ outcome.failed_pages.push(`${entitySlug} (page_body_segmented: the page is stored in segments, so its file is not compared or rewritten here; its rows stay unfenced, active and searchable)`);
+ return;
+ }
+ if (!fileBodyMatchesStored(bytes, entitySlug, stored)) {
+ outcome.failed_pages.push(fileDatabaseDriftToken(entitySlug, sourceId, 'before'));
+ return;
+ }
+ const fence = await planFence(engine, sourceId, entitySlug, bytes, group);
if ('warnings' in fence) {
outcome.failed_pages.push(`${entitySlug} (${fence.warnings.join('; ')})`);
return;
@@ -565,17 +602,10 @@ async function fenceFilePage(engine: BrainEngine, sourceId: string, entitySlug:
outcome.failed_pages.push(`${entitySlug} (${parsed.warnings.join('; ')})`);
return;
}
- renameSync(tmpPath, filePath);
// Mirror the file into pages so this run's reconcile and get_page read the
- // new fence (same body-only mirror as fence-write.ts: the row keeps its
- // content_hash, so the next sync re-imports and re-chunks the page).
- const reparsed = parseMarkdown(tmpBody, `${entitySlug}.md`);
- await maintenanceTransaction(engine, async tx => {
- const existing = await tx.getPage(entitySlug, { sourceId });
- if (existing) {
- await tx.refreshPageBody(entitySlug, sourceId, sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
- existing.content_hash || contentHash(existing));
- }
+ // new fence (same body-only mirror as fence-write.ts).
+ const written = await maintenanceTransaction(engine, async tx => {
+ if (readFileSync(filePath, 'utf-8') !== bytes || !await mirrorFileBody(tx, sourceId, entitySlug, tmpBody, stored)) return false;
// The parsed claim is what the fence projects; the row keeps its id,
// vectors and provenance (the reconcile would retire a row whose text
// differs from its fence row).
@@ -586,7 +616,15 @@ async function fenceFilePage(engine: BrainEngine, sourceId: string, entitySlug:
[a.row_num, entitySlug, a.id, sourceId, a.fact],
);
}
+ assertSourceFilesystemActive();
+ renameSync(tmpPath, filePath);
+ return true;
});
+ if (!written) {
+ rmSync(tmpPath, { force: true });
+ outcome.failed_pages.push(fileDatabaseDriftToken(entitySlug, sourceId, 'during'));
+ return;
+ }
if (durable) await commitFactFenceFile(writeRoot, filePath, entitySlug, sourceId, prewrite);
outcome.fenced += fence.assignments.length;
outcome.pages_touched += 1;
diff --git a/test/pathological/d1-unfenced-facts-overwrite.test.ts b/test/pathological/d1-unfenced-facts-overwrite.test.ts
new file mode 100644
index 0000000000..d7c9a2b010
--- /dev/null
+++ b/test/pathological/d1-unfenced-facts-overwrite.test.ts
@@ -0,0 +1,227 @@
+/**
+ * D-1 (GBRA-131, #6982): the extract_facts fence step never replaces a page's
+ * database body with an older or different checkout file.
+ *
+ * Protects: on an unmanaged brain, a page whose database body differs from its
+ * canonical file keeps both copies. With `sync.write_through` off the database
+ * is the copy of record, so the unfenced rows are fenced into the database
+ * body (a coordinated database-only publication that records the prior body
+ * in page_versions) and the file is not touched. With write-through on, a page
+ * whose file and database body differ (a newer database-only edit, a newer
+ * file edit sync has not imported, or an edit that lands while the step runs)
+ * is held: its rows stay unfenced, the warning names the page with
+ * `file_database_drift`, neither copy changes, and the other pages of the run
+ * still fence. A page whose copies agree fences as before, and the body it
+ * replaces is kept in page_versions.
+ * Fails when: the step plans the fence on the file and mirrors the file into
+ * `pages` without comparing (the pre-fix refreshPageBody path), which drops
+ * the database-only edit with no page_versions row holding it.
+ * Seams: an engine proxy whose first transaction lands a concurrent edit
+ * (database or file) after the step compared the copies. PGLite always,
+ * Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { runCycle } from '../../src/core/cycle.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { parseFactsFence } from '../../src/core/facts-fence.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, snapshotItems } from './harness.ts';
+
+const ALICE = 'people/alice-example';
+const BOB = 'people/bob-example';
+const DB_EDIT = 'DB-ONLY-EDIT-MARKER: a paragraph written with write-through disabled.';
+const FILE_EDIT = 'FILE-ONLY-EDIT-MARKER: a paragraph saved in the editor, not yet synced.';
+const LATE_EDIT = 'CONCURRENT-EDIT-MARKER: written while the fence step ran.';
+
+interface Brain {
+ engine: BrainEngine;
+ root: string;
+ file(slug: string): string;
+ body(slug: string): Promise<string>;
+ /** A database-only edit (the put_page path with write-through off, or a SQL edit): appends a paragraph to the stored body. */
+ dbEdit(slug: string, paragraph: string, engine?: BrainEngine): Promise<void>;
+ rows(slug: string): Promise<Array<{ fact: string; row_num: number | null }>>;
+ versionsHolding(slug: string, marker: string): Promise<number>;
+ unfenced(slug: string, fact: string): Promise<void>;
+ cycle(engine?: BrainEngine): Promise<{ status: string; warnings: string[] }>;
+}
+
+const personBody = (title: string) => `# ${title}\n\n${title} works at Acme Example.`;
+
+async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d1-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ _resetWriteThroughCacheForTest();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ const root = join(home, 'brain');
+ mkdirSync(root, { recursive: true });
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);
+ const path = (slug: string) => join(root, `${slug}.md`);
+ for (const [slug, title] of [[ALICE, 'Alice Example'], [BOB, 'Bob Example']] as const) {
+ const page = await engine.putPage(slug, { type: 'person', title, compiled_truth: personBody(title) });
+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${slug}.md`, page.id]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ mkdirSync(dirname(path(slug)), { recursive: true });
+ writeFileSync(path(slug), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ }
+ const b: Brain = {
+ engine, root,
+ file: slug => readFileSync(path(slug), 'utf8'),
+ body: async slug => (await engine.executeRaw<{ compiled_truth: string }>(
+ "SELECT compiled_truth FROM pages WHERE source_id = 'default' AND slug = $1", [slug]))[0]!.compiled_truth,
+ async dbEdit(slug, paragraph, on = engine) {
+ const page = (await on.getPage(slug, { sourceId: 'default' }))!;
+ await on.putPage(slug, { type: page.type, title: page.title, compiled_truth: `${page.compiled_truth.trimEnd()}\n\n${paragraph}\n`,
+ timeline: page.timeline, frontmatter: page.frontmatter }, { sourceId: 'default' } as never);
+ },
+ rows: async slug => (await engine.executeRaw<{ fact: string; row_num: number | null }>(
+ "SELECT fact, row_num FROM facts WHERE source_id = 'default' AND entity_slug = $1 AND expired_at IS NULL ORDER BY id", [slug]))
+ .map(r => ({ fact: r.fact, row_num: r.row_num === null ? null : Number(r.row_num) })),
+ versionsHolding: async (slug, marker) => Number((await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id = v.page_id
+ WHERE p.source_id = 'default' AND p.slug = $1 AND v.compiled_truth LIKE '%' || $2 || '%'`, [slug, marker]))[0]!.n),
+ async unfenced(slug, fact) {
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ('default', $1, $2, 'fact', 'private', 'medium', '2026-02-05', 'mcp:remember', 0.9)`, [slug, fact]);
+ },
+ async cycle(on = engine) {
+ const report = await runCycle(on, { brainDir: root, sourceId: 'default', phases: ['extract_facts'] });
+ const phase = report.phases.find(p => p.phase === 'extract_facts')!;
+ return { status: phase.status, warnings: ((phase.details as { warnings?: string[] })?.warnings ?? []).map(String) };
+ },
+ };
+ await run(b);
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+/**
+ * The engine whose first transaction after the step prepared the fence write for `file` (its `.tmp` exists, or the
+ * file already carries the fence) runs `before` first: a concurrent edit landing after the step compared the copies.
+ */
+function editsOnceFencePrepared(engine: BrainEngine, file: string, before: () => Promise<void>): BrainEngine {
+ let fired = false;
+ const prepared = () => existsSync(`${file}.tmp`) || fenceClaims(readFileSync(file, 'utf8')).length > 0;
+ return new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'transaction') return async (...args: unknown[]) => {
+ if (!fired && prepared()) { fired = true; await before(); }
+ 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;
+ },
+ });
+}
+
+const fenceClaims = (text: string) => parseFactsFence(text).facts.map(f => f.claim);
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-1 extract_facts fence step and a database body newer than the file (${backend})`, () => {
+ test('D-1 db-newer, write-through off: the rows are fenced into the database body, the edit survives and the file is untouched', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ await b.dbEdit(ALICE, DB_EDIT);
+ await b.unfenced(ALICE, 'Alice Example moved to Lisbon');
+ const fileBefore = b.file(ALICE);
+ const phase = await expectUnitNotAborted(() => b.cycle());
+ const body = await b.body(ALICE);
+ expect({ edit: body.includes(DB_EDIT), fence: fenceClaims(body) }).toEqual({ edit: true, fence: ['Alice Example moved to Lisbon'] });
+ expect({ file: b.file(ALICE) === fileBefore }).toEqual({ file: true });
+ expect(await b.rows(ALICE)).toEqual([{ fact: 'Alice Example moved to Lisbon', row_num: 1 }]);
+ expect(await b.versionsHolding(ALICE, DB_EDIT)).toBeGreaterThan(0);
+ expect(phase.warnings.filter(w => w.includes(ALICE))).toEqual([]);
+ });
+ }, 180_000);
+
+ test('D-1 db-newer, write-through on: the page is held with file_database_drift, both copies stay, the other page still fences', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.dbEdit(ALICE, DB_EDIT);
+ await b.unfenced(ALICE, 'Alice Example moved to Lisbon');
+ await b.unfenced(BOB, 'Bob Example moved to Porto');
+ const fileBefore = b.file(ALICE);
+ const bodyBefore = await b.body(ALICE);
+ const before = await snapshotItems(b.engine, 'default');
+ const phase = await expectUnitNotAborted(() => b.cycle());
+ expect({ body: (await b.body(ALICE)) === bodyBefore, file: b.file(ALICE) === fileBefore }).toEqual({ body: true, file: true });
+ expect(await b.rows(ALICE)).toEqual([{ fact: 'Alice Example moved to Lisbon', row_num: null }]);
+ const held = phase.warnings.filter(w => w.includes(`FACTS_FENCE_FAILED: ${ALICE} (file_database_drift`));
+ expect({ held: held.length, fix: held.some(w => w.includes('gbrain sync --source default')) }).toEqual({ held: 1, fix: true });
+ expect(await b.rows(BOB)).toEqual([{ fact: 'Bob Example moved to Porto', row_num: 1 }]);
+ expect(fenceClaims(b.file(BOB))).toEqual(['Bob Example moved to Porto']);
+ expectOthersUnchanged(before, await snapshotItems(b.engine, 'default'), { expectProgress: [BOB], progressFields: ['updated_at'] });
+ });
+ }, 180_000);
+
+ test('D-1 file-newer, write-through on: an unimported file edit holds the page and the database body is not replaced', async () => {
+ await withBrain(databaseUrl, async b => {
+ const edited = b.file(ALICE).replace('works at Acme Example.', `works at Acme Example.\n\n${FILE_EDIT}`);
+ writeFileSync(join(b.root, `${ALICE}.md`), edited);
+ await b.unfenced(ALICE, 'Alice Example moved to Lisbon');
+ const bodyBefore = await b.body(ALICE);
+ const phase = await expectUnitNotAborted(() => b.cycle());
+ expect({ body: (await b.body(ALICE)) === bodyBefore, file: b.file(ALICE) === edited }).toEqual({ body: true, file: true });
+ expect(await b.rows(ALICE)).toEqual([{ fact: 'Alice Example moved to Lisbon', row_num: null }]);
+ expect(phase.warnings.filter(w => w.includes(`FACTS_FENCE_FAILED: ${ALICE} (file_database_drift`)).length).toBe(1);
+ });
+ }, 180_000);
+
+ test('D-1 agreeing copies, write-through on: the fence lands in the file and the database, and the replaced body is kept in page_versions', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.unfenced(ALICE, 'Alice Example moved to Lisbon');
+ const bodyBefore = await b.body(ALICE);
+ const versionsBefore = await b.versionsHolding(ALICE, 'works at Acme Example');
+ const phase = await expectUnitNotAborted(() => b.cycle());
+ expect(phase.warnings.filter(w => w.includes(ALICE))).toEqual([]);
+ expect({ file: fenceClaims(b.file(ALICE)), db: fenceClaims(await b.body(ALICE)) })
+ .toEqual({ file: ['Alice Example moved to Lisbon'], db: ['Alice Example moved to Lisbon'] });
+ expect((await b.body(ALICE)).startsWith(bodyBefore.trimEnd())).toBe(true);
+ expect(await b.versionsHolding(ALICE, 'works at Acme Example')).toBe(versionsBefore + 1);
+ });
+ }, 180_000);
+
+ test('D-1 concurrent database edit after the comparison: the edit survives, the file is untouched and the page is held', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.unfenced(ALICE, 'Alice Example moved to Lisbon');
+ const fileBefore = b.file(ALICE);
+ let landed = false;
+ const racing = editsOnceFencePrepared(b.engine, join(b.root, `${ALICE}.md`), async () => { await b.dbEdit(ALICE, LATE_EDIT); landed = true; });
+ const phase = await expectUnitNotAborted(() => b.cycle(racing));
+ expect(landed).toBe(true);
+ expect({ edit: (await b.body(ALICE)).includes(LATE_EDIT), file: b.file(ALICE) === fileBefore }).toEqual({ edit: true, file: true });
+ expect(await b.rows(ALICE)).toEqual([{ fact: 'Alice Example moved to Lisbon', row_num: null }]);
+ expect(phase.warnings.filter(w => w.includes(`FACTS_FENCE_FAILED: ${ALICE} (file_database_drift`)).length).toBe(1);
+ });
+ }, 180_000);
+
+ test('D-1 concurrent file edit after the comparison: the editor\'s bytes survive and the database body is not replaced', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.unfenced(ALICE, 'Alice Example moved to Lisbon');
+ const bodyBefore = await b.body(ALICE);
+ let edited = '';
+ const racing = editsOnceFencePrepared(b.engine, join(b.root, `${ALICE}.md`), async () => {
+ edited = b.file(ALICE).replace('works at Acme Example.', `works at Acme Example.\n\n${LATE_EDIT}`);
+ writeFileSync(join(b.root, `${ALICE}.md`), edited);
+ });
+ const phase = await expectUnitNotAborted(() => b.cycle(racing));
+ expect(edited).toContain(LATE_EDIT);
+ expect({ file: b.file(ALICE) === edited, body: (await b.body(ALICE)) === bodyBefore }).toEqual({ file: true, body: true });
+ expect(await b.rows(ALICE)).toEqual([{ fact: 'Alice Example moved to Lisbon', row_num: null }]);
+ expect(phase.warnings.filter(w => w.includes(`FACTS_FENCE_FAILED: ${ALICE} (file_database_drift`)).length).toBe(1);
+ });
+ }, 180_000);
+ });
+}