Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): preserve divergent checkout and database bodies

garrytan49c5c83d424f
diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.ts
index 836f5b11ca..2f80f70686 100644
--- a/src/commands/migrations/v0_32_2.ts
+++ b/src/commands/migrations/v0_32_2.ts
@@ -47,9 +47,10 @@ import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
import { parseFactsFence } from '../../core/facts-fence.ts';
import { duplicateActiveFenceRows } from '../../core/facts/extract-from-fence.ts';
-import { resolvePageWriteTarget } from '../../core/write-through.ts';
+import { isWriteThroughDisabled, resolvePageWriteTarget } from '../../core/write-through.ts';
import { serializePageToMarkdown } from '../../core/markdown.ts';
import { managedPersistenceEnabled } from '../../core/persistence/ownership.ts';
+import { isSourceDbOnlySlug } from '../../core/persistence/source-storage.ts';
import { OperationError } from '../../core/ops/contract.ts';
import { fenceableRowCount, fenceUnfencedFacts, planUnfencedFacts, type UnfencedFactsOutcome } from '../../core/facts/unfenced-facts.ts';
@@ -262,24 +263,34 @@ async function phaseCVerify(
// the canonical file in the same publication; the database copy is the
// one every managed page has, database-only pages included.
const managed = await managedPersistenceEnabled(engine);
+ const writeThroughOff = !managed && await isWriteThroughDisabled(engine);
for (const g of groups) {
let body: string;
- if (managed) {
+ const target = managed ? null : await resolvePageWriteTarget(engine, g.source_markdown_slug, g.source_id);
+ const fileExists = target?.ok === true && existsSync(target.filePath);
+ const root = localPathById.get(g.source_id) ?? (target?.ok ? target.writeRoot : null);
+ let databaseOnly = managed || writeThroughOff || !!root && isSourceDbOnlySlug(root, g.source_markdown_slug, 'refuse');
+ if (!databaseOnly && !fileExists) {
+ const page = await engine.getPage(g.source_markdown_slug, { sourceId: g.source_id });
+ databaseOnly = !!page && !page.source_path?.trim() && !page.source_uri?.trim();
+ }
+ if (databaseOnly) {
const snapshot = await engine.readPageSnapshot(g.source_markdown_slug, { sourceId: g.source_id });
if (!snapshot) {
if (g.all_expired) skippedExpiredNoPage += 1;
else mismatches.push(`${g.source_markdown_slug} (page missing)`);
continue;
}
+ if (snapshot.page.body_storage === 'segmented') {
+ mismatches.push(`${g.source_markdown_slug} (page_body_segmented: verify cannot read its whole body; read it with gbrain get --source ${g.source_id} --body auto -- ${g.source_markdown_slug})`);
+ continue;
+ }
body = serializePageToMarkdown(snapshot.page, snapshot.tags);
} else {
- const localPath = localPathById.get(g.source_id);
- if (!localPath) continue;
- const target = await resolvePageWriteTarget(engine, g.source_markdown_slug, g.source_id);
- if (!target.ok || !existsSync(target.filePath)) {
+ if (!target?.ok || !fileExists) {
// Skip only an absent file; an unresolvable target is still drift.
- if (target.ok && g.all_expired) skippedExpiredNoPage += 1;
+ if (target?.ok && g.all_expired) skippedExpiredNoPage += 1;
else mismatches.push(`${g.source_markdown_slug} (file missing)`);
continue;
}
diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.ts
index 87492937fd..29f4255aa8 100644
--- a/src/commands/sync/full.ts
+++ b/src/commands/sync/full.ts
@@ -44,6 +44,8 @@ import {
import type { SyncOpts, SyncResult } from '../sync.ts';
import { heldRenameOrigins, holdRefusedImport, moveHeldRenames, noteScreenedImport, settleFullSyncHolds, wouldHoldFields, type LegacyHolds } from './holds.ts';
import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';
+import { classifyItemFailure } from '../../core/item-failure.ts';
+import { OperationError } from '../../core/ops/contract.ts';
export async function performFullSync(
engine: BrainEngine,
@@ -409,8 +411,8 @@ async function reconcileFullSyncDeletes(
// #5988 (E13): the old page of a held rename keeps its origin until the
// renamed file imports; its file being gone does not make it stale.
const heldOrigins = await heldRenameOrigins(engine, sid);
- const rows = (await engine.executeRaw<{ slug: string; source_path: string | null }>(
- `SELECT slug, source_path FROM pages WHERE source_id = $1 AND source_path IS NOT NULL AND deleted_at IS NULL`,
+ const rows = (await engine.executeRaw<{ slug: string; source_path: string | null; body_storage: string }>(
+ `SELECT slug, source_path, body_storage FROM pages WHERE source_id = $1 AND source_path IS NOT NULL AND deleted_at IS NULL`,
[sid],
)).filter(row => !heldOrigins.has(row.source_path!));
// #774: a scoped full sync is authoritative ONLY for its scope — pages
@@ -463,6 +465,7 @@ async function reconcileFullSyncDeletes(
// history (i.e. was genuinely deleted) are reconcile-deleted.
const everCommitted = company ? null : listEverCommittedPaths(gitContextRoot);
const pathBySlug = new Map(rows.map(r => [r.slug, r.source_path]));
+ const segmentedSlugs = new Set(rows.filter(r => r.body_storage === 'segmented').map(r => r.slug));
let deletableSlugs = plan.staleSlugs;
const dbOnlySlugs: string[] = [];
if (everCommitted) {
@@ -475,17 +478,31 @@ async function reconcileFullSyncDeletes(
}
if (dbOnlySlugs.length > 0) {
let reExported = 0;
- try {
- const { writePageThrough } = await import('../../core/write-through.ts');
- for (const slug of dbOnlySlugs) {
- const r = await writePageThrough(engine, slug, { sourceId: sid });
- if (r.written) reExported++;
+ let reExportFailures = 0;
+ const { writePageThrough } = await import('../../core/write-through.ts');
+ for (const slug of dbOnlySlugs) {
+ try {
+ if (segmentedSlugs.has(slug)) throw new OperationError('page_body_segmented', 'Re-export cannot render a segmented page; read it with gbrain get --body auto.');
+ const r = await writePageThrough(engine, slug, { sourceId: sid, expectedFileBytes: null });
+ if (r.written) { reExported++; continue; }
+ if (r.skipped === 'disabled_by_config' || r.skipped === 'url_clone') continue;
+ if (r.skipped === 'file_changed') throw new OperationError('file_database_drift', 'The checkout file exists; re-export only restores absent files.');
+ if (r.error) throw new Error(r.error);
+ throw new OperationError('storage_error', `The page was not re-exported (${r.skipped}).`);
+ } catch (error) {
+ const failure = classifyItemFailure(error);
+ if (failure.scope === 'run') throw error;
+ reExportFailures++;
+ serr(` ${slug} (${failure.code}: ${failure.message}) Kept the database page and any existing file. ` +
+ `If the file is newer, import it with gbrain sync --source ${sid} --include-gitignored; ` +
+ `if the database is newer, re-save its copy with write-through on; when both changed, ask the user which edit wins.`);
}
- } catch { /* best-effort — pages are preserved either way */ }
+ }
serr(
`\n Kept ${dbOnlySlugs.length} page(s) whose markdown was never committed to git ` +
`(DB-only write-through — not deleting).` +
(reExported > 0 ? ` Re-exported ${reExported} of them to the working tree.` : '') +
+ (reExportFailures > 0 ? ` ${reExportFailures} re-export failure(s), listed above.` : '') +
`\n Commit + push them (e.g. scripts/brain-commit-push.sh, or 'gbrain sources harden') ` +
`so the next sync sees them as file-backed.`,
);
diff --git a/src/core/github-source.ts b/src/core/github-source.ts
index b34b094875..c4ea03a5d9 100644
--- a/src/core/github-source.ts
+++ b/src/core/github-source.ts
@@ -48,6 +48,10 @@ import type { SyncOpts } from '../commands/sync.ts';
import { isWriteTargetContained } from './path-confine.ts';
import { createProgress, startHeartbeat } from './progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';
+import { replaceableFile } from './facts/file-body-guard.ts';
+import { assertInlineBody } from './page-body/page-shape.ts';
+import { OperationError } from './ops/contract.ts';
+import { isWriteThroughDisabled } from './write-through.ts';
// ── Types ────────────────────────────────────────────────────────────────────
@@ -965,20 +969,32 @@ async function materializePage(deps: GitHubSyncDeps, filePath: string, content:
const rel = relative(deps.cfg.dir, filePath).replace(/\\/g, '/');
content = connectorRender(content, { path: rel });
if (deps.managed) return deps.managed.importMarkdown(rel, content);
- const created = !existsSync(filePath);
+ const slug = slugifyPath(rel);
+ const existing = await deps.engine.getPage(slug, { sourceId: deps.sourceId });
+ if (existing) assertInlineBody(existing, 'GitHub connector materialization');
+ const databaseOnly = await isWriteThroughDisabled(deps.engine);
+ if (databaseOnly) return { ...await importPage(deps, filePath, activePack, rel, content), created: !existing };
+ const guard = await replaceableFile(deps.engine, deps.sourceId, slug, filePath);
+ const drift = () => new OperationError('file_database_drift',
+ `${slug}: the checkout file has an edit not retained in the database, or changed during import. The file was not replaced. If the file is newer, run gbrain sync --source ${deps.sourceId}; if the database is newer, re-save its page with write-through on; if both changed, ask the user which version to keep before retrying.`);
+ if (!guard.ok) throw drift();
+ const created = guard.expectedFileBytes === null;
mkdirSync(dirname(filePath), { recursive: true });
const tmpPath = `${filePath}.tmp`;
writeFileSync(tmpPath, content, 'utf-8');
try {
const result = await importPage(deps, tmpPath, activePack, rel);
+ const current = existsSync(filePath) ? readFileSync(filePath, 'utf8') : null;
+ if (current !== guard.expectedFileBytes) throw drift();
renameSync(tmpPath, filePath);
return { ...result, created };
} finally { rmSync(tmpPath, { force: true }); }
}
async function storedPage(deps: GitHubSyncDeps, filePath: string, apiUpdatedAt: string) {
- if (!deps.managed) return { fresh: isPageFresh(filePath, apiUpdatedAt), hasDetail: pageHasDetail(filePath), exists: existsSync(filePath) };
- const page = await deps.managed.page(relative(deps.cfg.dir, filePath).replace(/\\/g, '/').replace(/\.md$/, ''));
+ if (!deps.managed && !await isWriteThroughDisabled(deps.engine)) return { fresh: isPageFresh(filePath, apiUpdatedAt), hasDetail: pageHasDetail(filePath), exists: existsSync(filePath) };
+ const slug = relative(deps.cfg.dir, filePath).replace(/\\/g, '/').replace(/\.md$/, '');
+ const page = deps.managed ? await deps.managed.page(slug) : await deps.engine.getPage(slugifyPath(slug), { sourceId: deps.sourceId });
return { exists: !!page, fresh: typeof page?.frontmatter.updated_at === 'string' && page.frontmatter.updated_at >= apiUpdatedAt,
hasDetail: !!page && page.frontmatter.detail_fetched !== false };
}
@@ -988,14 +1004,17 @@ async function importPage(
filePath: string,
activePack: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string> }> } | undefined,
relPathOverride?: string,
+ content?: string,
): Promise<{ slug: string; chunks: number; status: 'imported' | 'skipped' }> {
- const { importFile } = await import('./import-file.ts');
+ const { importFile, importFromContent } = await import('./import-file.ts');
const rel = relPathOverride ?? relative(deps.cfg.dir, filePath).replace(/\\/g, '/');
- const result = await importFile(deps.engine, filePath, rel, {
+ const opts = {
noEmbed: true, // embeddings handled by the size gate below, like sync
sourceId: deps.sourceId,
activePack,
- });
+ };
+ const result = content === undefined ? await importFile(deps.engine, filePath, rel, opts)
+ : await importFromContent(deps.engine, slugifyPath(rel), content, { ...opts, sourcePath: rel, preserveGateMarkers: true });
if (result.status === 'error' || result.error) {
throw new Error(result.error ?? `Import failed for ${rel}`);
}
diff --git a/src/core/google/sweep-shared.ts b/src/core/google/sweep-shared.ts
index f6561fcb1f..9305ac048a 100644
--- a/src/core/google/sweep-shared.ts
+++ b/src/core/google/sweep-shared.ts
@@ -3,7 +3,7 @@
* primitives every Google sweep (contacts, calendar, Gmail) shares. Peeled
* from google-source.ts so the sweeps can live in their own modules.
*/
-import { closeSync, existsSync, fchmodSync, lstatSync, openSync, renameSync, rmSync, unlinkSync, writeSync } from 'node:fs';
+import { closeSync, existsSync, fchmodSync, lstatSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeSync } from 'node:fs';
import { dirname, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
@@ -13,6 +13,11 @@ import type { ManagedConnectorSync } from '../persistence/connector-sync.ts';
import { connectorRender } from '../connectors/connector-text.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { mkdirPrivate } from '../atomic-write.ts';
+import { replaceableFile } from '../facts/file-body-guard.ts';
+import { assertInlineBody } from '../page-body/page-shape.ts';
+import { OperationError } from '../ops/contract.ts';
+import { slugifyPath } from '../sync.ts';
+import { isWriteThroughDisabled } from '../write-through.ts';
import type { GoogleSourceConfig, GoogleSourceState } from './types.ts';
import type { LoopsExclusionPolicy } from './loops-exclusion.ts';
@@ -135,23 +140,40 @@ export async function importRendered(
}
const filePath = join(deps.cfg.dir, relPath);
assertContained(deps.cfg.dir, filePath);
- mkdirPrivate(dirname(filePath), deps.cfg.dir);
- const before = existsSync(filePath);
+ const slug = slugifyPath(relPath);
+ const existing = await deps.engine.getPage(slug, { sourceId: deps.sourceId });
+ if (existing) assertInlineBody(existing, 'Google connector materialization');
+ const databaseOnly = await isWriteThroughDisabled(deps.engine);
+ const guard = databaseOnly ? null : await replaceableFile(deps.engine, deps.sourceId, slug, filePath);
+ const drift = () => new OperationError('file_database_drift',
+ `${slug}: the checkout file has an edit not retained in the database, or changed during import. The file was not replaced. If the file is newer, run gbrain sync --source ${deps.sourceId}; if the database is newer, re-save its page with write-through on; if both changed, ask the user which version to keep before retrying.`);
+ if (guard && !guard.ok) throw drift();
+ const before = databaseOnly ? !!existing : existsSync(filePath);
// Temp-write → import → rename: a failed import never destroys the
// previously-good page (github-source pattern).
const tmpPath = `${filePath}.tmp`;
- writePrivateTemp(tmpPath, markdown);
+ if (!databaseOnly) {
+ mkdirPrivate(dirname(filePath), deps.cfg.dir);
+ writePrivateTemp(tmpPath, markdown);
+ }
try {
- const { importFile } = await import('../import-file.ts');
- const result = await importFile(deps.engine, tmpPath, relPath, {
+ const { importFile, importFromContent } = await import('../import-file.ts');
+ const opts = {
noEmbed: true, // embeds handled by the size gate below, like sync
sourceId: deps.sourceId,
...(activePack ? { activePack } : {}),
- });
+ };
+ const result = databaseOnly
+ ? await importFromContent(deps.engine, slug, markdown, { ...opts, sourcePath: relPath, preserveGateMarkers: true })
+ : await importFile(deps.engine, tmpPath, relPath, opts);
if (result.status === 'error' || result.error) {
throw new Error(result.error ?? `Import failed for ${relPath}`);
}
- renameSync(tmpPath, filePath);
+ if (guard?.ok) {
+ const current = existsSync(filePath) ? readFileSync(filePath, 'utf8') : null;
+ if (current !== guard.expectedFileBytes) throw drift();
+ renameSync(tmpPath, filePath);
+ }
if (result.status === 'imported') {
summary.pagesAffected.push(result.slug);
summary.chunksCreated += result.chunks;
@@ -163,7 +185,7 @@ export async function importRendered(
}
return result.slug;
} finally {
- rmSync(tmpPath, { force: true });
+ if (!databaseOnly) rmSync(tmpPath, { force: true });
}
}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 163ac4bde1..1bfa1a4f21 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -59,13 +59,14 @@ import { warnOncePerProcess, validateSlug, contentHash, contentHashLegacy, ATOMS
import { decorateEmbeddingDimError } from './embedding-dim-check.ts';
import { resolveImportContextualMode } from './import-contextual-mode.ts';
import { runGuardrails } from './guardrails.ts';
-import { fenceBody } from './page-body/page-shape.ts';
+import { fenceBody, pageBodySegmentedError } from './page-body/page-shape.ts';
import { abortSegmentedStaging, bodyStorageOf, demoteSegmentedPage, materializedPage, materializedSnapshot, sealSegmentedPage, stageSegmentedImport,
stringWriteStorage, type SegmentedImport } from './persistence/segmented-apply.ts';
import type { SegmentedStagingOwner } from './page-body/ingest.ts';
import type { PageBodyPolicy } from './page-body/limits.ts';
import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';
import { assertOriginUnclaimed, isOriginClaimRefusal } from './persistence/origin-guard.ts';
+import { fileBodyMatchesStored, readStoredBody } from './facts/file-body-guard.ts';
/**
* #2044 / #4548: row-level, visibility-aware fence merge for one page
@@ -524,12 +525,17 @@ export async function importFromContent(
const originUri = fileOriginUri(existing?.source_uri, opts.sourceRoot, opts.sourcePath);
const persistUnchanged = async (refreshBody = false) => {
- await maintenanceTransaction(engine, async tx => {
+ return maintenanceTransaction(engine, async tx => {
await assertImportBase(tx, slug, sourceId ?? 'default', existing);
- if (refreshBody) await tx.refreshPageBody(slug, sourceId ?? 'default', parsed.compiled_truth, parsed.timeline || '', hash);
+ if (refreshBody) {
+ const stored = await readStoredBody(tx, sourceId ?? 'default', slug, true);
+ if (!stored || !fileBodyMatchesStored(content, slug, stored)) return false;
+ await tx.refreshPageBody(slug, sourceId ?? 'default', parsed.compiled_truth, parsed.timeline || '', hash);
+ }
await refreshSourcePath(tx, slug, sourceId, opts.sourcePath, existing, originUri);
if (opts.beforeCommit) await verifyPageReadable(tx, slug, refreshBody ? hash : existing?.content_hash ?? hash, sourceId, 'importFromContent');
await opts.beforeCommit?.(tx, slug);
+ return true;
});
};
@@ -570,8 +576,8 @@ export async function importFromContent(
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}), ...fences.fields };
}
- if (existing && legacyHashMatch) {
- await persistUnchanged(true);
+ if (existing && legacyHashMatch && bodyStorageOf(existing) === 'segmented') throw pageBodySegmentedError(existing, 'legacy hash reconciliation');
+ if (existing && legacyHashMatch && fileBodyMatchesStored(content, slug, existing) && await persistUnchanged(true)) {
const resealed = await projectionBelowSafeFence(engine, existing.id) ? await resealSafeChunks(engine, slug, sourceId ?? 'default') : null;
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}), ...(resealed ? { resealed } : {}), ...fences.fields };
}
diff --git a/test/pathological/d15-sync-reexport-overwrite.test.ts b/test/pathological/d15-sync-reexport-overwrite.test.ts
new file mode 100644
index 0000000000..1452e2e049
--- /dev/null
+++ b/test/pathological/d15-sync-reexport-overwrite.test.ts
@@ -0,0 +1,181 @@
+/**
+ * D-15 / A-55 (GBRA-131, #6982): full sync only restores absent checkout files.
+ * Protects: ignored or untracked file bytes survive re-export, whether the
+ * database or file is newer; one failed restore is reported without stopping
+ * healthy siblings, while a run-scoped failure still stops the run.
+ * Fails when: re-export omits expectedFileBytes or ignores failed results.
+ * Existing coverage restores an absent file, never an ignored edited one.
+ * Seams: a real full sync and an engine proxy that edits after rendering starts
+ * or fails one read. No production-only seam. PGLite always, Postgres with URL.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { performFullSync } from '../../src/commands/sync/full.ts';
+import { withHumanLineSink } from '../../src/core/console-prefix.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { gitExec } from '../helpers/git-exec.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { segmentPage } from '../helpers/segmented-chunks-fixture.ts';
+import { segmentedPageState } from '../helpers/segmented-page.ts';
+import { expectUnitNotAborted, pathologicalArms } from './harness.ts';
+
+const ALICE = 'memories/alice-example';
+const BOB = 'memories/bob-example';
+
+async function withBrain(databaseUrl: string | undefined, run: (b: {
+ engine: BrainEngine; root: string; file(slug: string): string;
+ body(slug: string): Promise<string>; rendered(slug: string): Promise<string>;
+ sync(on?: BrainEngine): Promise<string[]>;
+}) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d15-'));
+ 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');
+ mkdirSync(join(root, 'memories'), { recursive: true });
+ gitExec('git init', root);
+ writeFileSync(join(root, '.gitignore'), 'memories/\n');
+ gitExec('git add .gitignore && git commit -m fixture', root);
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);
+ await engine.setConfig('sync.repo_path', root);
+ for (const slug of [ALICE, BOB]) {
+ const page = await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\nOriginal synthetic note.` });
+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${slug}.md`, page.id]);
+ }
+ await run({
+ engine, root, file: slug => join(root, `${slug}.md`),
+ 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,
+ rendered: async slug => {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ return serializePageToMarkdown(snapshot.page, snapshot.tags);
+ },
+ async sync(on = engine) {
+ const lines: string[] = [];
+ await withHumanLineSink(line => lines.push(line), () => performFullSync(on,
+ { gitContextRoot: root, syncScopeRoot: root, anchorPath: root, slugRootMode: 'source-root' },
+ gitExec('git rev-parse HEAD', root).trim(), { sourceId: 'default', noEmbed: true, noPull: true }));
+ return lines;
+ },
+ });
+ } finally { await close(); }
+ });
+ } finally { _resetWriteThroughCacheForTest(); rmSync(home, { recursive: true, force: true }); }
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-15 full-sync DB-only file restore (${backend})`, () => {
+ for (const newer of ['database', 'file', 'neither'] as const) {
+ test(`D-15 ${newer} newer: an existing ignored file is held and an absent sibling is restored`, async () => {
+ await withBrain(databaseUrl, async b => {
+ const original = await b.rendered(ALICE);
+ if (newer === 'database') await b.engine.putPage(ALICE, { type: 'note', title: ALICE, compiled_truth: '# Database-only newer edit\n\nPreserve this body.' });
+ const file = newer === 'file' ? `${original}\nUnimported file-only edit.\n` : original;
+ writeFileSync(b.file(ALICE), file);
+ const body = await b.body(ALICE);
+ const sibling = await b.rendered(BOB);
+ const lines = await expectUnitNotAborted(() => b.sync());
+ expect({ file: readFileSync(b.file(ALICE), 'utf8'), body: await b.body(ALICE) }).toEqual({ file, body });
+ expect(readFileSync(b.file(BOB), 'utf8')).toBe(sibling);
+ expect(lines.some(line => line.includes(ALICE) && line.includes('file_database_drift') && line.includes('gbrain sync --source default'))).toBe(true);
+ expect(lines.some(line => line.includes('1 re-export failure'))).toBe(true);
+ });
+ }, 180_000);
+ }
+
+ test('D-15 write-through off: database-only pages never materialize files', async () => {
+ await withBrain(databaseUrl, async b => {
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ const edit = '# Unsynced file-only edit\n';
+ writeFileSync(b.file(ALICE), edit);
+ const bodies = [await b.body(ALICE), await b.body(BOB)];
+ await expectUnitNotAborted(() => b.sync());
+ expect([await b.body(ALICE), await b.body(BOB)]).toEqual(bodies);
+ expect(readFileSync(b.file(ALICE), 'utf8')).toBe(edit);
+ expect(existsSync(b.file(BOB))).toBe(false);
+ });
+ }, 180_000);
+
+ test('D-15 segmented pages are held without mutation while inline siblings restore', async () => {
+ await withBrain(databaseUrl, async b => {
+ const fixture = await segmentPage(b.engine, ALICE, { generation: 1,
+ occurrences: [{ id: 1, byteStart: 0, genFrom: 1, chunks: [{ text: 'Synthetic segmented body.' }] }] });
+ const before = await segmentedPageState(b.engine, fixture.pageId);
+ const lines = await expectUnitNotAborted(() => b.sync());
+ expect(await segmentedPageState(b.engine, fixture.pageId)).toEqual(before);
+ expect(existsSync(b.file(ALICE))).toBe(false);
+ expect(readFileSync(b.file(BOB), 'utf8')).toBe(await b.rendered(BOB));
+ expect(lines.some(line => line.includes(ALICE) && line.includes('page_body_segmented'))).toBe(true);
+ });
+ }, 180_000);
+
+ test('D-15 an editor creates the destination after enumeration: exact bytes survive', async () => {
+ await withBrain(databaseUrl, async b => {
+ const body = await b.body(ALICE);
+ const edit = '# Concurrent file-only edit\n\nPreserve these exact bytes.\n';
+ let landed = false;
+ const racing = new Proxy(b.engine, {
+ get(target, prop) {
+ if (prop === 'getTags') return async (...args: Parameters<BrainEngine['getTags']>) => {
+ if (args[0] === ALICE && !landed) { landed = true; writeFileSync(b.file(ALICE), edit); }
+ return target.getTags(...args);
+ };
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const lines = await expectUnitNotAborted(() => b.sync(racing));
+ expect(landed).toBe(true);
+ expect({ file: readFileSync(b.file(ALICE), 'utf8'), body: await b.body(ALICE) }).toEqual({ file: edit, body });
+ expect(lines.some(line => line.includes(ALICE) && line.includes('file_database_drift'))).toBe(true);
+ expect(existsSync(b.file(BOB))).toBe(true);
+ });
+ }, 180_000);
+
+ test('A-55 one failed render is counted and named, and the next page still re-exports', async () => {
+ await withBrain(databaseUrl, async b => {
+ const body = await b.body(ALICE);
+ const sibling = await b.rendered(BOB);
+ const failing = new Proxy(b.engine, {
+ get(target, prop) {
+ if (prop === 'getPage') return async (...args: Parameters<BrainEngine['getPage']>) => {
+ if (args[0] === ALICE) throw new Error('Synthetic page render failure');
+ return target.getPage(...args);
+ };
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const lines = await expectUnitNotAborted(() => b.sync(failing));
+ expect({ body: await b.body(ALICE), file: existsSync(b.file(ALICE)) }).toEqual({ body, file: false });
+ expect(readFileSync(b.file(BOB), 'utf8')).toBe(sibling);
+ expect(lines.some(line => line.includes(ALICE) && line.includes('internal') && line.includes('gbrain sync --source default'))).toBe(true);
+ expect(lines.some(line => line.includes('1 re-export failure'))).toBe(true);
+ });
+ }, 180_000);
+
+ test('D-15 a run-scoped connection failure is not silently treated as a failed item', async () => {
+ await withBrain(databaseUrl, async b => {
+ const failing = new Proxy(b.engine, {
+ get(target, prop) {
+ if (prop === 'getPage') return async () => { throw new Error('Connection terminated unexpectedly'); };
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const before = await b.body(ALICE);
+ await expect(b.sync(failing)).rejects.toThrow('Connection terminated unexpectedly');
+ expect({ body: await b.body(ALICE), file: existsSync(b.file(ALICE)), sibling: existsSync(b.file(BOB)) })
+ .toEqual({ body: before, file: false, sibling: false });
+ });
+ }, 180_000);
+ });
+}
diff --git a/test/pathological/d16-google-file-replacement.test.ts b/test/pathological/d16-google-file-replacement.test.ts
new file mode 100644
index 0000000000..96fc47cab3
--- /dev/null
+++ b/test/pathological/d16-google-file-replacement.test.ts
@@ -0,0 +1,198 @@
+/**
+ * D-16 (GBRA-131, #6982).
+ * Protects: unmanaged Google materialization preserves checkout-only
+ * edits, including an edit after the replacement comparison, while healthy
+ * contacts still import. A stale file held in page_versions is replaceable;
+ * write-through off imports only to the database, and segmented pages are held.
+ * Fails when: unconditional temp-import-rename destroys an unimported file edit
+ * and ignores sync.write_through. Existing materialization tests cover upstream
+ * changes and import failures, not divergent copies or a late editor write.
+ * Seams: no production seam; real importer and engines, fake Google HTTP, an engine
+ * proxy edits the file when the import transaction starts after temp creation.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { parseGoogleSourceConfig, readGoogleState, runGoogleSync } from '../../src/core/google/google-source.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { contact, json, options, withGoogleAccount } from '../helpers/connector-fixture.ts';
+import { segmentPage } from '../helpers/segmented-chunks-fixture.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.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 SOURCE = 'google-example';
+const BAD = 'people/alice-example';
+const GOOD = 'people/bob-example';
+const EDIT = '\n\nFILE-ONLY-EDIT: café, exact bytes.\r\n';
+const CONFIG = { kind: 'google', g_account: '[email protected]', g_services: 'contacts', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+
+async function withSource(databaseUrl: string | undefined, run: (b: {
+ engine: BrainEngine; root: string; path: string; file(): string;
+ body(slug?: string): Promise<string>; versions(body: string): Promise<number>;
+ sync(engine?: BrainEngine): ReturnType<typeof runGoogleSync>;
+}) => Promise<void>) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-d16-'));
+ try {
+ await withEnv({ GBRAIN_HOME: root, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' }, async () => {
+ _resetWriteThroughCacheForTest();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [SOURCE, root, JSON.stringify(CONFIG)]);
+ let generation = 0;
+ const fetch = withGoogleAccount(async (url: string) => {
+ if (new URL(url).pathname === '/v1/people/me/connections') return json({ connections: [
+ { ...contact('c1', 'Alice Example'), organizations: [{ name: `Upstream ${generation}` }] },
+ { ...contact('c2', 'Bob Example'), organizations: [{ name: `Upstream ${generation}` }] },
+ ], nextSyncToken: `token-${generation}` });
+ throw new Error(`Unexpected Google fixture route: ${url}`);
+ }, CONFIG.g_account);
+ const cfg = parseGoogleSourceConfig(CONFIG, root);
+ const sync = (on = engine) => runGoogleSync(on, SOURCE, cfg, { ...options, sourceId: SOURCE }, fetch);
+ expect((await sync()).failedFiles ?? 0).toBe(0);
+ generation++;
+ const path = join(root, `${BAD}.md`);
+ const body = async (slug = BAD) => (await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]))[0]!.compiled_truth;
+ await run({ engine, root, path, file: () => readFileSync(path, 'utf8'), body, sync,
+ versions: async body => 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=$1 AND p.slug=$2 AND v.compiled_truth=$3', [SOURCE, BAD, body]))[0]!.n) });
+ } finally { await close(); }
+ });
+ } finally { rmSync(root, { recursive: true, force: true }); }
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-16 Google checkout replacement (${backend})`, () => {
+ test('db-newer: a file retained in history is safe to replace and both database preimages survive', async () => {
+ await withSource(databaseUrl, async b => {
+ const old = await b.body();
+ const page = (await b.engine.getPage(BAD, { sourceId: SOURCE }))!;
+ await b.engine.createVersion(BAD, { sourceId: SOURCE });
+ const newer = `${old}\n\nDB-ONLY-EDIT: must survive in history.`;
+ await b.engine.putPage(BAD, { ...page, compiled_truth: newer }, { sourceId: SOURCE });
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles ?? 0).toBe(0);
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(await b.versions(newer)).toBeGreaterThan(0);
+ expect(await b.body()).toContain('Upstream 1');
+ expect(parseMarkdown(b.file(), `${BAD}.md`).compiled_truth).toBe(await b.body());
+ });
+ }, 180_000);
+
+ test('file-newer: exact file and database bytes stay, typed holds count, siblings continue', async () => {
+ await withSource(databaseUrl, async b => {
+ const edited = b.file() + EDIT;
+ writeFileSync(b.path, edited);
+ const body = await b.body();
+ const before = await snapshotItems(b.engine, SOURCE);
+ for (let i = 0; i < 3; i++) {
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles).toBe(1);
+ expect(b.file()).toBe(edited);
+ expect(await b.body()).toBe(body);
+ }
+ const hold = readGoogleState(b.root).item_holds as { items: Record<string, { code: string; state: string; message: string }> };
+ expect(hold.items['contact:people/c1']).toMatchObject({ code: 'file_database_drift', state: 'held' });
+ expect(hold.items['contact:people/c1']!.message).toContain(`gbrain sync --source ${SOURCE}`);
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expectOthersUnchanged(before, await snapshotItems(b.engine, SOURCE), { expectProgress: [GOOD] });
+ });
+ }, 180_000);
+
+ test('late file edit: comparison preimage is checked again immediately before rename', async () => {
+ await withSource(databaseUrl, async b => {
+ const old = await b.body();
+ const edited = b.file() + EDIT;
+ let landed = false;
+ const racing = new Proxy(b.engine, { get(target, prop) {
+ const value = Reflect.get(target, prop, target);
+ if (prop === 'transaction') return (...args: unknown[]) => {
+ if (!landed && existsSync(`${b.path}.tmp`)) { landed = true; writeFileSync(b.path, edited); }
+ return value.apply(target, args);
+ };
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const result = await expectUnitNotAborted(() => b.sync(racing));
+ expect(landed).toBe(true);
+ expect(b.file()).toBe(edited);
+ expect(result.failedFiles).toBe(1);
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(await b.body()).toBe(old.replace('Upstream 0', 'Upstream 1'));
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expect(existsSync(`${b.path}.tmp`)).toBe(false);
+ });
+ }, 180_000);
+
+ test('late database edit: the importer holds or versions the exact newer body, never loses it', async () => {
+ await withSource(databaseUrl, async b => {
+ const old = await b.body();
+ const late = `${old}\n\nLATE-DB-EDIT: keep this exact paragraph.`;
+ const file = b.file();
+ let landed = false;
+ const racing = new Proxy(b.engine, { get(target, prop) {
+ const value = Reflect.get(target, prop, target);
+ if (prop === 'transaction') return async (...args: unknown[]) => {
+ if (!landed && existsSync(`${b.path}.tmp`)) {
+ landed = true;
+ const page = (await b.engine.getPage(BAD, { sourceId: SOURCE }))!;
+ await b.engine.createVersion(BAD, { sourceId: SOURCE });
+ await b.engine.putPage(BAD, { ...page, compiled_truth: late }, { sourceId: SOURCE });
+ }
+ return value.apply(target, args);
+ };
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const result = await expectUnitNotAborted(() => b.sync(racing));
+ expect(landed).toBe(true);
+ expect({ retained: (await b.body()) === late || await b.versions(late) > 0 }).toEqual({ retained: true });
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(result.failedFiles).toBe(1);
+ expect(b.file()).toBe(file);
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ });
+ }, 180_000);
+
+ test('write-through off: database imports continue without writing a divergent or absent file', async () => {
+ await withSource(databaseUrl, async b => {
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ const edited = b.file() + EDIT;
+ writeFileSync(b.path, edited);
+ const old = await b.body();
+ const goodPath = join(b.root, `${GOOD}.md`);
+ rmSync(goodPath);
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles ?? 0).toBe(0);
+ expect(b.file()).toBe(edited);
+ expect(existsSync(goodPath)).toBe(false);
+ expect(await b.body()).toContain('Upstream 1');
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(existsSync(`${b.path}.tmp`)).toBe(false);
+ });
+ }, 180_000);
+
+ test('segmented pages hold without changing either copy; agreeing inline controls import', async () => {
+ await withSource(databaseUrl, async b => {
+ const original = await b.body();
+ const segmented = await segmentPage(b.engine, BAD, { sourceId: SOURCE, generation: 1, bodyBytes: Buffer.byteLength(original),
+ occurrences: [{ id: 1, byteStart: 0, genFrom: 1, chunks: [{ text: original }] }] });
+ const segments = await materializeSegmentedBody(b.engine, segmented.pageId, SOURCE);
+ const file = b.file();
+ const body = await b.body();
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles).toBe(1);
+ expect(b.file()).toBe(file);
+ expect(await b.body()).toBe(body);
+ expect(await materializeSegmentedBody(b.engine, segmented.pageId, SOURCE)).toEqual(segments);
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expect(parseMarkdown(readFileSync(join(b.root, `${GOOD}.md`), 'utf8'), `${GOOD}.md`).compiled_truth).toBe(await b.body(GOOD));
+ });
+ }, 180_000);
+ });
+}
diff --git a/test/pathological/d17-github-file-replacement.test.ts b/test/pathological/d17-github-file-replacement.test.ts
new file mode 100644
index 0000000000..720a0873f2
--- /dev/null
+++ b/test/pathological/d17-github-file-replacement.test.ts
@@ -0,0 +1,202 @@
+/**
+ * D-17 (GBRA-131, #6982).
+ * Protects: unmanaged GitHub materialization preserves checkout-only
+ * edits, including an edit after the replacement comparison, while healthy
+ * items still import. A stale file held in page_versions is replaceable;
+ * write-through off imports only to the database, and segmented pages are held.
+ * Fails when: unconditional temp-import-rename destroys an unimported file edit
+ * and ignores sync.write_through. Existing materialization tests cover upstream
+ * changes and import failures, not divergent copies or a late editor write.
+ * Seams: no production seam; real importer and engines, fake GitHub HTTP, an engine
+ * proxy edits the file when the import transaction starts after temp creation.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { runGitHubSync, type GitHubSourceConfig } from '../../src/core/github-source.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { issueFixture, json, options } from '../helpers/connector-fixture.ts';
+import { segmentPage } from '../helpers/segmented-chunks-fixture.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.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 SOURCE = 'github-example';
+const BAD = 'gh/acme-example/app/1';
+const GOOD = 'gh/acme-example/app/2';
+const EDIT = '\n\nFILE-ONLY-EDIT: café, exact bytes.\r\n';
+const CONFIG = { kind: 'github', gh_scope: 'repos', gh_repos: 'acme-example/app', gh_token_env: 'CONNECTOR_TEST_TOKEN' };
+
+async function withSource(databaseUrl: string | undefined, run: (b: {
+ engine: BrainEngine; root: string; path: string; file(): string;
+ body(slug?: string): Promise<string>; versions(body: string): Promise<number>;
+ sync(engine?: BrainEngine): ReturnType<typeof runGitHubSync>;
+}) => Promise<void>) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-d17-'));
+ try {
+ await withEnv({ GBRAIN_HOME: root, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' }, async () => {
+ _resetWriteThroughCacheForTest();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [SOURCE, root, JSON.stringify(CONFIG)]);
+ let generation = 0;
+ const items = () => [1, 2].map(number => ({ ...issueFixture, number, title: `Item ${number}`, body: `Upstream ${generation}`,
+ updated_at: `2026-01-0${generation + 2}T00:00:00Z` }));
+ const fetch = async (url: string) => {
+ const path = new URL(url).pathname;
+ if (path.endsWith('/issues')) return json(items());
+ if (path.endsWith('/pulls') || path.endsWith('/comments')) return json([]);
+ const match = path.match(/\/issues\/(\d+)$/);
+ if (match) return json(items().find(item => item.number === Number(match[1])));
+ if (path === '/repos/acme-example/app') return json({ full_name: 'acme-example/app', private: true, default_branch: 'main' });
+ throw new Error(`Unexpected GitHub fixture route: ${url}`);
+ };
+ const cfg: GitHubSourceConfig = { tokenEnv: 'CONNECTOR_TEST_TOKEN', app: null, scope: 'repos', repos: ['acme-example/app'], dir: root };
+ const sync = (on = engine) => runGitHubSync(on, SOURCE, cfg, { ...options, sourceId: SOURCE }, fetch);
+ expect((await sync()).failedFiles ?? 0).toBe(0);
+ generation++;
+ const path = join(root, `${BAD}.md`);
+ const body = async (slug = BAD) => (await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]))[0]!.compiled_truth;
+ await run({ engine, root, path, file: () => readFileSync(path, 'utf8'), body, sync,
+ versions: async body => 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=$1 AND p.slug=$2 AND v.compiled_truth=$3', [SOURCE, BAD, body]))[0]!.n) });
+ } finally { await close(); }
+ });
+ } finally { rmSync(root, { recursive: true, force: true }); }
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-17 GitHub checkout replacement (${backend})`, () => {
+ test('db-newer: a file retained in history is safe to replace and both database preimages survive', async () => {
+ await withSource(databaseUrl, async b => {
+ const old = await b.body();
+ const page = (await b.engine.getPage(BAD, { sourceId: SOURCE }))!;
+ await b.engine.createVersion(BAD, { sourceId: SOURCE });
+ const newer = `${old}\n\nDB-ONLY-EDIT: must survive in history.`;
+ await b.engine.putPage(BAD, { ...page, compiled_truth: newer }, { sourceId: SOURCE });
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles ?? 0).toBe(0);
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(await b.versions(newer)).toBeGreaterThan(0);
+ expect(await b.body()).toContain('Upstream 1');
+ expect(parseMarkdown(b.file(), `${BAD}.md`).compiled_truth).toBe(await b.body());
+ });
+ }, 180_000);
+
+ test('file-newer: exact file and database bytes stay, typed holds count, siblings continue', async () => {
+ await withSource(databaseUrl, async b => {
+ const edited = b.file() + EDIT;
+ writeFileSync(b.path, edited);
+ const body = await b.body();
+ const before = await snapshotItems(b.engine, SOURCE);
+ for (let i = 0; i < 3; i++) {
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles).toBe(1);
+ expect(b.file()).toBe(edited);
+ expect(await b.body()).toBe(body);
+ }
+ const hold = JSON.parse(readFileSync(join(b.root, '.github-source.json'), 'utf8')).item_holds as { items: Record<string, { code: string; state: string; message: string }> };
+ expect(hold.items['acme-example/app#1']).toMatchObject({ code: 'file_database_drift', state: 'held' });
+ expect(hold.items['acme-example/app#1']!.message).toContain(`gbrain sync --source ${SOURCE}`);
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expectOthersUnchanged(before, await snapshotItems(b.engine, SOURCE), { expectProgress: [GOOD], changed: ['gh/acme-example/app'] });
+ });
+ }, 180_000);
+
+ test('late file edit: comparison preimage is checked again immediately before rename', async () => {
+ await withSource(databaseUrl, async b => {
+ const old = await b.body();
+ const edited = b.file() + EDIT;
+ let landed = false;
+ const racing = new Proxy(b.engine, { get(target, prop) {
+ const value = Reflect.get(target, prop, target);
+ if (prop === 'transaction') return (...args: unknown[]) => {
+ if (!landed && existsSync(`${b.path}.tmp`)) { landed = true; writeFileSync(b.path, edited); }
+ return value.apply(target, args);
+ };
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const result = await expectUnitNotAborted(() => b.sync(racing));
+ expect(landed).toBe(true);
+ expect(b.file()).toBe(edited);
+ expect(result.failedFiles).toBe(1);
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(await b.body()).toBe(old.replace('Upstream 0', 'Upstream 1'));
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expect(existsSync(`${b.path}.tmp`)).toBe(false);
+ });
+ }, 180_000);
+
+ test('late database edit: the importer holds or versions the exact newer body, never loses it', async () => {
+ await withSource(databaseUrl, async b => {
+ const old = await b.body();
+ const late = `${old}\n\nLATE-DB-EDIT: keep this exact paragraph.`;
+ const file = b.file();
+ let landed = false;
+ const racing = new Proxy(b.engine, { get(target, prop) {
+ const value = Reflect.get(target, prop, target);
+ if (prop === 'transaction') return async (...args: unknown[]) => {
+ if (!landed && existsSync(`${b.path}.tmp`)) {
+ landed = true;
+ const page = (await b.engine.getPage(BAD, { sourceId: SOURCE }))!;
+ await b.engine.createVersion(BAD, { sourceId: SOURCE });
+ await b.engine.putPage(BAD, { ...page, compiled_truth: late }, { sourceId: SOURCE });
+ }
+ return value.apply(target, args);
+ };
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const result = await expectUnitNotAborted(() => b.sync(racing));
+ expect(landed).toBe(true);
+ expect({ retained: (await b.body()) === late || await b.versions(late) > 0 }).toEqual({ retained: true });
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(result.failedFiles).toBe(1);
+ expect(b.file()).toBe(file);
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ });
+ }, 180_000);
+
+ test('write-through off: database imports continue without writing a divergent or absent file', async () => {
+ await withSource(databaseUrl, async b => {
+ await b.engine.setConfig('sync.write_through', 'false');
+ _resetWriteThroughCacheForTest();
+ const edited = b.file().replace(/updated_at: "[^"]+"/, 'updated_at: "2099-01-01T00:00:00Z"') + EDIT;
+ writeFileSync(b.path, edited);
+ const old = await b.body();
+ const goodPath = join(b.root, `${GOOD}.md`);
+ rmSync(goodPath);
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles ?? 0).toBe(0);
+ expect(b.file()).toBe(edited);
+ expect(existsSync(goodPath)).toBe(false);
+ expect(await b.body()).toContain('Upstream 1');
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expect(await b.versions(old)).toBeGreaterThan(0);
+ expect(existsSync(`${b.path}.tmp`)).toBe(false);
+ });
+ }, 180_000);
+
+ test('segmented pages hold without changing either copy; agreeing inline controls import', async () => {
+ await withSource(databaseUrl, async b => {
+ const original = await b.body();
+ const segmented = await segmentPage(b.engine, BAD, { sourceId: SOURCE, generation: 1, bodyBytes: Buffer.byteLength(original),
+ occurrences: [{ id: 1, byteStart: 0, genFrom: 1, chunks: [{ text: original }] }] });
+ const segments = await materializeSegmentedBody(b.engine, segmented.pageId, SOURCE);
+ const file = b.file();
+ const body = await b.body();
+ const result = await expectUnitNotAborted(() => b.sync());
+ expect(result.failedFiles).toBe(1);
+ expect(b.file()).toBe(file);
+ expect(await b.body()).toBe(body);
+ expect(await materializeSegmentedBody(b.engine, segmented.pageId, SOURCE)).toEqual(segments);
+ expect(await b.body(GOOD)).toContain('Upstream 1');
+ expect(parseMarkdown(readFileSync(join(b.root, `${GOOD}.md`), 'utf8'), `${GOOD}.md`).compiled_truth).toBe(await b.body(GOOD));
+ });
+ }, 180_000);
+ });
+}
diff --git a/test/pathological/d21-migration-verifier-record.test.ts b/test/pathological/d21-migration-verifier-record.test.ts
new file mode 100644
index 0000000000..58bde2155b
--- /dev/null
+++ b/test/pathological/d21-migration-verifier-record.test.ts
@@ -0,0 +1,164 @@
+/**
+ * D-21 (GBRA-131).
+ * Protects: migration verification reads the copy of record, not a stale
+ * checkout, for classic database-only pages and write-through-disabled brains.
+ * Fails when: a wrong copy produces false drift or a false complete migration.
+ * Existing migration tests cover managed snapshots and classic files, not this
+ * classic placement matrix. These probes compare all page, fact and history
+ * rows and file bytes before/after: verification must never repair anything.
+ * Seams: no new production seam; proxies inject a snapshot read failure or
+ * order the segmented group before a healthy group to prove continuation.
+ */
+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 { __testing } from '../../src/commands/migrations/v0_32_2.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { renderFactsTable } from '../../src/core/facts-fence.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { createSegmentedPage, segmentedPageState } from '../helpers/segmented-page.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const SLUG = 'private/example';
+const OPTS = { yes: true, dryRun: false, noAutopilotInstall: true };
+const fence = (rowNum: number) => '# Example\n\n' + renderFactsTable([{ rowNum, claim: 'A synthetic claim', kind: 'fact', confidence: 1,
+ visibility: 'private', notability: 'medium', validFrom: '2026-01-01', source: 'manual', active: true }]);
+
+async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine, root: string) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d21-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ _resetWriteThroughCacheForTest();
+ const root = join(home, 'brain');
+ mkdirSync(root);
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await engine.putPage('notes/sibling', { type: 'note', title: 'Sibling', compiled_truth: 'Keep this sibling exactly.' });
+ await run(engine, root);
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+async function seed(engine: BrainEngine, root: string, opts: { db: number; file?: number; origin?: 'path' | 'uri'; segmented?: boolean }) {
+ const { id } = opts.segmented
+ ? await createSegmentedPage(engine, { slug: SLUG, truth: fence(opts.db) })
+ : await engine.putPage(SLUG, { type: 'note', title: 'Example', compiled_truth: fence(opts.db) });
+ if (opts.origin === 'path') await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', ['recorded/example.md', id]);
+ const path = join(root, opts.origin ? 'recorded/example.md' : `${SLUG}.md`);
+ if (opts.origin === 'uri') await engine.executeRaw('UPDATE pages SET source_uri=$1 WHERE id=$2', [`file://${path}`, id]);
+ if (opts.file !== undefined) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, fence(opts.file));
+ }
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence, row_num, source_markdown_slug)
+ VALUES ('default',$1,'A synthetic claim','fact','private','medium','2026-01-01','manual',1,1,$1)`, [SLUG]);
+ return { id, path };
+}
+
+async function state(engine: BrainEngine, path: string) {
+ return { pages: await engine.executeRaw('SELECT * FROM pages ORDER BY id'), facts: await engine.executeRaw('SELECT * FROM facts ORDER BY id'),
+ versions: await engine.executeRaw('SELECT * FROM page_versions ORDER BY id'), file: existsSync(path) ? readFileSync(path, 'utf8') : null };
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-21 classic migration copy of record (${backend})`, () => {
+ for (const mode of ['off', 'declared', 'originless', 'no-root'] as const) {
+ for (const db of [1, 2]) {
+ test(`${mode}: ${db === 1 ? 'accepts the database fence despite a stale file' : 'detects database drift even if the file agrees'}`, async () => {
+ await withBrain(databaseUrl, async (engine, root) => {
+ const f = await seed(engine, root, { db, file: mode === 'off' || mode === 'declared' ? (db === 1 ? 2 : 1) : undefined,
+ origin: mode === 'off' || mode === 'declared' ? 'path' : undefined });
+ if (mode === 'off') await engine.setConfig('sync.write_through', 'off');
+ if (mode === 'declared') writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - private/\n');
+ if (mode === 'no-root') await engine.executeRaw("UPDATE sources SET local_path=NULL WHERE id='default'");
+ const before = await state(engine, f.path);
+ const items = await snapshotItems(engine, 'default');
+ const result = await expectUnitNotAborted(() => __testing.phaseCVerify(engine, OPTS));
+ expect(await state(engine, f.path)).toEqual(before);
+ expectOthersUnchanged(items, await snapshotItems(engine, 'default'));
+ expect(result.status).toBe(db === 1 ? 'complete' : 'failed');
+ expect(result.detail).toBe(db === 1 ? 'pages_checked=1' : `1 pages drifted: ${SLUG} (fence=1, db=1; not indexed: 2; not in fence: 1)`);
+ });
+ }, 180_000);
+ }
+ }
+
+ for (const origin of [undefined, 'path', 'uri'] as const) {
+ test(`write-through on with ${origin ?? 'unrecorded existing'} file: file drift is authoritative`, async () => {
+ await withBrain(databaseUrl, async (engine, root) => {
+ const f = await seed(engine, root, { db: 1, file: 2, origin });
+ const before = await state(engine, f.path);
+ expect(await __testing.phaseCVerify(engine, OPTS)).toMatchObject({ status: 'failed', detail: expect.stringContaining('not indexed: 2; not in fence: 1') });
+ expect(await state(engine, f.path)).toEqual(before);
+ });
+ }, 180_000);
+ }
+
+ for (const origin of ['path', 'uri'] as const) {
+ test(`missing recorded ${origin} is not database-only, but expired rows may skip`, async () => {
+ await withBrain(databaseUrl, async (engine, root) => {
+ const f = await seed(engine, root, { db: 1, origin });
+ const before = await state(engine, f.path);
+ expect(await __testing.phaseCVerify(engine, OPTS)).toEqual({ name: 'verify', status: 'failed', detail: `1 pages drifted: ${SLUG} (file missing)` });
+ expect(await state(engine, f.path)).toEqual(before);
+ await engine.executeRaw('UPDATE facts SET expired_at=now()');
+ const expired = await state(engine, f.path);
+ expect(await __testing.phaseCVerify(engine, OPTS)).toEqual({ name: 'verify', status: 'complete', detail: 'pages_checked=0 skipped_expired_no_page=1' });
+ expect(await state(engine, f.path)).toEqual(expired);
+ });
+ }, 180_000);
+ }
+
+ test('segmented database-only page is held without changing its generation or history', async () => {
+ await withBrain(databaseUrl, async (engine, root) => {
+ const f = await seed(engine, root, { db: 1, segmented: true });
+ await engine.putPage('zz/healthy', { type: 'note', title: 'Healthy', compiled_truth: fence(1) });
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence, row_num, source_markdown_slug)
+ VALUES ('default','zz/healthy','A synthetic claim','fact','private','medium','2026-01-01','manual',1,1,'zz/healthy')`);
+ const before = await state(engine, f.path);
+ const segments = await segmentedPageState(engine, f.id);
+ const checked: string[] = [];
+ const ordered = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ const rows = await target.executeRaw(sql, params);
+ return sql.includes('array_agg(row_num') ? rows.sort((a, b) => String(a.source_markdown_slug).localeCompare(String(b.source_markdown_slug))) : rows;
+ };
+ if (key === 'readPageSnapshot') return async (...args: Parameters<BrainEngine['readPageSnapshot']>) => {
+ checked.push(args[0]);
+ return target.readPageSnapshot(...args);
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ expect(await __testing.phaseCVerify(ordered, OPTS)).toMatchObject({ status: 'failed',
+ detail: expect.stringContaining(`1 pages drifted: ${SLUG} (page_body_segmented:`) });
+ expect(checked).toEqual([SLUG, 'zz/healthy']);
+ expect(await state(engine, f.path)).toEqual(before);
+ expect(await segmentedPageState(engine, f.id)).toEqual(segments);
+ });
+ }, 180_000);
+
+ test('snapshot read failures stop verification without mutation, not a successful zero-page scan', async () => {
+ await withBrain(databaseUrl, async (engine, root) => {
+ const f = await seed(engine, root, { db: 1 });
+ const before = await state(engine, f.path);
+ for (const failure of runScopedErrors()) {
+ let reached = false;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'readPageSnapshot') return async () => { reached = true; throw failure.error(); };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ expect(await __testing.phaseCVerify(proxy, OPTS)).toMatchObject({ status: 'failed' });
+ expect(reached).toBe(true);
+ expect(await state(engine, f.path)).toEqual(before);
+ }
+ });
+ }, 180_000);
+ });
+}
diff --git a/test/pathological/d22-legacy-hash-body-history.test.ts b/test/pathological/d22-legacy-hash-body-history.test.ts
new file mode 100644
index 0000000000..510a9ebcdf
--- /dev/null
+++ b/test/pathological/d22-legacy-hash-body-history.test.ts
@@ -0,0 +1,242 @@
+/**
+ * D-22 (GBRA-131).
+ * Protects: a legacy digest alone cannot authorize an unversioned body
+ * refresh. A database/file divergence must take the normal import path, keeping
+ * the exact old body and timeline in page_versions. Compare actual raw bytes,
+ * not the body after privacy-fence overlays. Existing hash tests cover only an
+ * unchanged body; publication guards cover CAS but not a stale legacy digest
+ * with a sealed projection (otherwise projection rebuilding bypasses the bug).
+ * Fails when: legacy reconcile overwrites a different stored body without
+ * history, compares only the overlaid input, or demotes a segmented page.
+ * Seams: no production seam; a transaction proxy lands competing writes immediately
+ * before publication, and a real segmented page tests the bounded-body refusal.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent, importFromFile } from '../../src/core/import-file.ts';
+import { renderFactsTable } from '../../src/core/facts-fence.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { contentHash, contentHashLegacy } from '../../src/core/utils.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { createSegmentedPage, segmentedPageState } from '../helpers/segmented-page.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { expectOthersUnchanged, pathologicalArms, snapshotItems } from './harness.ts';
+
+const SLUG = 'notes/example';
+const raw = (truth = 'Original synthetic body.', timeline = 'Original synthetic timeline.') =>
+ `---\ntitle: Example\ntype: note\ntags: [example]\n---\n\n${truth}\n\n<!-- timeline -->\n\n${timeline}\n`;
+
+async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine, path: string) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d22-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const root = join(home, 'brain');
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await engine.putPage('notes/sibling', { type: 'note', title: 'Sibling', compiled_truth: 'Keep sibling bytes.' });
+ await run(engine, join(root, `${SLUG}.md`));
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+async function state(engine: BrainEngine) {
+ const snapshot = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });
+ return { snapshot, chunks: await engine.getChunks(SLUG, { sourceId: 'default', includeUnsealed: true }),
+ versions: await engine.executeRaw<{ compiled_truth: string; timeline: string }>('SELECT * FROM page_versions WHERE page_id=$1 ORDER BY id', [snapshot!.page.id]) };
+}
+
+async function legacy(engine: BrainEngine, content: string) {
+ const parsed = parseMarkdown(content, `${SLUG}.md`);
+ await engine.executeRaw("UPDATE pages SET content_hash=$1, text_projection_revision=knowledge_revision WHERE source_id='default' AND slug=$2", [contentHashLegacy(parsed), SLUG]);
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`D-22 legacy hash and preserved import history (${backend})`, () => {
+ for (const field of ['truth', 'timeline', 'both'] as const) {
+ test(`${field} differs behind a stale legacy hash: import versions the exact database preimage`, async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ const incoming = raw();
+ writeFileSync(path, incoming);
+ await importFromFile(engine, path, `${SLUG}.md`, { noEmbed: true, sourceId: 'default' });
+ await engine.executeRaw("UPDATE pages SET compiled_truth=$1, timeline=$2 WHERE source_id='default' AND slug=$3",
+ [field === 'timeline' ? 'Original synthetic body.' : 'DATABASE-ONLY synthetic edit.', field === 'truth' ? 'Original synthetic timeline.' : 'DATABASE-ONLY timeline edit.', SLUG]);
+ await legacy(engine, incoming);
+ const before = await state(engine);
+ const siblings = await snapshotItems(engine, 'default');
+ const result = await importFromFile(engine, path, `${SLUG}.md`, { noEmbed: true, sourceId: 'default' });
+ const after = await state(engine);
+ expect(readFileSync(path, 'utf8')).toBe(incoming);
+ expectOthersUnchanged(siblings, await snapshotItems(engine, 'default'), { changed: [SLUG] });
+ expect(result.status).toBe('imported');
+ expect(after.snapshot!.revision).not.toBe(before.snapshot!.revision);
+ expect(after.snapshot!.page.compiled_truth).toBe('Original synthetic body.');
+ expect(after.snapshot!.page.timeline).toBe('Original synthetic timeline.');
+ expect(after.versions.slice(0, before.versions.length)).toEqual(before.versions);
+ expect(after.versions.slice(before.versions.length)).toMatchObject([{ compiled_truth: before.snapshot!.page.compiled_truth, timeline: before.snapshot!.page.timeline }]);
+ expect(after.snapshot!.tags).toEqual(before.snapshot!.tags);
+ expect((await importFromFile(engine, path, `${SLUG}.md`, { noEmbed: true, sourceId: 'default' })).status).toBe('skipped');
+ expect(await state(engine)).toEqual(after);
+ });
+ }, 180_000);
+ }
+
+ test('agreeing raw body, sanitized NUL and trimmed whitespace: canonical hash upgrade changes no revision, chunks or history', async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ const incoming = raw(' \nOriginal synthetic body.\0\n ');
+ writeFileSync(path, incoming);
+ await importFromFile(engine, path, `${SLUG}.md`, { noEmbed: true, sourceId: 'default' });
+ const stored = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ await engine.executeRaw('UPDATE pages SET content_hash=$1 WHERE id=$2', [contentHashLegacy(stored), stored.id]);
+ const before = await state(engine);
+ expect((await importFromFile(engine, path, `${SLUG}.md`, { noEmbed: true, sourceId: 'default' })).status).toBe('skipped');
+ const after = await state(engine);
+ expect(after.snapshot!.revision).toBe(before.snapshot!.revision);
+ expect(after.snapshot!.page.compiled_truth).toBe(stored.compiled_truth);
+ expect(after.snapshot!.page.timeline).toBe(stored.timeline);
+ expect(after.snapshot!.page.content_hash).toBe(contentHash({ ...stored, tags: ['example'] }));
+ expect(after.chunks).toEqual(before.chunks);
+ expect(after.versions).toEqual(before.versions);
+ expect(readFileSync(path, 'utf8')).toBe(incoming);
+ });
+ }, 180_000);
+
+ for (const column of ['truth', 'timeline'] as const) {
+ test(`raw ${column} lacks a hidden fact restored by privacy overlay: it cannot authorize an unversioned refresh`, async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ const facts = renderFactsTable([{ rowNum: 1, claim: 'A private synthetic claim.', kind: 'fact', confidence: 1,
+ visibility: 'private', notability: 'medium', validFrom: '2026-01-01', source: 'manual', active: true }]);
+ const incoming = raw();
+ const complete = raw(column === 'truth' ? `Original synthetic body.\n\n## Facts\n\n${facts}` : undefined,
+ column === 'timeline' ? `Original synthetic timeline.\n\n## Facts\n\n${facts}` : undefined);
+ await importFromContent(engine, SLUG, complete, { noEmbed: true, sourceId: 'default' });
+ await legacy(engine, complete);
+ writeFileSync(path, incoming);
+ const before = await state(engine);
+ const result = await importFromContent(engine, SLUG, readFileSync(path, 'utf8'), { noEmbed: true, sourceId: 'default', remote: true });
+ const after = await state(engine);
+ expect(result.status).toBe('imported');
+ expect(after.snapshot!.revision).toBe(before.snapshot!.revision);
+ expect(after.snapshot!.page.compiled_truth).toBe(before.snapshot!.page.compiled_truth);
+ expect(after.snapshot!.page.timeline).toBe(before.snapshot!.page.timeline);
+ expect(after.versions.slice(before.versions.length)).toMatchObject([{ compiled_truth: before.snapshot!.page.compiled_truth, timeline: before.snapshot!.page.timeline }]);
+ expect(readFileSync(path, 'utf8')).toBe(incoming);
+ });
+ }, 180_000);
+ }
+
+ for (const diverged of [false, true]) {
+ test(`concurrent database edit before publication (initially diverged=${diverged}) refuses without losing the winner`, async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ writeFileSync(path, raw());
+ await importFromContent(engine, SLUG, raw(), { noEmbed: true, sourceId: 'default' });
+ if (diverged) await engine.executeRaw("UPDATE pages SET compiled_truth='Database preparation preimage.' WHERE slug=$1", [SLUG]);
+ await legacy(engine, raw());
+ let winner: Awaited<ReturnType<typeof state>> | undefined;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'transaction') return async <T>(fn: (tx: BrainEngine) => Promise<T>) => {
+ if (!winner) {
+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ await engine.putPage(SLUG, { type: page.type, title: page.title, frontmatter: page.frontmatter,
+ compiled_truth: 'Concurrent synthetic winner.', timeline: 'Concurrent timeline.' }, { sourceId: 'default' });
+ winner = await state(engine);
+ }
+ return target.transaction(fn);
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ await expect(importFromContent(proxy, SLUG, readFileSync(path, 'utf8'), { noEmbed: true, sourceId: 'default' })).rejects.toMatchObject({ code: 'revision_conflict' });
+ expect(winner).toBeDefined();
+ expect(await state(engine)).toEqual(winner!);
+ expect(readFileSync(path, 'utf8')).toBe(raw());
+ });
+ }, 180_000);
+ }
+
+ test('database edit after the CAS read but before the row lock cannot be overwritten by legacy refresh', async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ writeFileSync(path, raw());
+ await importFromContent(engine, SLUG, raw(), { noEmbed: true, sourceId: 'default' });
+ await legacy(engine, raw());
+ let winner: Awaited<ReturnType<typeof state>> | undefined;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'transaction') return async <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => fn(new Proxy(tx, {
+ get(transaction, member) {
+ if (member === 'getPage') return async (...args: Parameters<BrainEngine['getPage']>) => {
+ const observed = await transaction.getPage(...args);
+ if (!winner && args[0] === SLUG) {
+ await transaction.putPage(SLUG, { type: observed!.type, title: observed!.title, frontmatter: observed!.frontmatter,
+ compiled_truth: 'Winner landed after CAS read.', timeline: 'Winner timeline after CAS read.' }, { sourceId: 'default' });
+ winner = await state(transaction);
+ }
+ return observed;
+ };
+ const value = Reflect.get(transaction, member, transaction);
+ return typeof value === 'function' ? value.bind(transaction) : value;
+ },
+ })));
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ await expect(importFromContent(proxy, SLUG, readFileSync(path, 'utf8'), { noEmbed: true, sourceId: 'default' })).rejects.toMatchObject({ code: 'revision_conflict' });
+ expect(winner).toBeDefined();
+ expect(await state(engine)).toEqual(winner!);
+ expect(readFileSync(path, 'utf8')).toBe(raw());
+ });
+ }, 180_000);
+
+ test('normal versioned import rolls back its preimage, chunks and revision when publication is rejected', async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ await importFromContent(engine, SLUG, raw('Database-only body.'), { noEmbed: true, sourceId: 'default' });
+ await legacy(engine, raw());
+ writeFileSync(path, raw());
+ const before = await state(engine);
+ let versioned = false;
+ await expect(importFromContent(engine, SLUG, raw(), { noEmbed: true, sourceId: 'default', beforeCommit: async tx => {
+ versioned = (await tx.executeRaw('SELECT id FROM page_versions WHERE page_id=$1', [before.snapshot!.page.id])).length === before.versions.length + 1;
+ throw new Error('Synthetic publication refused');
+ } })).rejects.toThrow('Synthetic publication refused');
+ expect(await state(engine)).toEqual(before);
+ expect(versioned).toBe(true);
+ expect(readFileSync(path, 'utf8')).toBe(raw());
+ });
+ }, 180_000);
+
+ test('small materialized segmented page at legacy reconcile is held without demotion or a history write', async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ const { id } = await createSegmentedPage(engine, { slug: SLUG, truth: 'Original synthetic body.', timeline: 'Original synthetic timeline.',
+ meta: { title: 'Example', type: 'note', frontmatter: {} } });
+ await legacy(engine, raw());
+ writeFileSync(path, raw());
+ const before = await segmentedPageState(engine, id);
+ const versions = await engine.executeRaw('SELECT * FROM page_versions WHERE page_id=$1', [id]);
+ await expect(importFromContent(engine, SLUG, raw(), { noEmbed: true, sourceId: 'default' })).rejects.toMatchObject({ code: 'page_body_segmented' });
+ expect(await segmentedPageState(engine, id)).toEqual(before);
+ expect(await engine.executeRaw('SELECT * FROM page_versions WHERE page_id=$1', [id])).toEqual(versions);
+ expect(readFileSync(path, 'utf8')).toBe(raw());
+ });
+ }, 180_000);
+
+ test('segmented page over the whole-body ceiling is held with its manifest and history intact', async () => {
+ await withBrain(databaseUrl, async (engine, path) => {
+ const { id } = await createSegmentedPage(engine, { slug: SLUG, truth: 'Segmented database-only body.' });
+ await engine.executeRaw('UPDATE pages SET body_bytes=$1 WHERE id=$2', [PAGE_MAX_BYTES + 1, id]);
+ await legacy(engine, raw());
+ writeFileSync(path, raw());
+ const before = await segmentedPageState(engine, id);
+ const versions = await engine.executeRaw('SELECT * FROM page_versions WHERE page_id=$1', [id]);
+ await expect(importFromContent(engine, SLUG, raw(), { noEmbed: true, sourceId: 'default' })).rejects.toMatchObject({ code: 'page_body_segmented' });
+ expect(await segmentedPageState(engine, id)).toEqual(before);
+ expect(await engine.executeRaw('SELECT * FROM page_versions WHERE page_id=$1', [id])).toEqual(versions);
+ expect(readFileSync(path, 'utf8')).toBe(raw());
+ });
+ }, 180_000);
+ });
+}
diff --git a/test/pathological/inventory-deferred.test.ts b/test/pathological/inventory-deferred.test.ts
index 9b73c81275..d10c87991f 100644
--- a/test/pathological/inventory-deferred.test.ts
+++ b/test/pathological/inventory-deferred.test.ts
@@ -34,7 +34,6 @@ export const DEFERRED: ReadonlyArray<readonly [string, string, string]> = [
['A-52', 'deferred: next wave (test.todo)', 'Unmanaged extraction (cycle incremental pass and full fs walk)'],
['A-53', 'GBRA-101 (4b)', 'Managed import batches (IMPORT_BATCH_MAX_PAGES) admit every member in one transaction'],
['A-54', 'deferred: next wave (test.todo)', 'One link whose addLink throws on the target (a target page absent for any reason other than a known failed/vanished page, or a link-type constraint...'],
- ['A-55', 'deferred: next wave (test.todo)', 'Full sync re-export of DB-only pages: one try around the loop, so the first writePageThrough throw stops re-export of all remaining pages, silently...'],
['A-56', 'deferred: next wave (test.todo)', 'Legacy facts backstop per page: catch { /* per-page enqueue is best-effort */ } with no counter'],
['A-57', 'GBRA-101 (4b)', 'Managed per-file prepare/screen: loadActivePackForEngine(...).catch(() => null)'],
['A-58', 'deferred: next wave (test.todo)', 'Legacy import, file gone from disk branch: clearLegacyHold is outside any try, so a DB error there escapes importOnePath and aborts the whole drain...'],
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 739dbd70ec..dd4ac6695f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -271,6 +271,11 @@ test/pathological/c2-url-clone-fences.test.ts
test/pathological/c4-bundle-stuck-recovery.test.ts
test/pathological/c5-writer-transfer-cancel.test.ts
test/pathological/c7-content-receipt-root.test.ts
+test/pathological/d15-sync-reexport-overwrite.test.ts
+test/pathological/d16-google-file-replacement.test.ts
+test/pathological/d17-github-file-replacement.test.ts
+test/pathological/d21-migration-verifier-record.test.ts
+test/pathological/d22-legacy-hash-body-history.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts
test/persistence-capacity-forecast.test.ts